I'm using emcee mcmc hammer in order to reconstruct a 1D Gaussian from 20 samples with random standard deviations. Here is the relevant part of my code:
def loglike(alpha,datapoints):
mu, sig = alpha
return nbabies*(np.log(1/(nsamples*np.sqrt(2*np.pi)*sig)))+np.sum(scipy.misc.logsumexp(-(datapoints-mu)**2/(2*sig**2),axis=1),axis=0)
import scipy.optimize as op
nll = lambda *args: -loglike(*args)
result = op.minimize(nll, [mupop, sigpop], args=(datapoints))
muml,sigml = result["x"]
def logprior(alpha):
mu, sig = alpha
if 0 < sig < 1 and 0.0 < mu < 1:
return 0.0
return -np.inf
def logprob(alpha,datapoints):
lp = logprior(alpha)
if not np.isfinite(lp):
return -np.inf
return lp + loglike(alpha,datapoints)
rendim = 2
renwalkers = 100
rensamples = 10000
p0 = [result["x"]+np.random.rand(rendim) for i in range(renwalkers)]
#now we run emcee!
momma2 = emcee.EnsembleSampler(renwalkers, rendim, logprob, args=(datapoints))
momma2.run_mcmc(p0, rensamples)
momma2samps = momma2.flatchain[0.2*renwalkers*rensamples:,]
But I keep getting the error message "ValueError: operands could not be broadcast together with shapes (1,2) (20,100)." What's the deal?
Your problem is that the line
result = op.minimize(nll, [mupop, sigpop], args=(datapoints))
should be
result = op.minimize(nll, [mupop, sigpop], args=(datapoints,))
minimize
takes a tuple as args, and if you don't include the comma, it does not interpret the arguments correctly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.