Skip to content

Instantly share code, notes, and snippets.

@matsuken92
Last active August 29, 2015 14:27
Show Gist options
  • Save matsuken92/dee584f1a7d3df809683 to your computer and use it in GitHub Desktop.
Save matsuken92/dee584f1a7d3df809683 to your computer and use it in GitHub Desktop.
GLMM : draw graphs of mixture distributions.
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
from matplotlib import animation as ani
plt.style.use('ggplot')
plt.rc('text', usetex=True)
n = 10000
s = 3
if s != 0:
r = rd.normal(0, s, size=n)
else:
r = np.zeros(n)
def logis(x):
return 1./(1+np.exp(-x))
q = logis(r)
fig = plt.figure(figsize=(9,18))
plt.subplot(311)
xx = np.linspace(-10,10,500)
ytop = 3000
plt.ylim(0,ytop)
plt.xlim(-10,10)
plt.plot(xx, logis(xx)*ytop)
plt.title("Histgram of r. s={0:.3f}".format(s))
plt.hist(r,range=(-10,10), bins=31, color="lightblue")
plt.subplot(312)
plt.xlim(0, 1)
plt.ylim(0, 1700)
plt.xticks(np.linspace(0,1,11))
plt.title("Histgram of q. s={0:.3f}".format(s))
plt.hist(q, color="lightgreen", bins=20)
plt.subplot(313)
res = np.zeros(9)
for f in q:
res += np.array([st.binom.pmf(i, n=9, p=f) for i in range(9)])
plt.title("Sum of binomial histgram with various q. s={0:.3f}".format(s))
plt.bar(range(9), res, width=1, color="blue", alpha=0.5)
plt.show()
# Please see the following page for generating animation graph with Python
# http://qiita.com/kenmatsu4/items/573ca0733b192d919d0e
num_frame = 31
n = 10000
ss = np.array(range(num_frame))/30. * 3
def animate(nframe):
global num_frame
plt.clf()
sys.stdout.write("{}, ".format(nframe))
s = ss[nframe]
if s != 0:
r = rd.normal(0, s, size=n)
else:
r = np.zeros(n)
def logis(x):
return 1./(1+np.exp(-x))
q = logis(r)
plt.subplot(312)
plt.xlim(0, 1)
plt.ylim(0, 1700)
plt.xticks(np.linspace(0,1,11))
plt.title("Histgram of q. s={0:.3f}".format(s))
plt.hist(q, color="lightgreen", bins=20)
plt.subplot(311)
xx = np.linspace(-10,10,500)
ytop = 3000
plt.ylim(0,ytop)
plt.xlim(-10,10)
plt.plot(xx, logis(xx)*ytop)
plt.title("Histgram of r. s={0:.3f}".format(s))
plt.hist(r,range=(-10,10), bins=31, color="lightblue")
plt.subplot(313)
res = np.zeros(9)
for f in q:
res += np.array([st.binom.pmf(i, n=8, p=f) for i in range(9)])
plt.title("Sum of binomial histgram with various q. s={0:.3f}".format(s))
plt.bar(range(9), res, width=1, color="blue", alpha=0.5)
plt.ylim(0,3000)
fig = plt.figure(figsize=(9,18))
anim = ani.FuncAnimation(fig, animate, frames=num_frame, blit=True)
anim.save('mix_poisson_norm.gif', writer='imagemagick', fps=3, dpi=64)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment