如何pickle scipy.stats发行版(不能pickle instancemethod对象)

时间:2013-01-09 12:55:35

标签: python scipy pickle

如何保存scipy.stats发行版?

例如:

a = [scipy.stats.norm(0,1), scipy.stats.norm(0,2)]
with open("distro.pickle", 'w') as f:
    pickle.dump(a, f)

这样做我得到TypeError: can't pickle instancemethod objects

1 个答案:

答案 0 :(得分:7)

他们不支持酸洗。 “解决”你的问题的更简单方法是挑选参数,并在unpickling时创建一个新对象:

>>> from collections import namedtuple
>>> Norm = namedtuple('Norm', 'mu variance')
>>> def pickle_norm(n):
...     return pickle.dumps(Norm(*n.args))
... 
>>> def unpickle_norm(s):
...     return scipy.stats.norm(*pickle.loads(s))
... 
>>> s = pickle_norm(scipy.stats.norm(5, 10))
>>> d = unpickle_norm(s)