如何修复'TypeError:hasattr():属性名称必须是字符串'错误?

时间:2015-07-14 06:02:56

标签: python numpy pymc

我有以下代码:

import pymc as pm
from matplotlib import pyplot as plt
from pymc.Matplot import plot as mcplot
import numpy as np
from matplotlib import rc

res = [18.752, 12.450, 11.832]

v = pm.Uniform('v', 0, 20)

errors = pm.Uniform('errors', 0, 100, size = 3)

taus = 1/(errors ** 2)

mydist = pm.Normal('mydist', mu = v, tau = taus, value = res, observed = True)

model=pm.Model([mydist, errors, taus, v, res])
mcmc=pm.MCMC(model) # This is line 19 where the TypeError originates
mcmc.sample(20000,10000)

mcplot(mcmc.trace('mydist'))

由于某种原因它不起作用,我得到'TypeError:hasattr():属性名称必须是字符串'错误,带有以下跟踪:

 Traceback (most recent call last):

  File "<ipython-input-49-759ebaf4321c>", line 1, in <module>
runfile('C:/Users/Paul/.spyder2-py3/temp.py', wdir='C:/Users/Paul/.spyder2-py3')

  File "C:\Users\Paul\Miniconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
execfile(filename, namespace)

  File "C:\Users\Paul\Miniconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)

  File "C:/Users/Paul/.spyder2-py3/temp.py", line 19, in <module>
mcmc=pm.MCMC(model)

  File "C:\Users\Paul\Miniconda3\lib\site-packages\pymc\MCMC.py", line 82, in __init__
**kwds)

  File "C:\Users\Paul\Miniconda3\lib\site-packages\pymc\Model.py", line 197, in __init__
Model.__init__(self, input, name, verbose)

  File "C:\Users\Paul\Miniconda3\lib\site-packages\pymc\Model.py", line 99, in __init__
ObjectContainer.__init__(self, input)

  File "C:\Users\Paul\Miniconda3\lib\site-packages\pymc\Container.py", line 606, in __init__
conservative_update(self, input_to_file)

  File "C:\Users\Paul\Miniconda3\lib\site-packages\pymc\Container.py", line 549, in conservative_update
if not hasattr(obj, k):

TypeError: hasattr(): attribute name must be string

如何让它工作并输出“mydist”?

编辑:我偶然发布了错误的痕迹。

Edit2:这一切都必须是因为res没有名字,因为它是一个数组,但我不知道如何为它指定一个名字,所以它会让它发挥作用。

2 个答案:

答案 0 :(得分:1)

我必须承认我不熟悉 pymc ,但是将其更改为以下内容至少使应用程序运行:

mydist = pm.Normal('mydist', mu = v, tau = taus, value = res, observed = False)

mcmc=pm.MCMC([mydist, errors, taus, v, res])

这似乎是因为您将所有内容都包装在 Model 中,这是ObjectContainer的扩展名,但是因为您传递了一个列表, MCMC { Container.py 中的{1}}尝试使用file_items将列表中的索引4分配给某个内容,但由于replaceModel它在ObjectContainer中分配了密钥4,导致您获得了奇怪的__dict__。删除包裹TypeError会导致Model正确使用MCMC

现在,line 543上的 Model.py 可能存在一个错误,其中可观察的随机指标未存储在数据库中 - 表达式为ListContainer但我怀疑应该也包括for object in self.stochastics | self.deterministics: - 所以我需要将self.observable_stochastics更改为observable,否则最后一行会抛出False

我对 pymc 不太熟悉,以确定它是否是实际或错误或期望的行为,因此我将其留给您提交issue

答案 1 :(得分:0)

您只需要将res定义为numpy数组:

res = np.array([18.752, 12.450, 11.832])

然后,您会在mcmc.trace('mydist')收到错误,因为mydist是观察到的数据,因此未进行采样。您可能想要绘制其他变量......