Skip to content

Instantly share code, notes, and snippets.

@matsuken92
Last active April 29, 2020 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matsuken92/d15675736e6c384a6bb2 to your computer and use it in GitHub Desktop.
Save matsuken92/d15675736e6c384a6bb2 to your computer and use it in GitHub Desktop.
カイ二乗分布の可視化
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import chi2
from matplotlib import animation as ani
def plot_dist(data, bins, title =""):
plt.figure(figsize=(7,5))
plt.title(title)
plt.hist(data, bins, color="lightgreen", normed=True)
plt.show()
x = np.random.normal(0, 1, 30000)
plot_dist(x,80, "normal distribution.")
def animate(nframe):
k = nframe + 1
plt.ylim(0, 0.6)
plt.plot(x, chi2.pdf(x, df=k))
plt.title("")
plt.title("chi2 dist. k=%d"%k)
n = 10000
r = 0.001
x = np.array([i*r+r for i in range(n)])
fig = plt.figure(figsize=(10,6))
anim = ani.FuncAnimation(fig, animate, frames=10, blit=True)
anim.save('chi2_dist.gif', writer='imagemagick', fps=3, dpi=64)
# 標準正規分布に従う乱数を30,000個生成
x = np.random.normal(0, 1, 30000)
# 生成した乱数を2乗する【【ここがキモ!!!】】
x2 = x**2
# ヒストグラムの描画
plt.figure(figsize=(7,5))
plt.title("chi2 distribution.[k=1]")
plt.hist(x2, 80, color="lightgreen", normed=True)
# 自由度1のカイ二乗分布の描画
xx = np.linspace(0, 25 ,1000)
plt.plot(xx, chi2.pdf(xx, df=1), linewidth=2, color="r")
def animate(nframe):
n = 30000
k = nframe + 1
cum = np.zeros(n)
for i in range(k):
# 標準正規分布に従う乱数を30,000個生成
x = np.random.normal(0, 1, n)
# 生成した乱数を2乗する【ここがキモです!】
x2 = x**2
# 足し合わせた数が自由度となります。
cum += x2
# ヒストグラムの描画
plt.clf()
#plt.figure(figsize=(9,7))
plt.ylim(0, 0.6)
plt.xlim(0, 25)
plt.title("chi2 histgram & pdf [k=%d]"%k)
plt.hist(cum, 80, color="lightgreen", normed=True)
# 自由度1のカイ二乗分布の描画
xx = np.linspace(0, 25 ,1000)
plt.plot(xx, chi2.pdf(xx, df=k), linewidth=2, color="r")
fig = plt.figure(figsize=(10,8))
anim = ani.FuncAnimation(fig, animate, frames=10, blit=True)
anim.save('chi2_hist_dist.gif', writer='imagemagick', fps=1, dpi=64)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment