python类infty()的实例源码

_testing.py 文件源码 项目:mpnum 作者: dseuss 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def assert_mpa_identical(mpa1, mpa2, decimal=np.infty):
    """Verify that two MPAs are complety identical
    """
    assert len(mpa1) == len(mpa2)
    assert mpa1.canonical_form == mpa2.canonical_form
    assert mpa1.dtype == mpa2.dtype

    for i, lten1, lten2 in zip(it.count(), mpa1.lt, mpa2.lt):
        if decimal is np.infty:
            assert_array_equal(lten1, lten2,
                               err_msg='mismatch in lten {}'.format(i))
        else:
            assert_array_almost_equal(lten1, lten2, decimal=decimal,
                                      err_msg='mismatch in lten {}'.format(i))
    # TODO: We should make a comprehensive comparison between `mpa1`
    # and `mpa2`.  Are we missing other things?
da.py 文件源码 项目:POT 作者: rflamary 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def __init__(self, reg_e=1., max_iter=1000,
                 tol=10e-9, verbose=False, log=False,
                 metric="sqeuclidean", norm=None,
                 distribution_estimation=distribution_estimation_uniform,
                 out_of_sample_map='ferradans', limit_max=np.infty):

        self.reg_e = reg_e
        self.max_iter = max_iter
        self.tol = tol
        self.verbose = verbose
        self.log = log
        self.metric = metric
        self.norm = norm
        self.limit_max = limit_max
        self.distribution_estimation = distribution_estimation
        self.out_of_sample_map = out_of_sample_map
da.py 文件源码 项目:POT 作者: rflamary 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def __init__(self, reg_e=1., reg_cl=0.1,
                 max_iter=10, max_inner_iter=200,
                 tol=10e-9, verbose=False,
                 metric="sqeuclidean", norm=None,
                 distribution_estimation=distribution_estimation_uniform,
                 out_of_sample_map='ferradans', limit_max=np.infty):

        self.reg_e = reg_e
        self.reg_cl = reg_cl
        self.max_iter = max_iter
        self.max_inner_iter = max_inner_iter
        self.tol = tol
        self.verbose = verbose
        self.metric = metric
        self.norm = norm
        self.distribution_estimation = distribution_estimation
        self.out_of_sample_map = out_of_sample_map
        self.limit_max = limit_max
gmm.py 文件源码 项目:cupy 作者: cupy 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def train_gmm(X, max_iter, tol, means, covariances):
    xp = cupy.get_array_module(X)
    lower_bound = -np.infty
    converged = False
    weights = xp.array([0.5, 0.5], dtype=np.float32)
    inv_cov = 1 / xp.sqrt(covariances)

    for n_iter in six.moves.range(max_iter):
        prev_lower_bound = lower_bound
        log_prob_norm, log_resp = e_step(X, inv_cov, means, weights)
        weights, means, covariances = m_step(X, xp.exp(log_resp))
        inv_cov = 1 / xp.sqrt(covariances)
        lower_bound = log_prob_norm
        change = lower_bound - prev_lower_bound
        if abs(change) < tol:
            converged = True
            break

    if not converged:
        print('Failed to converge. Increase max-iter or tol.')

    return inv_cov, means, weights, covariances
dtopotools_horiz_okada_and_1d.py 文件源码 项目:finite_volume_seismic_model 作者: cjvogl 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def containing_rect(self):
        r"""Find containing rectangle of fault in x-y plane.

        Returns tuple of x-limits and y-limits.

        """

        extent = [numpy.infty, -numpy.infty, numpy.infty, -numpy.infty]
        for subfault in self.subfaults:
            for corner in subfault.corners:
                extent[0] = min(corner[0], extent[0])
                extent[1] = max(corner[0], extent[1])
                extent[2] = min(corner[1], extent[2])
                extent[3] = max(corner[1], extent[3])

        return extent
dtopotools_horiz_okada_and_1d.py 文件源码 项目:finite_volume_seismic_model 作者: cjvogl 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def containing_rect(self):
        r"""Find containing rectangle of fault in x-y plane.

        Returns tuple of x-limits and y-limits.

        """

        extent = [numpy.infty, -numpy.infty, numpy.infty, -numpy.infty]
        for subfault in self.subfaults:
            for corner in subfault.corners:
                extent[0] = min(corner[0], extent[0])
                extent[1] = max(corner[0], extent[1])
                extent[2] = min(corner[1], extent[2])
                extent[3] = max(corner[1], extent[3])

        return extent
