在这里,我有这个类定义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


有解决方案的主意吗?

最佳答案

这不是腌制错误。您不能使用picklecPickle腌制类实例,但是可以使用dill腌制类实例。您的代码在某个地方有一个错误,给您IndexError

也比使用具有dumpload方法的类更好,您可以直接使用dump中的loaddill ...如果您做复杂的事情,仍然可以添加和__getstate__方法。

另外,从腌制的文件中加载时也会出现错误。您正在执行此操作:

    self = dill.loads(in_path)


您应该(1)改为使用__setstate__,并且(2)加载到dill.load,然后替换相关状态。

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

10-06 03:02