統計・確率のお勉強

統計学を中心に色々勉強するブログ

カイ二乗分布の自由度を大きくしていくと同じ平均, 分散の正規分布と変わらなくなる話

カイ二乗分布

カイ二乗分布は大丈夫だと思いますが,  X_i \sim N(0, 1) のとき,

$$
\sum_{i=1}^n X_i^2 \sim \chi_n^2
$$

となります. 自由度 nカイ二乗分布に従うということです.

カイ二乗分布正規分布 N(n, 2n) に近づいていく様子

今回は自由度 n が大きくなるにつれて, カイ二乗分布が同平均, 同分散の正規分布に近づいていく様子をgifアニメ化してみました.

その結果がこちらです.

f:id:doratai:20171116135147g:plain

ここでは, 自由度を1から100まで動かしています. 自由度が大きくなるにつれて正規分布と一致していくのがわかります.

ソースコード

Jupyter 上で動かしました. アニメーションを作成するプログラムではなく, インタラクティブにnの値を変えることができ, そのときのカイ二乗分布(緑の破線)と正規分布(赤の曲線)の密度関数と, カイ二乗分布から得られた乱数をもとに作ったヒストグラムが描画されます.

%matplotlib inline
import matplotlib.pyplot as plt
from ipywidgets import interact
import numpy as np
from scipy.stats import norm, chi2

plt.style.use('ggplot')

bins = 100

@interact(n=(1,200))
def plot_chisquare(n=1):
    np.random.seed(0)
    data = np.random.chisquare(n, 10000)
    
    x = np.linspace(data.min(), data.max(), 1000) 
 
    param = norm.fit(data)
    pdf_fitted = norm.pdf(x, loc=param[0], scale=param[1])
    pdf = chi2.pdf(x,n)
    plt.plot(x, pdf_fitted, 'r-', label='normal pdf')
    plt.plot(x, pdf, 'g--', label='chi2 pdf')
    plt.hist(data, bins, color='pink', density=True)
    if n== 1:
        plt.ylim(0, 1)
    plt.title('Chi-square distribution with n degrees of freedom')
    plt.legend(loc='best')
    plt.show()