我正在使用 fast-ai 库来训练 IMDB 评论数据集的样本。我的目标是实现情感分析,我只想从一个小数据集开始(这个包含 1000 条 IMDB 评论)。我已经使用本教程在 VM 中训练了模型。
我保存了模型,然后保存了编码器,然后data_lm
保存了分类器学习器。然后,我从 VM 中获取这 4 个文件并将它们放入我的机器中,并希望使用这些预训练模型来对情绪进行分类。data_clas
ft_enc
sentiment_model
这就是我所做的:
# Use the IMDB_SAMPLE file
path = untar_data(URLs.IMDB_SAMPLE)
# Language model data
data_lm = TextLMDataBunch.from_csv(path, 'texts.csv')
# Sentiment classifier model data
data_clas = TextClasDataBunch.from_csv(path, 'texts.csv',
vocab=data_lm.train_ds.vocab, bs=32)
# Build a classifier using the tuned encoder (tuned in the VM)
learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5)
learn.load_encoder('ft_enc')
# Load the trained model
learn.load('sentiment_model')
之后,我想使用该模型来预测句子的情绪。执行此代码时,我遇到了以下错误:
RuntimeError: Error(s) in loading state_dict for AWD_LSTM:
size mismatch for encoder.weight: copying a param with shape torch.Size([8731, 400]) from checkpoint, the shape in current model is torch.Size([8888, 400]).
size mismatch for encoder_dp.emb.weight: copying a param with shape torch.Size([8731, 400]) from checkpoint, the shape in current model is torch.Size([8888, 400]).
Traceback 是:
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/SentAn/mainApp.py", line 51, in <module>
learn = load_models()
File "C:/Users/user/PycharmProjects/SentAn/mainApp.py", line 32, in load_models
learn.load_encoder('ft_enc')
File "C:\Users\user\Desktop\py_code\env\lib\site-packages\fastai\text\learner.py", line 68, in load_encoder
encoder.load_state_dict(torch.load(self.path/self.model_dir/f'{name}.pth'))
File "C:\Users\user\Desktop\py_code\env\lib\site-packages\torch\nn\modules\module.py", line 769, in load_state_dict
self.__class__.__name__, "\n\t".join(error_msgs)))
所以加载编码器时会出现错误。但是,我也尝试删除该load_encoder
行,但下一行发生了同样的错误learn.load('sentiment_model')
。
我搜索了fast-ai论坛,发现其他人也有这个问题,但没有找到解决方案。在这篇文章中,用户说这可能与不同的预处理有关,尽管我不明白为什么会发生这种情况。
有谁知道我做错了什么?