代码在PyMC3中,但这是一个普遍的问题。我想找到哪个矩阵(变量组合)给我最高概率。取每个元素的痕迹的平均值是没有意义的,因为它们彼此依赖。
这是一个简单的案例;为简单起见,代码使用向量而不是矩阵。目标是找到长度为2的向量,其中每个值介于0和1之间,因此总和为1。
import numpy as np
import theano
import theano.tensor as tt
import pymc3 as mc
# define a theano Op for our likelihood function
class LogLike_Matrix(tt.Op):
itypes = [tt.dvector] # expects a vector of parameter values when called
otypes = [tt.dscalar] # outputs a single scalar value (the log likelihood)
def __init__(self, loglike):
self.likelihood = loglike # the log-p function
def perform(self, node, inputs, outputs):
# the method that is used when calling the Op
theta, = inputs # this will contain my variables
# call the log-likelihood function
logl = self.likelihood(theta)
outputs[0][0] = np.array(logl) # output the log-likelihood
def logLikelihood_Matrix(data):
"""
We want sum(data) = 1
"""
p = 1-np.abs(np.sum(data)-1)
return np.log(p)
logl_matrix = LogLike_Matrix(logLikelihood_Matrix)
# use PyMC3 to sampler from log-likelihood
with mc.Model():
"""
Data will be sampled randomly with uniform distribution
because the log-p doesn't work on it
"""
data_matrix = mc.Uniform('data_matrix', shape=(2), lower=0.0, upper=1.0)
# convert m and c to a tensor vector
theta = tt.as_tensor_variable(data_matrix)
# use a DensityDist (use a lamdba function to "call" the Op)
mc.DensityDist('likelihood_matrix', lambda v: logl_matrix(v), observed={'v': theta})
trace_matrix = mc.sample(5000, tune=100, discard_tuned_samples=True)
如果您只想要最高似然参数值,那么您需要最大后验(MAP)估计,可以使用pymc3.find_MAP()
获得(有关方法详细信息,请参阅starting.py
)。如果您期望多模式后验,那么您可能需要使用不同的初始化重复运行此选项并选择获得最大logp
值的那个,但这仍然只会增加找到全局最优值的机会,但不能保证它。
应当注意,在高参数维度下,MAP估计通常不是典型集合的一部分,即,它不代表将导致观察数据的典型参数值。 Michael Betancourt在A Conceptual Introduction to Hamiltonian Monte Carlo讨论了这个问题。完全贝叶斯方法是使用posterior predictive distributions,它有效地平均所有高似然参数配置,而不是使用参数的单点估计。