【发布时间】:2020-04-09 19:03:47
【问题描述】:
我使用 PyTorch 保存方法来序列化一堆基本对象。其中,有一个类在同一个类的 __init__ 中引用了一个私有方法。现在,在序列化之后,我无法反序列化(unpickle)文件,因为在类外部无法访问私有方法。知道如何解决或绕过它吗?我需要恢复保存到该类属性中的数据。
File ".conda/envs/py37/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-a5666d77c70f>", line 1, in <module>
torch.load("snapshots/model.pth", map_location='cpu')
File ".conda/envs/py37/lib/python3.7/site-packages/torch/serialization.py", line 529, in load
return _legacy_load(opened_file, map_location, pickle_module, **pickle_load_args)
File ".conda/envs/py37/lib/python3.7/site-packages/torch/serialization.py", line 702, in _legacy_load
result = unpickler.load()
AttributeError: 'Trainer' object has no attribute '__iterator'
- EDIT-1:
这里有一段代码会产生我现在面临的问题。
import torch
class Test:
def __init__(self):
self.a = min
self.b = max
self.c = self.__private # buggy
def __private(self):
return None
test = Test()
torch.save({"test": test}, "file.pkl")
torch.load("file.pkl")
但是,如果您从方法中删除私有属性,则不会出现任何错误。
import torch
class Test:
def __init__(self):
self.a = min
self.b = max
self.c = self.private # not buggy
def private(self):
return None
test = Test()
torch.save({"test": test}, "file.pkl")
torch.load("file.pkl")
【问题讨论】:
标签: python serialization deployment pytorch pickle