pymc3 - 如何使用具有自定义对数概率的 MCMC 并求解矩阵
问题描述
代码在 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)
解决方案
如果您只需要最高似然参数值,那么您需要最大 A 后验 (MAP) 估计,该估计可以使用pymc3.find_MAP()
(参见starting.py
方法详细信息)获得。如果您期望多峰后验,那么您可能需要使用不同的初始化重复运行它并选择获得最大值的logp
那个,但这仍然只会增加找到全局最优值的机会,尽管不能保证它。
应该注意的是,在高参数维度上,MAP 估计通常不是典型集合的一部分,即,它不代表会导致观察到的数据的典型参数值。Michael Betancourt 在A Conceptual Introduction to Hamiltonian Monte Carlo中讨论了这一点。完全贝叶斯方法是使用后验预测分布,它有效地对所有高似然参数配置进行平均,而不是对参数使用单点估计。
推荐阅读
- python - 为什么 Python 的 curve_fit 没有完成优化?
- domain-driven-design - 在 DDD 中:产生没有人消费的事件的命令
- javascript - 如何使用 node-postgres 制作自己的 CRUD 模块?
- css - 当父容器启用内容可编辑时,不显示 Microsoft Edge 中的调整大小光标
- excel - VBA将嵌入的excel表转换为word文件中的word表
- assembly - 什么是“错误 A2008:语法错误:整数”,我该如何解决?
- microsoft-graph-api - OneNote API 为任何请求返回 19999 错误代码
- reactjs - 如何使该表可排序?
- flutter - 是否可以在 Flutter/Dart 中创建具有多种类型的列表?
- angular - ng2-charts:数据标签值未显示在我的图表中