[python] 누적 정규 분포를 계산하는 방법은 무엇입니까?

Python에서 누적 정규 분포 함수를 제공하는 Numpy 또는 Scipy (또는 엄격한 Python 라이브러리)의 함수를 찾고 있습니다.



답변

예를 들면 다음과 같습니다.

>>> from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435

즉, 표준 정규 구간의 약 95 %는 표준 평균 0을 중심으로 두 표준 편차 내에 있습니다.

역 CDF가 필요한 경우 :

>>> norm.ppf(norm.cdf(1.96))
array(1.9599999999999991)


답변

질문에 답하기에는 너무 늦었을지 모르지만 Google이 여전히 사람들을 여기에서 이끌 기 때문에 여기에 솔루션을 작성하기로 결정했습니다.

즉, Python 2.7부터 math라이브러리는 오류 기능을 통합했습니다.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

오류 함수와 표준 정규 분포 함수는 어떤 관련이 있습니까?


답변

여기 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))


답변

시작 Python 3.8하면 표준 라이브러리 NormalDiststatistics모듈의 일부로 객체를 제공합니다 .

주어진 평균 ( ) 및 표준 편차 ( )에 대해 누적 분포 함수 ( cdf-임의 표본 X가 x보다 작거나 같을 확률) 를 얻는 데 사용할 수 있습니다 .musigma

from statistics import NormalDist

NormalDist(mu=0, sigma=1).cdf(1.96)
# 0.9750021048517796

표준 정규 분포 ( mu = 0sigma = 1)에 대해 단순화 할 수 있습니다 .

NormalDist().cdf(1.96)
# 0.9750021048517796

NormalDist().cdf(-1.96)
# 0.024997895148220428


답변

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의 대답은 표준 정규 분포에 대한 해를 보여줍니다 (평균 = 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 구현 여기 .


답변

위에서 찍은 :

from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435

양측 테스트의 경우 :

Import numpy as np
z = 1.96
p_value = 2 * norm.cdf(-np.abs(z))
0.04999579029644087