내용
정규분포(Normal (Gaussian) Distribution)
정규분포
여러 현상들에 대해 큰 규모의 자료를 조사하면 평균에서 가장 높은 확률을 보이며 그 평균을 중심으로 양쪽으로 같은 정도로 확률 감소를 보이는 종 모양의 형태를 보입니다. 이러한 분포를 정규분포라고 합니다. 특히 큰 규모의 확률변수들의 분포는 그 변수들의 조건에 상관없이 정규분포에 근접하기 때문에 데이터들의 여러 특성들을 연구하는데 중심이 되는 분포입니다
그림 1은 특정기간의 삼성 전자의 주가데이터 중에서 2일간의 종가(Close price) 차이에 대한 것으로 이 데이터에 대한 빈도를 히스토그램(파란색)로, 평균과 분산을 매개변수로 하는 확률밀도함수(PDF)를 (빨간선)를 나타낸 것입니다.
이 데이터의 확률밀도함수는 scipy.stats 모듈의 norm.pdf()
메소드를 사용하여 산출하였습니다.
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import stats from sympy import *
import FinanceDataReader as fdr st=pd.Timestamp(2020,1, 1) et=pd.Timestamp(2022,2,3) data=fdr.DataReader('005930', st, et) close=data["Close"] close.tail(2)
Date | |
---|---|
2022-01-28 | 73300 |
2022-02-03 | 73300 |
Name: Close, dtype: int64 |
clsDiff=close.diff() clsdiff2=np.sort(clsDiff)[:-1] pdf=[stats.norm.pdf(i, clsdiff2.mean(), clsdiff2.std()) for i in clsdiff2] pdf[:3]
[8.900740882409289e-06, 1.1307010944501499e-05, 1.4249121674104278e-05]
plt.figure(dpi=100) plt.hist(clsDiff, bins=30, density=True, alpha=0.3, label='Historam') plt.plot(clsdiff2, pdf, linewidth=2, color="red", label="PDF") plt.xlabel("diff(cost, 2)", size=12, weight='bold') plt.ylabel("Probability, Density", size=12, weight='bold') plt.legend(loc="best") plt.show()
그림 1의 빨간 pdf는 0을 기준으로 양쪽이 대칭인 종모양을 보이는 정규분포곡선으로 간주할 수 있으며 히스토그램의 형태와 거의 일치함을 보입니다.
그 정규분포(빨간선)을 분리하여 나타내면 그림 2와 같으며 이 정규분포의 y 축은 확률(pdf)을 나타내며 가장 높은 지점이 이 분포의 평균이 되고 양쪽이 대칭인 형태를 보입니다. 또한 이 분포의 총 면적은 1이므로 특정 변수 부분의 확률은 평균을 중심으로 계산할 수 있으며 그 역 또한 이 분포로부터 결정할 수 있습니다. 이 분포의 평균, 최빈값, 중앙값이 모두 같습니다.
pct=np.array([0.68, 0.95, 0.99]) point=np.array([]) for i in pct: point=np.append(point, stats.norm.interval(i)) point=np.sort(point) plt.figure(dpi=100) col=["red","green", "orange","green", "red"] lgd=[r"99%,[$-2.58\sigma, 2.58\sigma$]","96%, [$-1.96\sigma, 1.96\sigma$]","68%, [$-\sigma, \sigma$]"] for i in range(1, len(point)): rngx=np.linspace(point[i-1], point[i], 100) if (i-1) in [0, 1, 2]: plt.fill_between(rngx, [stats.norm.pdf(j) for j in rngx], color=col[i-1], label=lgd[i-1]) else: plt.fill_between(rngx, [stats.norm.pdf(j) for j in rngx], color=col[i-1]) plt.xlabel("x", size=12, weight="bold") plt.ylabel("Probability", size=12, weight="bold") plt.legend(loc="best", prop={'weight':'bold', 'size':9}) plt.show()
그림 2와 같이 정규분포는 평균을 기준으로 대칭적인 종 모양의 분포입니다. 이 분포는 평균 μ를 기준으로 표준편차 σ의 배수에 대응되는 확률을 지정할 수 있습니다.
$$\begin{align} &\mu \pm \sigma = 0.68\\&\mu \pm 1.96\sigma = 0.95\\ &\mu \pm 2.56\sigma = 0.99 \end{align}$$결과적으로 정규분포에서 평균은 분포의 중심 위치(location)을 나타내며 분산은 퍼짐(dispersion)의 정도를 의미하는 수치입니다.
전체 데이터(모집단)의 일부에서 다양한 표본들을 생성할 수 있으며 각 표본의 평균들에 대한 분포를 표본분포라고 합니다. 표본분포에서 표본 평균의 수가 증가하면 그 변수는 정규분포에 부합합니다. 이러한 현상을 중심극한정리(Central Limit Theorem, CLT)라는 하며 이 정리를 사용하여 분포를 특정할 수 없는 다양한 자료들의 통계분석의 근거를 제공할 수 있습니다. 즉, 그림 3과 같이 CLT에 의해 실제 데이터들로부터의 표집된 표본들에 대한 평균들의 분포를 정규분포로 가정할 수 있으므로 선형회귀, 분산분석 등 다양한 추론 통계를 실행할 수 있습니다.
np.random.seed(1) x=np.random.randn(51) np.random.seed(2) x1=np.random.randn(1000)
plt.figure(dpi=100) X=[x, x1] lbl=["(a) sample size=51", "(b) sample size=1000"] for n, i in enumerate(X): plt.subplot(1, 2, n+1) plt.hist(i, bins=30, density=True, rwidth=0.6) rng=np.linspace(i.min(), i.max(), 100) plt.plot(rng, [stats.norm.pdf(j) for j in rng], linewidth=2) plt.xlabel("x", size=12, weight="bold") plt.title(lbl[n], size=12, weight="bold") if n==0: plt.ylabel("Probability", size=12, weight="bold") plt.show()
그림 4와 같이 정규분포의 전체적인 형상은 평균과 분산에 의해 결정됩니다. 즉, 정규분포의 모수(parameter)는 평균과 분산이 됩니다.
mu=[0, 3, 5, 7] sig=[1, 1.5, 2, 2.5] x_mu={} y_mu={} x_sig={} y_sig={} for i in range(4): x_mu[mu[i]]=np.sort(stats.norm.rvs(loc=mu[i], size=100)) y_mu[mu[i]]=np.array([stats.norm.pdf(j, loc=mu[i]) for j in x_mu[mu[i]]]) x_sig[sig[i]]=np.sort(stats.norm.rvs(scale=sig[i], size=1000)) y_sig[sig[i]]=np.array([stats.norm.pdf(j, scale=sig[i]) for j in x_sig[sig[i]]])
plt.figure(dpi=150) plt.subplot(1,2,1) for i in mu: plt.plot(x_mu[i], y_mu[i], label=r"$\mu=$"+str(i)) plt.legend(loc="best", prop={"weight":"bold", "size":8}) plt.xlabel("x", size=12, weight="bold") plt.ylabel("Probability", size=12, weight="bold") plt.subplot(1,2,2) for i in sig: plt.plot(x_sig[i], y_sig[i], label=r"$\sigma=$"+str(i)) plt.legend(loc="best", prop={"weight":"bold", "size":8}) plt.xlabel("x", size=12, weight="bold") plt.show()
확률변수 X의 확률밀도 함수가 모수(parameter) 평균(μ)와 분산(σ2)을 가진 정규분포는 다음과 같이 나타냅니다.
이 분포의 확률밀도함수(pdf)는 식 1과 같습니다.
$$\begin{equation}\tag{1} f(x)=\frac{1}{\sqrt{2\pi \sigma}}\exp(-\frac{(x-\mu)^2}{2\sigma^2}), \quad -\infty \lt x \lt \infty \end{equation}$$정규분포를 따르는 변수는 식 2와 같이 표준화(standardization)하여 평균 0, 분산 1인 새로운 변수 Z으로 변환할 수 있습니다.
$$\begin{equation}\tag{2} Z=\frac{X-\mu_x}{\sigma_x} \end{equation}$$정규분포를 따르는 모든 자료는 위와 같이 변환할 수 있으며 이 분포에서 평균과 분산은 고정된 값으로 다양한 통계분석에서 사용됩니다. 이러한 분포를 표준정규분포(Standard Normal Distribution)라 하며 식 3과 같이 나타내며 PDF 역시 위에서 나타낸 정규분포 PDF에 비해 간략해 집니다.
$$\begin{align}\tag{3} &Z \sim N(0, 1)\\ & f(z) = \frac{1}{\sqrt{2 \pi}}\exp(-\frac{z^2}{2}), \quad z \in \mathbb{R} \end{align}$$정규분포를 따르는 확률변수는 scipy.stats 모듈의 zscore()
함수를 사용하여 의 표준화 할 수 있습니다. 또한 표준화는 sklearn.preprocessing 모듈의 StandardScaler()
클래스를 적용할 수 있습니다.
위 표준정규분포의 평균과 분산은 각각 0, 1입니다. 그 통계량은 기대값과 분산의 정의를 사용하여 확인해 볼 수 있습니다.
z=symbols('z', real=True) f=1/sqrt(2*pi)*exp(-z**2/2) E=integrate(z*f, (z, -oo, oo)) E
0
Ex2=integrate(z**2*f, (z, -oo, oo)) Ex2
1
var=Ex2-E**2 var
1
정규분포의 pdf는 stats.norm.pdf(x, loc=0, scale=1)
메소드에 의해 계산할 수 있습니다. 이 메소드에서 x는 확률변수값이고 loc와 scale은 각각 평균과 표준편차를 나타냅니다. 표준정규분포의 경우 평균과 표준편차는 0 과 1로서 이 메소드의 기본값입니다.
다음은 표준정규분포의 곡선을 나타낸 것으로 평균 0을 기준으로 대칭이 됨을 나타냅니다.
plt.figure(dpi=100) x=[stats.norm.pdf(i) for i in np.linspace(-5, 5, 100)] plt.plot(np.linspace(-5, 5, 100), x, label="N(0, 1)") plt.xlabel("x", fontsize="15", fontweight="bold") plt.ylabel("f(x)", fontsize="15", fontweight="bold") plt.axvline(x=0, color="red", linestyle="--", label="mean") plt.legend(loc="best") plt.show()
누적분포함수(CDF)
누적분포함수는 지정한 범위에서의 확률밀도함수들의 합으로 정의됩니다. 그러므로 연속변수의 경우 식 4와 같이 계산됩니다. 일반적으로 표준정규분포의 CDF의 F(x)를 Φ(x) 으로 나타냅니다.
$$\begin{aligned} F(x)&=\Phi(x)\\&=P(Z\le x)\\&=\frac{1}{\sqrt{2}}\int^x_{-\infty} \exp(-\frac{x^2}{2})\,dx \end{aligned}$$식 4의 오차함수(error function, erf), Φ(x),는 다음과 같이 정의됩니다.
$$\Phi(x)=\frac{1}{2} \left(1+\text{erf}\left(\frac{x}{\sqrt{2}}\right)\right)$$누적분포함수는 다음의 조건들을 모두 만족해야 합니다.
- $\displaystyle \lim_{x \to \infty}=1, \; \lim_{x \to -\infty}=0$
- $\displaystyle \Phi(0) = \frac{1}{2}$
- $\displaystyle \Phi(-x)=1-\Phi(x), \quad x \in \mathbb{R}$
표준정규분포와 정규분포는 단지 데이터의 수치적 변경에 의한 것으로 본질적으로는 동일한 형태를 나타내므로 정규분포 변수 X의 PDF, CDF는 표준정규분포에서 z을 x로 대치하는 것으로 산출할 수 있습니다.
예)
X ∼ N(-10, 4)의 분포에 대해 다음의 확률들을 정규분포에서 계산하고 그들을 변환된 표준정규분포에서 계산해봅니다.
- P(X < 0)
- P(-7 < X < 3)
- P(X > -3 | X > -5)
이 정규분포에 대한 표준 정규분포는 다음과 같습니다.
plt.figure(dpi=100) rng=np.linspace(-25, 5, 1000) p=[stats.norm.pdf(i, -10, 4) for i in rng] plt.plot(rng, p, label="N(-10, 4)") rngZ=(rng-(-10))/np.sqrt(4) pZ=[stats.norm.pdf(i) for i in rngZ] plt.plot(rngZ, pZ, label="N(0, 1)") plt.title(r'Normal Distribution $\rightarrow$ Standard Normal Distribution', fontsize="12", fontweight="bold") plt.xlabel("x", fontsize="15", fontweight="bold") plt.ylabel("f(x)", fontsize="15", fontweight="bold") plt.legend(loc="best") plt.show()
1) $\displaystyle P(X \lt 0)=P(Z \lt \frac{0-(-10)}{2})$
mu=-10 var=4 cf=stats.norm.cdf(0, mu, np.sqrt(var)) cf
0.9999997133484281
cfS=stats.norm.cdf((0-mu)/np.sqrt(var)) #표준정규분포 cfS
0.9999997133484281
2) $\displaystyle P(-7 \lt X \lt 3)=P(\frac{-7-(-10)}{2} \lt Z \lt \frac{3-(-10)}{2})$
mu=-10 var=4 cf=stats.norm.cdf(3, mu, np.sqrt(var))-stats.norm.cdf(-7, mu, np.sqrt(var)) cf
0.0668072012286981
#표준정규분포 cfS=stats.norm.cdf((3-mu)/np.sqrt(var))-stats.norm.cdf((-7-mu)/np.sqrt(var)) cfS
0.0668072012286981
3) 조건부확률입니다.
$$\begin{align} P(X \gt -3 | X \gt -5)&=\frac{P(X \gt -3, X \gt -5)}{P(X \gt -5)}\\ &=\frac{P(X \gt -3)}{P(X \gt -5)}\\&=\frac{1-P(X \le -3)}{1-P(X \le -5)}\end{align}$$위 식과 같이 전체에서 누적확률을 제외하는 결과는 생존확률(survival provability)라고 하며 scipy.stats 모듈의 각 분포 클래스의 sf()
메서드를 적용하여 계산할 수 있습니다.
mu=-10 var=4 cf=(1-stats.norm.cdf(-3, mu, np.sqrt(var)))/(1-stats.norm.cdf(-5, mu, np.sqrt(var))) cf
0.03746241815479215
survivalf=stats.norm.sf(-3, mu, np.sqrt(var))/stats.norm.sf(-5, mu, np.sqrt(var)) survivalf
0.03746241815478989
cfS=(1-stats.norm.cdf((-3-mu)/np.sqrt(var)))/(1-stats.norm.cdf((-5-mu)/np.sqrt(var))) cfS
0.03746241815479215
survivalf=stats.norm.sf((-3-mu)/np.sqrt(var))/stats.norm.sf((-5-mu)/np.sqrt(var)) survivalf
0.03746241815478989
정규분포를 표준정규분포로 변환하는 것은 원시자료(raw data)의 선형변환에 의해 새로운 변수를 생성하는 것입니다. 같은 방법으로 확률 변수 X를 aX+b로 선형변환하여 생성한 다른 변수 Y의 평균과 분산은 다음과 같이 계산할 수 있습니다.
$$\begin{align} &X \sim N(\mu_x, \sigma^2_x)\\ &Y=aX+b, \quad a, b \in \mathbb{R}\\ &\mu_y=a \mu_x+b\\ & \sigma^2_y=a^2\sigma^2_x\\ &Y \sim N(a\mu_x+b, a^2\sigma^2_x) \end{align}$$예)
두 회사 주가의 일간변화율 X, Y를 확률변수로 하는 정규분포는 다음과 같이 나타냅니다.
서로 독립이라는 가정하에서 다음을 결정합니다.
1) 두 확률변수들의 결합분포 Z에대해 P(Z > 0.7)? $$\begin{align} &Z=X+Y\\ &\begin{aligned} E(Z)&=E(X)+E(Y)\\&=0.18+0.33\\&=0.51\\ Var(Z)&=Var(X)+Var(Y)\\&=4.43+11.5\\&=15.93 \end{aligned}\\ &Z \sim N(0.51, 15.93) \end{align}$$
muz=0.18+0.33 varz=4.43+11.5 pthan07=stats.norm.sf(0.7, muz, np.sqrt(varz)) round(pthan07, 4)
0.481
2) Y-X가 0.03이상일 확률?
P(Y-X > 0.3)으로 나타내며 새로운 결합확률변수 Z=Y-X에 대해 계산합니다.
mux=0.18; muy=0.33 varx=4.43; vary=11.5 pthan03=stats.norm.sf(0.3, muy-mux, np.sqrt(vary-var)) round(pthan03, 4)
0.4782
댓글
댓글 쓰기