當前位置: 首頁>>代碼示例>>Python>>正文


Python special.binom方法代碼示例

本文整理匯總了Python中scipy.special.binom方法的典型用法代碼示例。如果您正苦於以下問題:Python special.binom方法的具體用法?Python special.binom怎麽用?Python special.binom使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在scipy.special的用法示例。


在下文中一共展示了special.binom方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _munp

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def _munp(self, n, beta, m):
        """
        Returns the n-th non-central moment of the crystalball function.
        """
        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) + _norm_pdf_C * _norm_cdf(beta))

        def n_th_moment(n, beta, m):
            """
            Returns n-th moment. Defined only if n+1 < m
            Function cannot broadcast due to the loop over n
            """
            A = (m/beta)**m * np.exp(-beta**2 / 2.0)
            B = m/beta - beta
            rhs = 2**((n-1)/2.0) * sc.gamma((n+1)/2) * (1.0 + (-1)**n * sc.gammainc((n+1)/2, beta**2 / 2))
            lhs = np.zeros(rhs.shape)
            for k in range(n + 1):
                lhs += sc.binom(n, k) * B**(n-k) * (-1)**k / (m - k - 1) * (m/beta)**(-m + k + 1)
            return A * lhs + rhs

        return N * _lazywhere(np.atleast_1d(n + 1 < m),
                              (n, beta, m),
                              np.vectorize(n_th_moment, otypes=[np.float]),
                              np.inf) 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:25,代碼來源:_continuous_distns.py

示例2: mccoy

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def mccoy(mode, op_a, op_b, m, n):
    """ Implement the McCoy formula on two operators of the
    form op_a^m op_b^n.

    Args:
        mode (int): the mode number the two operators act on.
        op_a: the label of operator a. This can be any hashable type.
        op_b: the label of operator b. This can be any hashable type.
        m (int): the power of operator a.
        n (int): the power of operator b.
    """
    new_op = dict()
    for r in range(0, n+1):
        coeff = binom(n, r)/(2**n)
        new_term = tuple([(mode, op_b)]*r + [(mode, op_a)]*m
                         + [(mode, op_b)]*(n-r))
        if new_term not in new_op:
            new_op[tuple(new_term)] = coeff
        else:
            new_op[tuple(new_term)] += coeff
    return new_op 
開發者ID:quantumlib,項目名稱:OpenFermion,代碼行數:23,代碼來源:_weyl_ordering.py

示例3: test_pascal

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def test_pascal(self):
        # Test pascal triangle.
        # Nilpotent exponential, used to trigger a failure (gh-8029)

        for scale in [1.0, 1e-3, 1e-6]:
            for n in range(120):
                A = np.diag(np.arange(1, n + 1), -1) * scale
                B = expm(A)

                sc = scale**np.arange(n, -1, -1)
                if np.any(sc < 1e-300):
                    continue

                got = B
                expected = binom(np.arange(n + 1)[:,None],
                                 np.arange(n + 1)[None,:]) * sc[None,:] / sc[:,None]
                err = abs(expected - got).max()
                atol = 1e-13 * abs(expected).max()
                assert_allclose(got, expected, atol=atol) 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:21,代碼來源:test_matfuncs.py

示例4: _check_n_replications

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def _check_n_replications(self, data_a, data_b):
        """Check if no. replications is sufficient request no. permutations."""
        assert data_a.n_replications == data_b.n_replications, (
                            'Unequal no. replications in the two data sets.')
        n_replications = data_a.n_replications
        if self.settings['stats_type'] == 'dependent':
            if 2**n_replications < self.settings['n_perm_comp']:
                raise RuntimeError('The number of replications {0} in the data'
                                   ' is not sufficient to allow for the '
                                   'requested no. permutations {1}'.format(
                                            n_replications,
                                            self.settings['n_perm_comp']))
        elif self.settings['stats_type'] == 'independent':
            if (binom(2*n_replications, n_replications) <
                    self.settings['n_perm_comp']):
                raise RuntimeError('The number of replications {0} in the data'
                                   ' is not sufficient to allow for the '
                                   'requested no. permutations {1}'.format(
                                                n_replications,
                                                self.settings['n_perm_comp']))
        else:
            raise RuntimeError('Unknown ''stats_type''!') 
開發者ID:pwollstadt,項目名稱:IDTxl,代碼行數:24,代碼來源:network_comparison.py

