本文整理匯總了Python中scipy.stats.chi2方法的典型用法代碼示例。如果您正苦於以下問題:Python stats.chi2方法的具體用法?Python stats.chi2怎麽用?Python stats.chi2使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類scipy.stats
的用法示例。
在下文中一共展示了stats.chi2方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: setup_class
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def setup_class(cls):
cls.dist_equivalents = [
#transf, stats.lognorm(1))
#The below fails on the SPARC box with scipy 10.1
#(lognormalg, stats.lognorm(1)),
#transf2
(squarenormalg, stats.chi2(1)),
(absnormalg, stats.halfnorm),
(absnormalg, stats.foldnorm(1e-5)), #try frozen
#(negsquarenormalg, 1-stats.chi2), # won't work as distribution
(squaretg(10), stats.f(1, 10))
] #try both frozen
l,s = 0.0, 1.0
cls.ppfq = [0.1,0.5,0.9]
cls.xx = [0.95,1.0,1.1]
cls.nxx = [-0.95,-1.0,-1.1]
示例2: test_equivalent_negsq
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def test_equivalent_negsq(self):
#special case negsquarenormalg
#negsquarenormalg.cdf(x) == stats.chi2(1).cdf(-x), for x<=0
xx, nxx, ppfq = self.xx, self.nxx, self.ppfq
d1,d2 = (negsquarenormalg, stats.chi2(1))
#print d1.name
assert_almost_equal(d1.cdf(nxx), 1-d2.cdf(xx), err_msg='cdf'+d1.name)
assert_almost_equal(d1.pdf(nxx), d2.pdf(xx))
assert_almost_equal(d1.sf(nxx), 1-d2.sf(xx))
assert_almost_equal(d1.ppf(ppfq), -d2.ppf(ppfq)[::-1])
assert_almost_equal(d1.isf(ppfq), -d2.isf(ppfq)[::-1])
assert_almost_equal(d1.moment(3), -d2.moment(3))
ch2oddneg = [v*(-1)**(i+1) for i,v in
enumerate(d2.stats(moments='mvsk'))]
assert_almost_equal(d1.stats(moments='mvsk'), ch2oddneg,
err_msg='stats '+d1.name+d2.name)
示例3: test_whiteness
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def test_whiteness(self, nlags=10, signif=0.05, adjusted=False):
"""
Residual whiteness tests using Portmanteau test
Parameters
----------
nlags : int > 0
signif : float, between 0 and 1
adjusted : bool, default False
Returns
-------
results : WhitenessTestResults
Notes
-----
Test the whiteness of the residuals using the Portmanteau test as
described in [1]_, chapter 4.4.3.
References
----------
.. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
"""
statistic = 0
u = np.asarray(self.resid)
acov_list = _compute_acov(u, nlags)
cov0_inv = scipy.linalg.inv(acov_list[0])
for t in range(1, nlags+1):
ct = acov_list[t]
to_add = np.trace(chain_dot(ct.T, cov0_inv, ct, cov0_inv))
if adjusted:
to_add /= (self.nobs - t)
statistic += to_add
statistic *= self.nobs**2 if adjusted else self.nobs
df = self.neqs**2 * (nlags - self.k_ar)
dist = stats.chi2(df)
pvalue = dist.sf(statistic)
crit_value = dist.ppf(1 - signif)
return WhitenessTestResults(statistic, crit_value, pvalue, df, signif,
nlags, adjusted)
示例4: __init__
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def __init__(self, statistic, distribution, dist_args, table=None,
pvalues=None):
self.table = table
self.distribution = distribution
self.statistic = statistic
#self.sd = sd
self.dist_args = dist_args
# The following is because I don't know which we want
if table is not None:
self.statistic = table['statistic'].values
self.pvalues = table['pvalue'].values
self.df_constraints = table['df_constraint'].values
if self.distribution == 'F':
self.df_denom = table['df_denom'].values
else:
if self.distribution is 'chi2':
self.dist = stats.chi2
self.df_constraints = self.dist_args[0] # assumes tuple
# using dist_args[0] is a bit dangerous,
elif self.distribution is 'F':
self.dist = stats.f
self.df_constraints, self.df_denom = self.dist_args
else:
raise ValueError('only F and chi2 are possible distribution')
if pvalues is None:
self.pvalues = self.dist.sf(np.abs(statistic), *dist_args)
else:
self.pvalues = pvalues
示例5: __init__
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def __init__(self):
self.dist = squarenormalg
self.trargs = ()
self.trkwds = dict(loc=-10, scale=20)
self.statsdist = stats.chi2
self.stargs = (1,)
self.stkwds = dict(loc=-10, scale=20)
示例6: test_squared_normal_chi2
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def test_squared_normal_chi2():
#'\nsquare of standard normal random variable is chisquare with dof=1 distributed'
cdftr = squarenormalg.cdf(xx,loc=l, scale=s)
sfctr = 1-squarenormalg.sf(xx,loc=l, scale=s) #sf complement
cdfst = stats.chi2.cdf(xx,1)
assert_almost_equal(cdfst, cdftr, 14)
assert_almost_equal(cdfst, sfctr, 14)
# print('sqnorm pdf for (%3.2f, %3.2f, %3.2f):' % tuple(xx), squarenormalg.pdf(xx,loc=l, scale=s)
# print('chi2 pdf for (%3.2f, %3.2f, %3.2f):' % tuple(xx), stats.chi2.pdf(xx,1)
# print('sqnorm ppf for (%3.2f, %3.2f, %3.2f):' % tuple(xx), squarenormalg.ppf(ppfq,loc=l, scale=s)
# print('chi2 ppf for (%3.2f, %3.2f, %3.2f):' % tuple(xx), stats.chi2.ppf(ppfq,1)
# print('sqnorm cdf with loc scale', squarenormalg.cdf(xx,loc=-10, scale=20)
# print('chi2 cdf with loc scale', stats.chi2.cdf(xx,1,loc=-10, scale=20)
示例7: correct_covariance
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def correct_covariance(self, data):
"""Apply a correction to raw Minimum Covariance Determinant estimates.
Correction using the empirical correction factor suggested
by Rousseeuw and Van Driessen in [RVD]_.
Parameters
----------
data : array-like, shape (n_samples, n_features)
The data matrix, with p features and n samples.
The data set must be the one which was used to compute
the raw estimates.
References
----------
.. [RVD] A Fast Algorithm for the Minimum Covariance
Determinant Estimator, 1999, American Statistical Association
and the American Society for Quality, TECHNOMETRICS
Returns
-------
covariance_corrected : array-like, shape (n_features, n_features)
Corrected robust covariance estimate.
"""
# Check that the covariance of the support data is not equal to 0.
# Otherwise self.dist_ = 0 and thus correction = 0.
n_samples = len(self.dist_)
n_support = np.sum(self.support_)
if n_support < n_samples and np.allclose(self.raw_covariance_, 0):
raise ValueError('The covariance matrix of the support data '
'is equal to 0, try to increase support_fraction')
correction = np.median(self.dist_) / chi2(data.shape[1]).isf(0.5)
covariance_corrected = self.raw_covariance_ * correction
self.dist_ /= correction
return covariance_corrected
示例8: find_optimal_T_chi2
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def find_optimal_T_chi2(bg_rate, m, P):
"""Returns the min. T so that bg_rate is <= than lower_conf_rate(m,T,P).
This is equivalent but much faster than find_optimal_T_iter().
Note: This is based on the confidence intervall of multiple exponential
"""
T = 0.5*chi2(2*m).ppf(P)/bg_rate
return T
示例9: find_optimal_threshold
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def find_optimal_threshold(m, P):
"""Returns the min. threshold to have prob. < P to be BG (averaging m ph).
Same formula as find_optimal_T() (must be multiplied by bg to have the rate.
"""
return m/(0.5*chi2(2*m).ppf(P))
示例10: setUp_configure
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def setUp_configure(self):
from scipy import stats
self.dist = distributions.Chisquare
self.scipy_dist = stats.chi2
self.test_targets = set([
'batch_shape', 'entropy', 'event_shape', 'log_prob', 'mean',
'sample', 'support', 'variance'])
k = numpy.random.randint(1, 10, self.shape).astype(numpy.float32)
self.params = {'k': k}
self.scipy_params = {'df': k}
self.support = 'positive'
示例11: test_1D_is_chisquared
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def test_1D_is_chisquared(self):
# The 1-dimensional Wishart with an identity scale matrix is just a
# chi-squared distribution.
# Test variance, mean, entropy, pdf
# Kolgomorov-Smirnov test for rvs
np.random.seed(482974)
sn = 500
dim = 1
scale = np.eye(dim)
df_range = np.arange(1, 10, 2, dtype=float)
X = np.linspace(0.1,10,num=10)
for df in df_range:
w = wishart(df, scale)
c = chi2(df)
# Statistics
assert_allclose(w.var(), c.var())
assert_allclose(w.mean(), c.mean())
assert_allclose(w.entropy(), c.entropy())
# PDF
assert_allclose(w.pdf(X), c.pdf(X))
# rvs
rvs = w.rvs(size=sn)
args = (df,)
alpha = 0.01
check_distribution_rvs('chi2', args, alpha, rvs)
示例12: test_is_scaled_chisquared
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def test_is_scaled_chisquared(self):
# The 2-dimensional Wishart with an arbitrary scale matrix can be
# transformed to a scaled chi-squared distribution.
# For :math:`S \sim W_p(V,n)` and :math:`\lambda \in \mathbb{R}^p` we have
# :math:`\lambda' S \lambda \sim \lambda' V \lambda \times \chi^2(n)`
np.random.seed(482974)
sn = 500
df = 10
dim = 4
# Construct an arbitrary positive definite matrix
scale = np.diag(np.arange(4)+1)
scale[np.tril_indices(4, k=-1)] = np.arange(6)
scale = np.dot(scale.T, scale)
# Use :math:`\lambda = [1, \dots, 1]'`
lamda = np.ones((dim,1))
sigma_lamda = lamda.T.dot(scale).dot(lamda).squeeze()
w = wishart(df, sigma_lamda)
c = chi2(df, scale=sigma_lamda)
# Statistics
assert_allclose(w.var(), c.var())
assert_allclose(w.mean(), c.mean())
assert_allclose(w.entropy(), c.entropy())
# PDF
X = np.linspace(0.1,10,num=10)
assert_allclose(w.pdf(X), c.pdf(X))
# rvs
rvs = w.rvs(size=sn)
args = (df,0,sigma_lamda)
alpha = 0.01
check_distribution_rvs('chi2', args, alpha, rvs)
示例13: __init__
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def __init__(self, dofs):
self.dofs = dofs
if self.dofs is not None:
if self.dofs == 1:
self.bounds = np.array([1e-15, np.inf])
else:
self.bounds = np.array([0.0, np.inf])
if self.dofs >= 1:
self.mean = float(self.dofs)
self.variance = 2 * self.mean
self.skewness = np.sqrt(8.0 / self.mean)
self.kurtosis = 12.0/self.mean + 3.0
self.x_range_for_pdf = np.linspace(0.0, 10.0*self.mean,RECURRENCE_PDF_SAMPLES)
self.parent = chi2(self.dofs)
示例14: _lrt_pvalue
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def _lrt_pvalue(logl_H0, logl_H1, dof=1):
from scipy.stats import chi2
from numpy import clip, inf
epsilon = np.finfo(float).tiny
lrs = clip(2 * (logl_H1 - logl_H0), epsilon, inf)
pv = chi2(df=dof).sf(lrs)
return clip(pv, epsilon, 1 - epsilon)
示例15: correct_covariance
# 需要導入模塊: from scipy import stats [as 別名]
# 或者: from scipy.stats import chi2 [as 別名]
def correct_covariance(self, data):
"""Apply a correction to raw Minimum Covariance Determinant estimates.
Correction using the empirical correction factor suggested
by Rousseeuw and Van Driessen in [RVD]_.
Parameters
----------
data : array-like, shape (n_samples, n_features)
The data matrix, with p features and n samples.
The data set must be the one which was used to compute
the raw estimates.
References
----------
.. [RVD] `A Fast Algorithm for the Minimum Covariance
Determinant Estimator, 1999, American Statistical Association
and the American Society for Quality, TECHNOMETRICS`
Returns
-------
covariance_corrected : array-like, shape (n_features, n_features)
Corrected robust covariance estimate.
"""
correction = np.median(self.dist_) / chi2(data.shape[1]).isf(0.5)
covariance_corrected = self.raw_covariance_ * correction
self.dist_ /= correction
return covariance_corrected