Numpy または Scipy (または厳密な Python ライブラリ) で、Python の累積正規分布関数を提供する関数を探しています。
8 に答える
次に例を示します。
>>> from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435
つまり、標準正常間隔の約 95% は、標準平均ゼロを中心として 2 つの標準偏差内にあります。
逆 CDF が必要な場合:
>>> norm.ppf(norm.cdf(1.96))
array(1.9599999999999991)
質問に答えるには遅すぎるかもしれませんが、Google はまだここで人々をリードしているため、ここに私の解決策を書くことにしました。
つまり、Python 2.7 以降、math
ライブラリには error 関数が統合されています。math.erf(x)
このerf()
関数を使用して、累積標準正規分布などの従来の統計関数を計算できます。
from math import *
def phi(x):
#'Cumulative distribution function for the standard normal distribution'
return (1.0 + erf(x / sqrt(2.0))) / 2.0
参照:
https://docs.python.org/2/library/math.html
からPython 3.8
、標準ライブラリはNormalDist
オブジェクトをstatistics
モジュールの一部として提供します。
これを使用して、特定の平均( ) と標準偏差( )の累積分布関数( cdf
- ランダム サンプル X が x 以下になる確率) を取得できます。mu
sigma
from statistics import NormalDist
NormalDist(mu=0, sigma=1).cdf(1.96)
# 0.9750021048517796
これは、標準正規分布(mu = 0
およびsigma = 1
)に対して簡略化できます。
NormalDist().cdf(1.96)
# 0.9750021048517796
NormalDist().cdf(-1.96)
# 0.024997895148220428
ここから適応http://mail.python.org/pipermail/python-list/2000-June/039873.html
from math import *
def erfcc(x):
"""Complementary error function."""
z = abs(x)
t = 1. / (1. + 0.5*z)
r = t * exp(-z*z-1.26551223+t*(1.00002368+t*(.37409196+
t*(.09678418+t*(-.18628806+t*(.27886807+
t*(-1.13520398+t*(1.48851587+t*(-.82215223+
t*.17087277)))))))))
if (x >= 0.):
return r
else:
return 2. - r
def ncdf(x):
return 1. - 0.5*erfcc(x/(2**0.5))
Unknown の例に基づいて構築するには、多くのライブラリで実装されている関数 normdist() に相当する Python は次のようになります。
def normcdf(x, mu, sigma):
t = x-mu;
y = 0.5*erfcc(-t/(sigma*sqrt(2.0)));
if y>1.0:
y = 1.0;
return y
def normpdf(x, mu, sigma):
u = (x-mu)/abs(sigma)
y = (1/(sqrt(2*pi)*abs(sigma)))*exp(-u*u/2)
return y
def normdist(x, mu, sigma, f):
if f:
y = normcdf(x,mu,sigma)
else:
y = normpdf(x,mu,sigma)
return y
Alex's answer は、標準正規分布 (平均 = 0、標準偏差 = 1) のソリューションを示しています。mean
とstd
(つまり)を持つ正規分布がありsqr(var)
、計算したい場合:
from scipy.stats import norm
# cdf(x < val)
print norm.cdf(val, m, s)
# cdf(x > val)
print 1 - norm.cdf(val, m, s)
# cdf(v1 < x < v2)
print norm.cdf(v2, m, s) - norm.cdf(v1, m, s)