pickle.load报错【AttributeError: Can’t get attribute ‘Vocabulary’ on <module ‘main’】
-
背景:在看代码的时候想看看一个pkl文件的文件结构和里面的数据,于是就用pickle.load打开,但是出现了
AttributeError: Can't get attribute 'Vocabulary' on <module '__main__'
错误 -
原因:就像我们在保存模型的时候有两种方式,一种是保存整个模型,虽然很大但是使用方便;另一种是只保存了模型的参数,这里加载时就需要先初始化一个模型。这里也是一样的,
msvd_vocab.pkl
在加载时也需要找到其依赖的类,而在报错信息中也说明了,需要导入的类是Vocabulary
。所以需要在项目中找到类Vocabulary,然后在调用pickle.load('.../msvd_vocab.pkl','rb')
的python文件中import该类 -
报错代码
import pickle
with open('.\data\MSVD\msvd_vocab.pkl','rb') as f:
v = pickle.load(f)
# 报错:在demo.py的main中没有‘Vocabulary’模块
AttributeError: Can't get attribute 'Vocabulary' on <module '__main__' from '.../demo.py'>
- 找到‘Vocabulary’类
- 更正
import pickle
from utils.utils import *
with open('.\data\MSVD\msvd_vocab.pkl','rb') as f:
v = pickle.load(f)
完美撒花