我正在尝试在以下场景中对 softmax 选择函数的单个参数执行参数估计:
在每个试验中,给出三个选项值(例如,[1,2,3]),并且受试者在选项(0、1 或 2)之间做出选择。softmax 函数将选项值转换为选择概率(3 个概率的向量,总和为 1),具体取决于温度参数(此处限制在 0 和 10 之间)。
每个试验中的选择应该被建模为一个分类分布,其中试验选择概率是从 softmax 计算的。请注意,分类的选择概率取决于选项值,因此在每次试验中都不同。
这是我想出的:
# Generate data
nTrials = 60 # number of trials (value triplets and choices)
np.random.seed(42)
# generate nTrials triplets of values
values = np.random.choice([1,2,3,4,5], size=(nTrials, 3))
choices = values.argmax(axis=1) # choose highest value option
# add some random variation, so that *not* always the highest value option is chosen
errors = np.random.rand(nTrials)>0.8 # determine trials with non-optimal choice
# randomly determine new choices for these trials
choices[errors] = np.random.choice([0,1,2], size=sum(errors==True))
# Model specification & estimation
import pymc3 as pm
from theano import tensor as t
with pm.Model():
# prior over theta
theta = pm.Uniform('theta', lower=0, upper=10)
# softmax implementation
enumerator = pm.exp(theta*values)
denominator = t.reshape(pm.sum(pm.exp(theta*values), axis=1), (nTrials, 1))
ps = enumerator/denominator
# Likelihood (sampling model for the data)
for trial in range(nTrials):
yobs = pm.Categorical('yobs{}'.format(trial), p=ps[trial], observed=choices[trial])
# draw 500 samples from posterior
trace = pm.sample(500, pm.Metropolis())
对于大于 50 的 nTrials,此代码将失败,并带有极长的警告/错误消息:
警告:
INFO (theano.gof.compilelock): Refreshing lock /Users/felixmolter/.theano/compiledir_Darwin-14.4.0-x86_64-i386-64bit-i386-2.7.8-64/lock_dir/lock
INFO:theano.gof.compilelock:Refreshing lock /Users/felixmolter/.theano/compiledir_Darwin-14.4.0-x86_64-i386-64bit-i386-2.7.8-64/lock_dir/lock
00001 #include <Python.h>
00002 #include <iostream>
00003 #include <math.h>
00004 #include <numpy/arrayobject.h>
00005 #include <numpy/arrayscalars.h>
00006 #include <vector>
00007 #include <algorithm>
00008 //////////////////////
00009 //// Support Code
00010 //////////////////////
00011
00012
00013 namespace {
00014 struct __struct_compiled_op_65734e56ae54d89bdcf84e36893358e6 {
00015 PyObject* __ERROR;
00016
00017 PyObject* storage_V3;
00018 PyObject* storage_V5;
00019 PyObject* storage_V7;
00020 PyObject* storage_V9;
00021 PyObject* storage_V11;
00022 PyObject* storage_V13;
[...]
错误:
Exception: ('The following error happened while compiling the node', Elemwise{Composite{((Switch(LE(Abs((i0 + i1)), i2), log(i3), i4) + Switch(LE(Abs((i0 + i5)), i2), log(i6), i4) + Switch(LE(Abs((i0 + i7)), i2), log(i8), i4) + Switch(LE(Abs((i0 + i9)), i2), log(i10), i4) + Switch(LE(Abs((i0 + i11)), [...]
我对 PyMC(和 Theano)相当陌生,我觉得我的实现非常笨拙且不理想。非常感谢任何帮助和建议!
菲利克斯
编辑:我已将代码作为笔记本上传,完整显示警告和错误消息:http: //nbviewer.ipython.org/github/moltaire/softmaxPyMC/blob/master/softmax_stackoverflow.ipynb