将预训练模型加载到Python脚本时遇invalidkey错误求解决方案
解决预训练Pickle模型加载时的invalidkey错误
问题核心原因
你当前代码里使用的GitHub URL是模型文件的网页展示地址,不是原始文件的下载链接。用这个URL下载到的其实是GitHub的HTML页面,而非真正的pickle模型文件,反序列化时自然会触发invalidkey错误。另外每次调用predict都重复下载模型,既浪费资源又拖慢效率。
修复步骤
1. 替换为原始文件下载链接
在GitHub的模型文件页面,点击右上角的「Raw」按钮,复制弹出的原始文件URL。你的模型正确下载链接应为:https://raw.githubusercontent.com/JuanRuedz/Rice-classification-model/48ead0817e633e5f5e295636e7960182119d72cd/cnn.pkl
2. 优化模型加载逻辑
将模型加载逻辑移到类初始化阶段,只执行一次,避免重复下载和读取操作。
修复后的完整代码
import numpy as np import pickle from PIL import Image import urllib class Model(): def __init__(self): self.model = None self.model_url = 'https://raw.githubusercontent.com/JuanRuedz/Rice-classification-model/48ead0817e633e5f5e295636e7960182119d72cd/cnn.pkl' self._load_model() def _load_model(self): # 优先读取本地模型,避免重复下载 if not self.model: try: with open('cnn.pkl', "rb") as f: self.model = pickle.load(f) except (FileNotFoundError, pickle.UnpicklingError): # 本地无有效文件时重新下载 response = urllib.request.urlopen(self.model_url) with open('cnn.pkl', "wb") as f: f.write(response.read()) # 加载新下载的模型 with open('cnn.pkl', "rb") as f: self.model = pickle.load(f) def predict(self, file_path): img = Image.open(file_path) img = np.array(img) img = np.expand_dims(img, axis=0) pred = self.model.predict(img) index = np.where(pred[0] == 1)[0][0] return index
额外注意事项
- Pickle安全风险:Pickle反序列化不受信任的文件可能导致恶意代码执行,务必确保模型来源可靠。
- 依赖版本一致性:运行环境的依赖库版本(如TensorFlow/Keras)要和模型训练时保持一致,否则可能出现加载或预测错误。
内容的提问来源于stack exchange,提问作者Juan_Ruedz
相关产品推荐
相关产品推荐

