在 python jupyter notebook 中加载 pickle 文件时出现属性错误

数据挖掘 Python 喀拉斯 物体检测 朱庇特 泡菜
2022-03-02 08:18:57

我为对象检测任务创建了一个包含以下代码的配置文件,并保存在本地磁盘中。

# Create the config
C = Config()
C.use_horizontal_flips = horizontal_flips
C.use_vertical_flips = vertical_flips
C.rot_90 = rot_90
C.record_path = record_path
C.model_path = output_weight_path
C.num_rois = num_rois
C.base_net_weights = base_weight_path

with open(config_output_filename, 'wb') as config_f:
pickle.dump(C,config_f)

我正在尝试将这个泡菜文件加载到另一个 jupyter 笔记本中。

with open(config_output_filename, "rb") as f:
C = pickle.load(f)    
# turn off any data augmentation at test time
C.use_horizontal_flips = False
C.use_vertical_flips = False
C.rot_90 = False
print(C.num_rois)

但它给了我以下错误。

------------------------------------------------------------------------ 

AttributeError             Traceback (most recent call 
last)
 <ipython-input-20-c5528d5ef98b> in <module>
  1 with open(config_output_filename, "rb") as f:
   ----> 2     C = pickle.load(f)

  AttributeError: Can't get attribute 'Config' on <module '__main__'>

但是在我之前的尝试中,我能够从磁盘加载pickle文件而没有错误,并将配置应用于测试集。

2个回答

我猜这Config()是你创建的一个类。当您加载存储配置的泡菜文件时,将再次需要它。因此,您需要将其导入用于加载 pickle 文件的 jupyter notebook 中。

希望这会有所帮助。

一种选择是重构代码以使用 Python 字典。Python 字典可以序列化为 pickle 或 json。

config = {"use_horizontal_flips": True,
          "use_vertical_flips":   False,
        }