How to use the pymc3.plot_posterior function in pymc3

To help you get started, we’ve selected a few pymc3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aloctavodia / Doing_bayesian_data_analysis / 15_SystemsPyMC.py View on Github external
## Plot KDE and sampled values for each parameter.
#pm.traceplot(trace)


## Extract chains
muG_sample = trace['muG']
tauG_sample = trace['tauG']
m_sample = trace['m']
d_sample = trace['d']

# Plot the hyperdistributions:
_, ax = plt.subplots(1, 4, figsize=(20, 5))
pm.plot_posterior(muG_sample, bins=30, ax=ax[0])
ax[0].set_xlabel(r'$\mu_g$', fontsize=16)
pm.plot_posterior(tauG_sample, bins=30 ,ax=ax[1])
ax[1].set_xlabel(r'$\tau_g$', fontsize=16)
pm.plot_posterior(m_sample, bins=30, ax=ax[2])
ax[2].set_xlabel('m', fontsize=16)
pm.plot_posterior(d_sample, bins=30, ax=ax[3])
ax[3].set_xlabel('d', fontsize=16)

plt.tight_layout()
plt.savefig('Figure_15.9.png')
plt.show()
github aloctavodia / Doing_bayesian_data_analysis / 19_ANOVAtwowayPyMC.py View on Github external
plt.savefig('Figure_19.4.png')

## Display contrast analyses
plt.figure(figsize=(10, 12))
count = 1
for key, value in x1contrastDict.items():
    contrast = np.dot(b1_sample, value)
    ax = plt.subplot(3, 2, count)
    pm.plot_posterior(contrast, ref_val=0.0, bins=50, ax=ax)
    ax.set_title('Contrast {}'.format(key))
    count += 1
    
for key, value in x2contrastDict.items():
    contrast = np.dot(b2_sample, value)
    ax = plt.subplot(3, 2, count)
    pm.plot_posterior(contrast, ref_val=0.0, bins=50, ax=ax)
    ax.set_title('Contrast {}'.format(key))
    count += 1
    
for key, value in x1x2contrastDict.items():
    contrast = np.tensordot(b1b2_sample, value)
    ax = plt.subplot(3, 2, count)
    pm.plot_posterior(contrast, ref_val=0.0, bins=50, ax=ax)
    ax.set_title('Contrast {}'.format(key))
    count += 1
plt.tight_layout()
plt.savefig('Figure_19.5.png')

plt.show()
github aloctavodia / Doing_bayesian_data_analysis / 09_BernBetaMuKappaPyMC.py View on Github external
theta3_sample = trace['theta'][:,2]
mu_sample = trace['mu']
kappa_sample = trace['kappa']


# Scatter plot hyper-parameters
fig, ax = plt.subplots(4, 3, figsize=(12,12))
ax[0, 0].scatter(mu_sample, kappa_sample, marker='o', color='skyblue')
ax[0, 0].set_xlim(0,1)
ax[0, 0].set_xlabel(r'$\mu$')
ax[0, 0].set_ylabel(r'$\kappa$')

# Plot mu histogram
#plot_post(mu_sample, xlab=r'$\mu$', show_mode=False, labelsize=9, framealpha=0.5)

pm.plot_posterior(mu_sample, ax=ax[0, 1], color='skyblue')
ax[0, 1].set_xlabel(r'$\mu$')
ax[0, 1].set_xlim(0,1)

# Plot kappa histogram
#plot_post(kappa_sample, xlab=r'$\kappa$', show_mode=False, labelsize=9, framealpha=0.5)
pm.plot_posterior(kappa_sample, ax=ax[0, 2], color='skyblue')
ax[0, 2].set_xlabel(r'$\kappa$')

# Plot theta 1

#plot_post(theta1_sample, xlab=r'$\theta1$', show_mode=False, labelsize=9, framealpha=0.5)
pm.plot_posterior(theta1_sample, ax=ax[1, 0], color='skyblue')
ax[1, 0].set_xlabel(r'$\theta1$')
ax[1, 0].set_xlim(0,1)

# Scatter theta 1 vs mu
github aloctavodia / Doing_bayesian_data_analysis / 09_BernBetaMuKappaPyMC_TT.py View on Github external
## Check for mixing and autocorrelation
pm.autocorrplot(trace, varnames=['mu', 'kappa'])

