def log_prob_b2(b2, state, data): # loglike logit_p = state.b0 + state.b1 * data.x + b2 * data.x**2 p = mcmc.sigmoid(logit_p) loglike = data.y * np.log(p) + (1 - data.y) * np.log1p(-p) # logprior logprior = b2_prior().lpdf(b2) return loglike.sum() + logprior
# COMPILE _ = fit(State(0, 0, 0), Data(x, y), burn=1, niter=1) with Timer.Timer("MCMC", digits=3): out = fit(State(0, 0, 0), Data(x, y), burn=1000) print('Done') b0 = np.array([s['b0'] for s in out]) b1 = np.array([s['b1'] for s in out]) b2 = np.array([s['b2'] for s in out]) B = len(out) M = 200 xx = np.linspace(-4, 4, 100) p = mcmc.sigmoid(b0[:, None] + b1[:, None] * xx[None, :] + b2[:, None] * xx[None, :]**2) # Plots plt.plot(xx, p.mean(0), label='est') plt.plot(xx, np.quantile(p, .975, axis=0), linestyle='--') plt.plot(xx, np.quantile(p, .025, axis=0), linestyle='--') plt.scatter(simdat['x'][::100], simdat['p'][::100], label='true', s=5) plt.scatter(simdat['x'], simdat['y'] + np.random.randn(len(simdat['y'])) * .01, label='data', s=5, alpha=.1) plt.legend() plt.show()
def loglike(self, b0, b1, b2): logit_p = b0 + self.data.x * b1 + (self.data.x**2) * b2 p = mcmc.sigmoid(logit_p) ll = self.data.y * np.log(p) + (1 - self.data.y) * np.log1p(-p) return ll.sum()