示例5: _check_n_subjects

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def _check_n_subjects(self, data_set_a, data_set_b):
        """Check if no. subjects is sufficient request no. permutations."""
        if self.settings['stats_type'] == 'dependent':
            assert len(data_set_a) == len(data_set_b), (
                    'The number of data sets is not equal between conditions.')
            n_data_sets = len(data_set_a)
            if 2**n_data_sets < self.settings['n_perm_comp']:
                raise RuntimeError('The number of data sets per condition {0} '
                                   'is not sufficient to enable the '
                                   'requested no. permutations {1}'.format(
                                                n_data_sets,
                                                self.settings['n_perm_comp']))
        elif self.settings['stats_type'] == 'independent':
            max_len = max(len(data_set_a), len(data_set_b))
            total_len = len(data_set_a) + len(data_set_b)
            if binom(total_len, max_len) < self.settings['n_perm_comp']:
                raise RuntimeError('The total number of data sets {0} is not '
                                   'sufficient to enable the requested no. '
                                   'permutations {1}'.format(
                                                total_len,
                                                self.settings['n_perm_comp']))
        else:
            raise RuntimeError('Unknown ''stats_type''!')
        self.settings['n_subjects'] = [len(data_set_a), len(data_set_b)] 
開發者ID:pwollstadt,項目名稱:IDTxl,代碼行數:26,代碼來源:network_comparison.py

示例6: _compute_log_a_int

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def _compute_log_a_int(q, sigma, alpha):
  """Compute log(A_alpha) for integer alpha. 0 < q < 1."""
  assert isinstance(alpha, six.integer_types)

  # Initialize with 0 in the log space.
  log_a = -np.inf

  for i in range(alpha + 1):
    log_coef_i = (
        math.log(special.binom(alpha, i)) + i * math.log(q) +
        (alpha - i) * math.log(1 - q))

    s = log_coef_i + (i * i - i) / (2 * (sigma**2))
    log_a = _log_add(log_a, s)

  return float(log_a) 
開發者ID:tensorflow,項目名稱:privacy,代碼行數:18,代碼來源:rdp_accountant.py

示例7: _compute_log_a_int

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def _compute_log_a_int(q, sigma, alpha):
  """Compute log(A_alpha) for integer alpha. 0 < q < 1."""
  assert isinstance(alpha, (int, long))

  # Initialize with 0 in the log space.
  log_a = -np.inf

  for i in range(alpha + 1):
    log_coef_i = (
        math.log(special.binom(alpha, i)) + i * math.log(q) +
        (alpha - i) * math.log(1 - q))

    s = log_coef_i + (i * i - i) / (2 * (sigma**2))
    log_a = _log_add(log_a, s)

  return float(log_a) 
開發者ID:PipelineAI,項目名稱:models,代碼行數:18,代碼來源:rdp_accountant.py

示例8: _compute_log_a_int

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def _compute_log_a_int(q, sigma, alpha: int):
    """Compute log(A_alpha) for integer alpha. 0 < q < 1."""

    # Initialize with 0 in the log space.
    log_a = -np.inf

    for i in range(alpha + 1):
        log_coef_i = (
            math.log(special.binom(alpha, i))
            + i * math.log(q)
            + (alpha - i) * math.log(1 - q)
        )

        s = log_coef_i + (i * i - i) / (2 * (sigma ** 2))
        log_a = _log_add(log_a, s)

    return float(log_a) 
開發者ID:facebookresearch,項目名稱:pytorch-dp,代碼行數:19,代碼來源:privacy_analysis.py

示例9: check_all_triplets_number

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def check_all_triplets_number(
    labels: List[int], num_selected_tri: int, max_tri: int
) -> None:
    """
    Checks that the selection strategy for all triplets
    returns the correct number of triplets.

    Args:
        labels: list of classes labels
        num_selected_tri: number of selected triplets
        max_tri: limit on the number of selected triplets
    """
    labels_counts = Counter(labels).values()

    n_all_tri = 0
    for count in labels_counts:
        n_pos = binom(count, 2)
        n_neg = len(labels) - count
        n_all_tri += n_pos * n_neg

    assert num_selected_tri == n_all_tri or num_selected_tri == max_tri 
開發者ID:catalyst-team,項目名稱:catalyst,代碼行數:23,代碼來源:test_sampler_inbatch.py

示例10: test_beta_binomial_two_identical_models

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def test_beta_binomial_two_identical_models(db_path, sampler):
    binomial_n = 5

    def model_fun(args):
        return {"result": st.binom(binomial_n, args.theta).rvs()}

    models = [model_fun for _ in range(2)]
    models = list(map(SimpleModel, models))
    population_size = ConstantPopulationSize(800)
    parameter_given_model_prior_distribution = [Distribution(theta=st.beta(
                                                                      1, 1))
                                                for _ in range(2)]
    abc = ABCSMC(models, parameter_given_model_prior_distribution,
                 MinMaxDistance(measures_to_use=["result"]),
                 population_size,
                 eps=MedianEpsilon(.1),
                 sampler=sampler)
    abc.new(db_path, {"result": 2})

    minimum_epsilon = .2
    history = abc.run(minimum_epsilon, max_nr_populations=3)
    mp = history.get_model_probabilities(history.max_t)
    assert abs(mp.p[0] - .5) + abs(mp.p[1] - .5) < .08 