## Plot KDE and sampled values for each parameter.
pm.traceplot(trace)
#pm.traceplot(trace)

# Create arrays with the posterior sample
theta1_sample = trace['theta'][:,0]
theta28_sample = trace['theta'][:,27]
mu_sample = trace['mu']
kappa_sample = trace['kappa']

# Plot mu histogram
fig, ax = plt.subplots(2, 2, figsize=(12,12))
pm.plot_posterior(mu_sample, ax=ax[0, 0], color='skyblue')
ax[0, 0].set_xlabel(r'$\mu$')

# Plot kappa histogram
pm.plot_posterior(kappa_sample, ax=ax[0, 1], color='skyblue')
ax[0, 1].set_xlabel(r'$\kappa$')

# Plot theta 1
pm.plot_posterior(theta1_sample, ax=ax[1, 0], color='skyblue')
ax[1, 0].set_xlabel(r'$\theta1$')

# Plot theta 28
pm.plot_posterior(theta1_sample, ax=ax[1, 1], color='skyblue')
ax[1, 1].set_xlabel(r'$\theta28$')


plt.tight_layout()
github probml / pyprobml / scripts / pymc3_demo.py View on Github external
print(Rhat)

# Estimate posterior over mu when unclamped
# Bayes rule for Gaussians MLAPA sec 5.6.2
Sigma_post = 1/( 1/Sigma_prior + N/Sigma_x )
xbar = np.mean(x)
mu_post = Sigma_post * (1/Sigma_x * N * xbar + 1/Sigma_prior * mu_prior)

vals = mcmc_samples.get_values('mu')
mu_post_mcmc = np.mean(vals)
Sigma_post_mcmc = np.var(vals)
assert np.isclose(mu_post, mu_post_mcmc, atol=1e-1)
assert np.isclose(Sigma_post, Sigma_post_mcmc, atol=1e-1)


pm.plot_posterior(vi_samples);


B = np.reshape(np.arange(6), (2,3))
a  = np.array([1,2]) # vector
A = np.array[a].T # (2,1) matrix
C = A * B # broadcast across columns
print(C)
github aloctavodia / Doing_bayesian_data_analysis / 19_ANOVAtwowayPyMC.py View on Github external
pm.plot_posterior(b1b2_sample[:,j,i], bins=50, ax=ax)
        ax.set_title('x1: {}, x2: {}'.format(x1names[j], x2names[i]))
        ax.set_xlabel(r'$\beta12_{}{}$'.format(i, j))
        count += 1


plt.tight_layout()
plt.savefig('Figure_19.4.png')

## Display contrast analyses
plt.figure(figsize=(10, 12))
count = 1
for key, value in x1contrastDict.items():
    contrast = np.dot(b1_sample, value)
    ax = plt.subplot(3, 2, count)
    pm.plot_posterior(contrast, ref_val=0.0, bins=50, ax=ax)
    ax.set_title('Contrast {}'.format(key))
    count += 1
    
for key, value in x2contrastDict.items():
    contrast = np.dot(b2_sample, value)
    ax = plt.subplot(3, 2, count)
    pm.plot_posterior(contrast, ref_val=0.0, bins=50, ax=ax)
    ax.set_title('Contrast {}'.format(key))
    count += 1
    
for key, value in x1x2contrastDict.items():
    contrast = np.tensordot(b1b2_sample, value)
    ax = plt.subplot(3, 2, count)
    pm.plot_posterior(contrast, ref_val=0.0, bins=50, ax=ax)
    ax.set_title('Contrast {}'.format(key))
    count += 1
github pymc-devs / pymc3 / pymc3 / examples / censored_data.py View on Github external
def run(n=1500):
    if n == 'short':
        n = 50

    print('Model with no censored data (omniscient)')
    with omniscient_model:
        trace = pm.sample(n)
        pm.plot_posterior(trace[-1000:], varnames=['mu', 'sigma'])
        plt.show()

    print('Imputed censored model')
    with imputed_censored_model:
        trace = pm.sample(n)
        pm.plot_posterior(trace[-1000:], varnames=['mu', 'sigma'])
        plt.show()

    print('Unimputed censored model')
    with unimputed_censored_model:
        trace = pm.sample(n)
        pm.plot_posterior(trace[-1000:], varnames=['mu', 'sigma'])
        plt.show()