acousticModelTraining.py 文件源码 项目:jingjuSingingPhraseMatching 作者: ronggong 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def bicGMMModelSelection(X):
    '''
    bic model selection
    :param X: features - observation * dimension
    :return:
    '''
    lowest_bic = np.infty
    bic = []
    n_components_range  = [10,15,20,25,30,35,40,45,50,55,60,65,70]
    best_n_components   = n_components_range[0]
    for n_components in n_components_range:
        # Fit a Gaussian mixture with EM
        print 'Fitting GMM with n_components =',str(n_components)
        gmm = mixture.GaussianMixture(n_components=n_components,
                                      covariance_type='diag')
        gmm.fit(X)
        bic.append(gmm.bic(X))
        if bic[-1] < lowest_bic:
            lowest_bic = bic[-1]
            best_n_components = n_components
            best_gmm          = gmm

    return best_n_components,gmm
ad_helpme.py 文件源码 项目:bates_galaxies_lab 作者: aleksds 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def chivecfn(theta):
    """A version of lnprobfn that returns the simple uncertainty 
    normalized residual instead of the log-posterior, for use with 
    least-squares optimization methods like Levenburg-Marquardt.
    """
    lnp_prior = model.prior_product(theta)
    if not np.isfinite(lnp_prior):
        return -np.infty

    # Generate mean model
    t1 = time.time()
    try:
        spec, phot, x = model.mean_model(theta, obs, sps=sps)
    except(ValueError):
        return -np.infty
    d1 = time.time() - t1

    chispec = chi_spec(spec, obs)
    chiphot = chi_phot(phot, obs)
    return np.concatenate([chispec, chiphot])
ad_helpme_params.py 文件源码 项目:bates_galaxies_lab 作者: aleksds 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def chivecfn(theta):
    """A version of lnprobfn that returns the simple uncertainty 
    normalized residual instead of the log-posterior, for use with 
    least-squares optimization methods like Levenburg-Marquardt.
    """
    lnp_prior = model.prior_product(theta)
    if not np.isfinite(lnp_prior):
        return -np.infty

    # Generate mean model
    t1 = time.time()
    try:
        spec, phot, x = model.mean_model(theta, obs, sps=sps)
    except(ValueError):
        return -np.infty
    d1 = time.time() - t1

    chispec = chi_spec(spec, obs)
    chiphot = chi_phot(phot, obs)
    return np.concatenate([chispec, chiphot])
sg_helpme_params.py 文件源码 项目:bates_galaxies_lab 作者: aleksds 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def chivecfn(theta):
            """A version of lnprobfn that returns the simple uncertainty 
            normalized residual instead of the log-posterior, for use with 
            least-squares optimization methods like Levenburg-Marquardt.
            """
            lnp_prior = model.prior_product(theta)
            if not np.isfinite(lnp_prior):
                return -np.infty

            # Generate mean model
            t1 = time.time()
            try:
                spec, phot, x = model.mean_model(theta, obs, sps=sps)
            except(ValueError):
                return -np.infty
            d1 = time.time() - t1

            chispec = chi_spec(spec, obs)
            chiphot = chi_phot(phot, obs)
            return np.concatenate([chispec, chiphot])

        ###
prospect_by_galaxy_uvis.py 文件源码 项目:bates_galaxies_lab 作者: aleksds 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def chivecfn(theta):
            """A version of lnprobfn that returns the simple uncertainty 
            normalized residual instead of the log-posterior, for use with 
            least-squares optimization methods like Levenburg-Marquardt.
            """
            lnp_prior = model.prior_product(theta)
            if not np.isfinite(lnp_prior):
                return -np.infty

            # Generate mean model
            t1 = time.time()
            try:
                spec, phot, x = model.mean_model(theta, obs, sps=sps)
            except(ValueError):
                return -np.infty
            d1 = time.time() - t1

            chispec = chi_spec(spec, obs)
            chiphot = chi_phot(phot, obs)
            return np.concatenate([chispec, chiphot])

        ###
helpme.py 文件源码 项目:bates_galaxies_lab 作者: aleksds 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def chivecfn(theta):
    """A version of lnprobfn that returns the simple uncertainty 
    normalized residual instead of the log-posterior, for use with 
    least-squares optimization methods like Levenburg-Marquardt.
    """
    lnp_prior = model.prior_product(theta)
    if not np.isfinite(lnp_prior):
        return -np.infty

    # Generate mean model
    t1 = time.time()
    try:
        spec, phot, x = model.mean_model(theta, obs, sps=sps)
    except(ValueError):
        return -np.infty
    d1 = time.time() - t1

    chispec = chi_spec(spec, obs)
    chiphot = chi_phot(phot, obs)
    return np.concatenate([chispec, chiphot])
