我正在尝试像这样腌制namedtuple
:
def f():
TemplateData = namedtuple('TemplateData', ['field1', 'field2'])
f1 = np.random.randn(50,50)
f2 = np.random.randn(50,50)
td = TemplateData(f1, f2)
return td
data = f()
with open("aaaa.pkl", "wb") as fl:
pkl.dump(data, fl)
但是由于错误而崩溃:
PicklingError: Can't pickle <class '__main__.TemplateData'>: it's not the same object as __main__.TemplateData
怎么了?
如果pickle
不是存储命名元组的最佳方法-哪种方法最有效?
答案 0 :(得分:3)
您需要在函数外部定义namedtuple,并将namedtuple的名称更改为TemplateData
。
TemplateData = namedtuple('TemplateData', ['field1', 'field2'])
f1 = np.random.randn(50,50)
f2 = np.random.randn(50,50)
model_cluster = TemplateData(f1, f2)
with open("aaaa.pkl", "wb") as fl:
pkl.dump(model_clusters_dict, fl)