github aloctavodia / Doing_bayesian_data_analysis / 16_SimpleLinearRegressionPyMC.py View on Github external
plt.ylabel('Standardized Intercept')
plt.xlabel('Standardized Slope')
plt.subplot(1, 2, 2)
plt.plot(b1[::thin_idx], b0[::thin_idx], 'b.', alpha=0.7)
plt.ylabel('Intercept (ht when wt=0)')
plt.xlabel('Slope (pounds per inch)')
plt.tight_layout()
plt.savefig('Figure_16.4.png')

# Display the posterior of the b1:
plt.figure(figsize=(8, 5))
ax = plt.subplot(1, 2, 1)
pm.plot_posterior(z1, ref_val=0.0, bins=30, ax=ax)
ax.set_xlabel('Standardized slope')
ax = plt.subplot(1, 2, 2)
pm.plot_posterior(b1, ref_val=0.0, bins=30, ax=ax)
ax.set_xlabel('Slope (pounds per inch)')
plt.tight_layout()
plt.savefig('Figure_16.5.png')

# Display data with believable regression lines and posterior predictions.
plt.figure()
# Plot data values:
x_rang = np.max(x) - np.min(x)
y_rang = np.max(y) - np.min(y)
lim_mult = 0.25
x_lim = [np.min(x)-lim_mult*x_rang, np.max(x)+lim_mult*x_rang]
y_lim = [np.min(y)-lim_mult*y_rang, np.max(y)+lim_mult*y_rang]
plt.plot(x, y, 'k.')
plt.title('Data with credible regression lines')
plt.xlabel('X (height in inches)')
plt.ylabel('Y (weight in pounds)')
github aloctavodia / Doing_bayesian_data_analysis / 17_MultipleLinearRegressionPyMC.py View on Github external
columns = ['Sigma y', 'Intercept']
[columns.append('Slope_%s' % i) for i in predictorNames[:n_predictors]]
traces = np.array([Sigma_samp, b0_samp, b_samp[:,0], b_samp[:,1]]).T
df = pd.DataFrame(traces, columns=columns)
sns.set_style('dark')
g = sns.PairGrid(df)
g.map(plt.scatter)
plt.savefig('Figure_17.5b.png')

## Display the posterior:
sns.set_style('darkgrid')

plt.figure(figsize=(16,4))
ax = plt.subplot(1, n_predictors+2, 1)
pm.plot_posterior(Sigma_samp, ax=ax)
ax.set_xlabel(r'$\sigma y$') 
ax = plt.subplot(1, n_predictors+2, 2)
ax = pm.plot_posterior(b0_samp,  ax=ax)
ax.set_xlabel('Intercept')

for i in range(0, n_predictors):
    ax = plt.subplot(1, n_predictors+2, 3+i)
    pm.plot_posterior(b_samp[:,i], ref_val=0, ax=ax)
    ax.set_xlabel('Slope_{}'.format(predictorNames[i]))
plt.tight_layout()
plt.savefig('Figure_17.5a.png')


# Posterior prediction:
# Define matrix for recording posterior predicted y values for each xPostPred.
# One row per xPostPred value, with each row holding random predicted y values.
github aloctavodia / Doing_bayesian_data_analysis / 15_SystemsPyMC.py View on Github external
## Extract chains
muG_sample = trace['muG']
tauG_sample = trace['tauG']
m_sample = trace['m']
d_sample = trace['d']

# Plot the hyperdistributions:
_, ax = plt.subplots(1, 4, figsize=(20, 5))
pm.plot_posterior(muG_sample, bins=30, ax=ax[0])
ax[0].set_xlabel(r'$\mu_g$', fontsize=16)
pm.plot_posterior(tauG_sample, bins=30 ,ax=ax[1])
ax[1].set_xlabel(r'$\tau_g$', fontsize=16)
pm.plot_posterior(m_sample, bins=30, ax=ax[2])
ax[2].set_xlabel('m', fontsize=16)
pm.plot_posterior(d_sample, bins=30, ax=ax[3])
ax[3].set_xlabel('d', fontsize=16)

plt.tight_layout()
plt.savefig('Figure_15.9.png')
plt.show()