ad_prospect_by_galaxy_uvis.py 文件源码 项目:bates_galaxies_lab 作者: aleksds 项目源码 文件源码 阅读 67 收藏 0 点赞 0 评论 0
def chivecfn(theta):
            """A version of lnprobfn that returns the simple uncertainty 
            normalized residual instead of the log-posterior, for use with 
            least-squares optimization methods like Levenburg-Marquardt.
            """
            lnp_prior = model.prior_product(theta)
            if not np.isfinite(lnp_prior):
                return -np.infty

            # Generate mean model
            t1 = time.time()
            try:
                spec, phot, x = model.mean_model(theta, obs, sps=sps)
            except(ValueError):
                return -np.infty
            d1 = time.time() - t1

            chispec = chi_spec(spec, obs)
            chiphot = chi_phot(phot, obs)
            return np.concatenate([chispec, chiphot])

        ###
prospect_by_galaxy.py 文件源码 项目:bates_galaxies_lab 作者: aleksds 项目源码 文件源码 阅读 43 收藏 0 点赞 0 评论 0
def chivecfn(theta):
            """A version of lnprobfn that returns the simple uncertainty 
            normalized residual instead of the log-posterior, for use with 
            least-squares optimization methods like Levenburg-Marquardt.
            """
            lnp_prior = model.prior_product(theta)
            if not np.isfinite(lnp_prior):
                return -np.infty

            # Generate mean model
            t1 = time.time()
            try:
                spec, phot, x = model.mean_model(theta, obs, sps=sps)
            except(ValueError):
                return -np.infty
            d1 = time.time() - t1

            chispec = chi_spec(spec, obs)
            chiphot = chi_phot(phot, obs)
            return np.concatenate([chispec, chiphot])

        ###
tfidf_retrieval.py 文件源码 项目:ADEM 作者: mike-n-7 项目源码 文件源码 阅读 43 收藏 0 点赞 0 评论 0
def sanity_check(test_emb, train_emb, num_test):
    '''
    Sanity check on the cosine similarity calculations
    Finds the closest vector in the space by brute force
    '''
    correct_list = []
    for i in xrange(num_test):
        smallest_norm = np.infty
        index = 0
        for j in xrange(len(train_emb)):
            norm = np.linalg.norm(emb - test_emb[i])
            if norm < smallest_norm:
                smallest_norm = norm
                index = j
        correct_list.append(index)
    # Pad the list to make it the same length as test_emb
    for i in xrange(len(test_emb) - num_test):
        correct_list.append(-1)
    return correct_list
vhred_retrieval.py 文件源码 项目:ADEM 作者: mike-n-7 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def sanity_check(test_emb, train_emb, num_test):
    '''
    Sanity check on the cosine similarity calculations
    Finds the closest vector in the space by brute force
    '''
    correct_list = []
    for i in xrange(num_test):
        smallest_norm = np.infty
        index = 0
        for j in xrange(len(train_emb)):
            norm = np.linalg.norm(emb - test_emb[i])
            if norm < smallest_norm:
                smallest_norm = norm
                index = j
        correct_list.append(index)
    # Pad the list to make it the same length as test_emb
    for i in xrange(len(test_emb) - num_test):
        correct_list.append(-1)
    return correct_list
__init__.py 文件源码 项目:sparsereg 作者: Ohjeah 项目源码 文件源码 阅读 45 收藏 0 点赞 0 评论 0
def crowding_distance(models, *attrs):
    """
    Assumes models in lexicographical sorted.
    """

    get_fit = _get_fit(models, attrs)

    f = np.array(sorted([get_fit(m) for m in models]))

    scale = np.max(f, axis=0) - np.min(f, axis=0)

    with np.errstate(invalid="ignore"):
        dist = np.sum(abs(np.roll(f, 1, axis=0) - np.roll(f, -1, axis=0) ) / scale, axis=1)
    dist[0] = np.infty
    dist[-1] = np.infty
    return dist
