y_vals = np.concatenate([drug, placebo])labels = [ 'drug'] * len(drug) + [ 'placebo'] * len(placebo)data = pd.DataFrame([y_vals, labels]).Tdata.columns = [ 'IQ', 'treatment'] withpm.Model() askruschke_model: # Focus on the use of Distribution Objects.# Linking Distribution Objects together is done by # passing objects into other objects' parameters.mu_drug = pm.Normal( 'mu_drug', mu= 0, sd= 100** 2) mu_placebo = pm.Normal( 'mu_placebo', mu= 0, sd= 100** 2) sigma_drug = pm.HalfCauchy( 'sigma_drug', beta= 100) sigma_placebo = pm.HalfCauchy( 'sigma_placebo', beta= 100) nu = pm.Exponential( 'nu', lam= 1/ 29) + 1drug_like = pm.StudentT( 'drug', nu=nu, mu=mu_drug, sd=sigma_drug, observed=drug) placebo_like = pm.StudentT( 'placebo', nu=nu, mu=mu_placebo, sd=sigma_placebo, observed=placebo) diff_means = pm.Deterministic( 'diff_means', mu_drug - mu_placebo) pooled_sd = pm.Deterministic( 'pooled_sd', np.sqrt(np.power(sigma_drug, 2) + np.power(sigma_placebo, 2) / 2)) effect_size = pm.Deterministic( 'effect_size', diff_means / pooled_sd) MCMC Inference Button (TM)withkruschke_model: kruschke_trace = pm.sample( 10000, step=pm.Metropolis()) 结果pm.traceplot(kruschke_trace[ 2000:], varnames=[ 'mu_drug', 'mu_placebo'])plt.show() pm.plot_posterior(kruschke_trace[ 2000:], color= '#87ceeb',varnames=[ 'mu_drug', 'mu_placebo', 'diff_means'])plt.show() Difference in mean IQ:[0.5, 4.6] 概率P值:0.02 defget_forestplot_line(ax, kind):widths = { 'median': 2.8, 'iqr': 2.0, 'hpd': 1.0}assertkind inwidths.keys(), f( 'line kind must be one of {widths.keys()}') lines = [] forchild inax.get_children(): ifisinstance(child, mpl.lines.Line2D) andnp.allclose(child.get_lw(), widths[kind]): lines.append(child) returnlines defadjust_forestplot_for_slides(ax):forline inget_forestplot_line(ax, kind= 'median'): line.set_markersize( 10) forline inget_forestplot_line(ax, kind= 'iqr'): line.set_linewidth( 5) forline inget_forestplot_line(ax, kind= 'hpd'): line.set_linewidth( 3) returnaxpm.forestplot(kruschke_trace[ 2000:], varnames=[ 'mu_drug', 'mu_placebo'])ax = plt.gca()ax = adjust_forestplot_for_slides(ax)plt.show() Forest plot:相同轴上后验分布的95%HPD(细线),atv,IQR(较粗线)和中位数(点)。 (责任编辑:本港台直播) |