gpt4 book ai didi

python - 无法pickle Python 类实例

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:24 25 4
gpt4 key购买 nike

这里我有这个类定义class definition 。当我运行下面的代码时,它会引发以下错误。

sm = SaliencyMaskSlic()
operations = [('img_resize', img_resize), ('sal_mask', sm.transform)]
args_list = [{'h_size':258}, {'cropped':True}]

pre_pipeline = Pipeline(ops=operations, arg_list=args_list)
ch = ColorHist('RGB', [6,6,6], [2,2], center=True, pre_pipeline = pre_pipeline)

dill.dump(ch, open('erogol.pkl','wb'))
...
dill.loads('erogol.pkl')


---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-11-c8a5937780b5> in <module>()
----> 1 dill.loads('erogol.pkl')

/usr/local/lib/python2.7/dist-packages/dill/dill.pyc in loads(str)
158 """unpickle an object from a string"""
159 file = StringIO(str)
--> 160 return load(file)
161
162 # def dumpzs(obj, protocol=None):

/usr/local/lib/python2.7/dist-packages/dill/dill.pyc in load(file)
148 pik = Unpickler(file)
149 pik._main_module = _main_module
--> 150 obj = pik.load()
151 if type(obj).__module__ == _main_module.__name__: # point obj class to main
152 try: obj.__class__ == getattr(pik._main_module, type(obj).__name__)

/usr/lib/python2.7/pickle.pyc in load(self)
856 while 1:
857 key = read(1)
--> 858 dispatch[key](self)
859 except _Stop, stopinst:
860 return stopinst.value

/usr/lib/python2.7/pickle.pyc in load_appends(self)
1185 def load_appends(self):
1186 stack = self.stack
-> 1187 mark = self.marker()
1188 list = stack[mark - 1]
1189 list.extend(stack[mark + 1:])

/usr/lib/python2.7/pickle.pyc in marker(self)
872 mark = self.mark
873 k = len(stack)-1
--> 874 while stack[k] is not mark: k = k-1
875 return k
876

IndexError: list index out of range

基本上,我有一个类实例在内部使用另一个类实例。我也使用了 cPickle,但当我转储时它会升高;

TypeError: can't pickle instancemethod objects

有解决办法吗?

最佳答案

这不是 pickle 错误。您无法使用 picklecPickle 来pickle 类实例,但可以使用dill。您的代码在某处存在错误,该错误会导致 IndexError

也比具有 dumpload 方法的类更好,您可能只使用 dumpload直接来自 dill...那么如果您正在做一些复杂的事情,您仍然可以添加 __getstate____setstate__ 方法。

此外,从 pickle 文件加载有一个错误。你正在这样做:

    self = dill.loads(in_path)

虽然您应该 (1) 使用 dill.load 代替,(2) 加载到 _self,然后替换相关状态。

    _self = dill.load(in_path)
self.nbins = _self.nbins
self.mask = _self.mask
# and so on... (or update all at once using `__dict__`)

关于python - 无法pickle Python 类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27471143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com