decisionboundaryplot.py 文件源码 项目:highdimensional-decision-boundary-plot 作者: tmadl 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _find_decision_boundary_on_hypersphere(self, centroid, R, penalize_known=False):
        def objective(phi, grad=0):
            # search on hypersphere surface in polar coordinates - map back to cartesian
            cx = centroid + polar_to_cartesian(phi, R)
            try:
                cx2d = self.dimensionality_reduction.transform([cx])[0]
                error = self.decision_boundary_distance(cx)
                if penalize_known:
                    # slight penalty for being too close to already known decision boundary
                    # keypoints
                    db_distances = [euclidean(cx2d, self.decision_boundary_points_2d[k])
                                    for k in range(len(self.decision_boundary_points_2d))]
                    error += 1e-8 * ((self.mean_2d_dist - np.min(db_distances)) /
                                     self.mean_2d_dist)**2
                return error
            except (Exception, ex):
                print("Error in objective function:", ex)
                return np.infty

        optimizer = self._get_optimizer(
            D=self.X.shape[1] - 1, upper_bound=2 * np.pi, iteration_budget=self.hypersphere_iteration_budget)
        optimizer.set_min_objective(objective)
        db_phi = optimizer.optimize([rnd.random() * 2 * np.pi for k in range(self.X.shape[1] - 1)])
        db_point = centroid + polar_to_cartesian(db_phi, R)
        return db_point
find_best_match.py 文件源码 项目:CV-lecture-quizzes-python 作者: pdvelez 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def find_best_match(patch, strip):
    # TODO: Find patch in strip and return column index (x value) of topleft corner

    # We will use SSD to find out the best match

    best_id = 0
    min_diff = np.infty

    for i in range(int(strip.shape[1] - patch.shape[1])):
        temp = strip[:, i: i + patch.shape[1]]
        ssd = np.sum((temp - patch) ** 2)
        if ssd < min_diff:
            min_diff = ssd
            best_id = i

    return best_id

# Test code:

# Load images
algorithms.py 文件源码 项目:scikit-cmeans 作者: bm424 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def converge(self, x):
        """Finds cluster centers through an alternating optimization routine.

        Terminates when either the number of cycles reaches `max_iter` or the
        objective function changes by less than `tol`.

        Parameters
        ----------
        x : :obj:`np.ndarray`
            (n_samples, n_features)
            The original data.

        """
        centers = []
        j_new = np.infty
        for i in range(self.max_iter):
            j_old = j_new
            self.update(x)
            centers.append(self.centers)
            j_new = self.objective(x)
            if np.abs(j_old - j_new) < self.tol:
                break
        return np.array(centers)
test_attacks.py 文件源码 项目:cleverhans 作者: tensorflow 项目源码 文件源码 阅读 45 收藏 0 点赞 0 评论 0
def test_generate_np_gives_adversarial_example_linfinity(self):
        self.help_generate_np_gives_adversarial_example(np.infty)
electrostatics.py 文件源码 项目:electrostatics 作者: tomduck 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def E(self, x):  # pylint: disable=invalid-name
        """Electric field vector.
        Ref: http://www.phys.uri.edu/gerhard/PHY204/tsl31.pdf
        """
        x = array(x)
        x1, x2, lam = self.x1, self.x2, self.lam

        # Get lengths and angles for the different triangles
        theta1, theta2 = angle(x, x1, x2), pi - angle(x, x2, x1)
        a = point_line_distance(x, x1, x2)
        r1, r2 = norm(x - x1), norm(x - x2)

        # Calculate the parallel and perpendicular components
        sign = where(is_left(x, x1, x2), 1, -1)

        # pylint: disable=invalid-name
        Epara = lam*(1/r2-1/r1)
        Eperp = -sign*lam*(cos(theta2)-cos(theta1))/where(a == 0, infty, a)

        # Transform into the coordinate space and return
        dx = x2 - x1

        if len(x.shape) == 2:
            Epara = Epara[::, newaxis]
            Eperp = Eperp[::, newaxis]

        return Eperp * (array([-dx[1], dx[0]])/norm(dx)) + Epara * (dx/norm(dx))
rw.py 文件源码 项目:nanopores 作者: mitschabaude 项目源码 文件源码 阅读 41 收藏 0 点赞 0 评论 0
def interpolation(X, Y, extend_to_infty=True):
    if extend_to_infty:
        X = [-np.infty] + X + [np.infty]
        Y = [Y[0]] + Y + [Y[-1]]
    X = np.array(X)
    Y = np.array(Y)
    return lambda x: evaluate_interpolation(x, X, Y)
test_imaging.py 文件源码 项目:algorithm-reference-library 作者: SKA-ScienceDataProcessor 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def test_predict_facets(self):
        self.actualSetUp()
        self.params['facets'] = 2
        self._predict_base(predict_facets, fluxthreshold=numpy.infty)
test_imaging.py 文件源码 项目:algorithm-reference-library 作者: SKA-ScienceDataProcessor 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def test_predict_timeslice(self):
        # This works poorly because of the poor interpolation accuracy for point sources. The corresponding
        # invert works well particularly if the beam sampling is high
        self.actualSetUp()
        self._predict_base(predict_timeslice, fluxthreshold=numpy.infty)