開發者ID:ICB-DCM,項目名稱:pyABC,代碼行數:25,代碼來源:test_abc_smc_algorithm.py

示例11: test_beta_binomial_two_identical_models_adaptive

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def test_beta_binomial_two_identical_models_adaptive(db_path, sampler):
    binomial_n = 5

    def model_fun(args):
        return {"result": st.binom(binomial_n, args.theta).rvs()}

    models = [model_fun for _ in range(2)]
    models = list(map(SimpleModel, models))
    population_size = AdaptivePopulationSize(800)
    parameter_given_model_prior_distribution = [
        Distribution(theta=st.beta(1, 1)) for _ in range(2)]
    abc = ABCSMC(models, parameter_given_model_prior_distribution,
                 MinMaxDistance(measures_to_use=["result"]),
                 population_size,
                 eps=MedianEpsilon(.1),
                 sampler=sampler)
    abc.new(db_path, {"result": 2})

    minimum_epsilon = .2
    history = abc.run(minimum_epsilon, max_nr_populations=3)
    mp = history.get_model_probabilities(history.max_t)
    assert abs(mp.p[0] - .5) + abs(mp.p[1] - .5) < .08 
開發者ID:ICB-DCM,項目名稱:pyABC,代碼行數:24,代碼來源:test_abc_smc_algorithm.py

示例12: _compute_differenced_model_params

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def _compute_differenced_model_params(phi, p, q, d):
    phi_out = []
    for i in range(p + d):
        if q > 1:
            if len(phi[0].shape) == 2:
                phi_out.append(np.zeros((q, q)))
            else:
                phi_out.append(np.zeros(phi[0].shape))
        else:
            phi_out.append(0.0)

    for i in range(1, d + 1):
        if q > 1:
            phi_out[i - 1] -= binom(d, i) * (-1) ** i * np.eye(q)
        else:
            phi_out[i - 1] -= binom(d, i) * (-1) ** i
    for i in range(1, p + 1):
        phi_out[i - 1] += phi[i - 1]
    for i in range(1, p + 1):
        for j in range(1, d + 1):
            phi_out[i + j - 1] += phi[i - 1] * binom(d, j) * (-1) ** j

    return phi_out 
開發者ID:pySTEPS,項目名稱:pysteps,代碼行數:25,代碼來源:autoregression.py

示例13: csp_one_one

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def csp_one_one(cov_matrix,NO_csp,NO_classes):
	'''	
	calculate spatial filter for class all pairs of classes 

	Keyword arguments:
	cov_matrix -- numpy array of size [NO_channels, NO_channels]
	NO_csp -- number of spatial filters (24)

	Return:	spatial filter numpy array of size [22,NO_csp] 
	'''
	N, _ = cov_matrix[0].shape 
	n_comb = binom(NO_classes,2)

	NO_filtpairs = int(NO_csp/(n_comb*2))
	
	w = np.zeros((N,NO_csp))
	
	kk = 0 # internal counter 
	for cc1 in range(0,NO_classes):
		for cc2 in range(cc1+1,NO_classes):
			w[:,NO_filtpairs*2*(kk):NO_filtpairs*2*(kk+1)] = gevd(cov_matrix[cc1], cov_matrix[cc2],NO_filtpairs)
			kk +=1		
	return w 
開發者ID:MultiScale-BCI,項目名稱:IV-2a,代碼行數:25,代碼來源:csp.py

示例14: number_of_points

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def number_of_points(self):
        return int(special.binom(self.n_dim + self.n_partitions - 1, self.n_partitions)) 
開發者ID:msu-coinlab,項目名稱:pymoo,代碼行數:4,代碼來源:das_dennis.py

示例15: get_number_of_uniform_points

# 需要導入模塊: from scipy import special [as 別名]
# 或者: from scipy.special import binom [as 別名]
def get_number_of_uniform_points(n_partitions, n_dim):
    """
    Returns the number of uniform points that can be created uniformly.
    """
    return int(special.binom(n_dim + n_partitions - 1, n_partitions)) 
開發者ID:msu-coinlab,項目名稱:pymoo,代碼行數:7,代碼來源:reference_direction.py


注:本文中的scipy.special.binom方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。