124

Numpy または Scipy (または厳密な Python ライブラリ) で、Python の累積正規分布関数を提供する関数を探しています。

4

8 に答える 8

149

次に例を示します。

>>> 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)
于 2009-04-30T22:24:02.590 に答える
52

質問に答えるには遅すぎるかもしれませんが、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

https://docs.python.org/3/library/math.html

エラー関数と標準正規分布関数はどのように関連していますか?

于 2015-03-26T07:40:44.443 に答える
39

からPython 3.8、標準ライブラリはNormalDistオブジェクトをstatisticsモジュールの一部として提供します。

これを使用して、特定の平均( ) と標準偏差( )の累積分布関数( cdf- ランダム サンプル X が x 以下になる確率) を取得できます。musigma

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
于 2019-02-28T19:50:14.893 に答える
18

ここから適応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))
于 2009-04-30T22:23:28.830 に答える
17

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
于 2010-08-19T19:35:08.430 に答える
13

Alex's answer は、標準正規分布 (平均 = 0、標準偏差 = 1) のソリューションを示しています。meanstd(つまり)を持つ正規分布があり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)

cdfの詳細についてはこちらを、多くの数式を使用した正規分布の scipy 実装についてはこちらをご覧ください。

于 2015-11-20T10:24:57.540 に答える