test_imaging.py 文件源码 项目:algorithm-reference-library 作者: SKA-ScienceDataProcessor 项目源码 文件源码 阅读 44 收藏 0 点赞 0 评论 0
def test_predict_timeslice_wprojection(self):
        self.actualSetUp()
        self.params['kernel'] = 'wprojection'
        self.params['wstep'] = 2.0
        self._predict_base(predict_timeslice, fluxthreshold=numpy.infty)
conditions.py 文件源码 项目:pl-cnn 作者: oval-group 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def initialize_run(nnet):

    if nnet.data.dataset_name == 'imagenet':
        nnet.max_passes = 1
        nnet.max_inner_iterations = 5
        nnet.max_outer_iterations = 1
        nnet.epoch = epoch_imagenet

    elif Cfg.store_on_gpu:
        nnet.max_passes = 50
        nnet.max_inner_iterations = 100
        nnet.max_outer_iterations = 1
        nnet.epoch = epoch_full_gpu

        nnet.old_objective = np.infty
        nnet.old_validation_acc = 0.

        performance(nnet, which_set='train', print_=True)

    else:
        nnet.max_passes = 50
        nnet.max_inner_iterations = 100
        nnet.max_outer_iterations = 1
        nnet.epoch = epoch_part_gpu

        nnet.old_objective = np.infty
        nnet.old_validation_acc = 0.

        performance(nnet, which_set='train', print_=True)

    return
chx_generic_functions.py 文件源码 项目:chxanalys 作者: yugangzhang 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def get_series_g2_taus( fra_max_list, acq_time=1, max_fra_num=None, log_taus = True, 
                        num_bufs = 8):
    '''
    Get taus for dose dependent analysis
    Parameters:
        fra_max_list: a list, a lsit of largest available frame number        
        acq_time: acquistion time for each frame
        log_taus: if true, will use the multi-tau defined taus bu using buf_num (default=8),
               otherwise, use deltau =1        
    Return:
        tausd, a dict, with keys as taus_max_list items  
    e.g., 
    get_series_g2_taus( fra_max_list=[20,30,40], acq_time=1, max_fra_num=None, log_taus = True,  num_bufs = 8)
    --> 
    {20: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8, 10, 12, 14, 16]),
     30: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8, 10, 12, 14, 16, 20, 24, 28]),
     40: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8, 10, 12, 14, 16, 20, 24, 28, 32])
    }

    '''
    tausd = {}
    for n in fra_max_list:
        if max_fra_num is not None:
            L = max_fra_num
        else:
            L = np.infty            
        if n>L:
            warnings.warn("Warning: the dose value is too large, and please" 
                          "check the maxium dose in this data set and give a smaller dose value."
                          "We will use the maxium dose of the data.") 
            n = L 
        if log_taus:
            lag_steps = get_multi_tau_lag_steps(n,  num_bufs)
        else:
            lag_steps = np.arange( n )
        tausd[n] = lag_steps * acq_time
    return tausd
wav.py 文件源码 项目:mirapie 作者: Chutlhu 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def wavread(fileName, lmax=np.infty, offset = 0, len_in_smpl = False):
    """reads the wave file file and returns a NDarray and the sampling frequency"""

    def isValid(filename):
        if not fileName:
            return False
        try:
            fileHandle = wave.open(fileName, 'r')
            fileHandle.close()
            return True
        except:
            return False
    if not isValid(fileName):
        print("invalid WAV file. Aborting")
        return None

    # metadata properties of a file
    length, nChans, fs, sampleWidth = wavinfo(fileName)
    if not len_in_smpl:
        lmax = lmax * fs
    length = min(length - offset, lmax)
    waveform = np.zeros((length, nChans))

    # reading data
    fileHandle = wave.open(fileName, 'r')
    fileHandle.setpos(offset)
    batchSizeT = 3000000
    pos = 0
    while pos < length:
        batchSize = min(batchSizeT, length - pos)
        str_bytestream = fileHandle.readframes(int(batchSize*2/sampleWidth))
        tempData = np.fromstring(str_bytestream, 'h')
        tempData = tempData.astype(float)
        tempData = tempData.reshape(batchSize, nChans)
        waveform[pos:pos+batchSize, :] = tempData / float(2**(8*sampleWidth - 1))
        pos += batchSize
    fileHandle.close()
    return (waveform, fs)
norms.py 文件源码 项目:NLP.py 作者: PythonOptimizers 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def norm_infty(x):
    """Compute infinity norm of `x`."""
    if len(x) > 0:
        return norm(x, ord=infty)
    return 0.0


问题


面经


文章

微信
公众号

扫码关注公众号