0
最近在使用 Keras 复现主动学习的脚本时遇到了一个 bug,没想到这还真是 Keras 自身的一个 bug:
Bug
原始代码很简单:加载预训练模型(.h5文件),使用该模型预测结果,然后就会报错。具体代码 debug 后没有保存,大致如下:
from keras.models import load_model
# load model
model = load_model('~\~\model_path')
# x is a tensor with size: (1,299,299,3)
pred = model.predict(x)
...
# 然后将pred作为其他函数的参数使用
报错如下:
Traceback (most recent call last):
...
raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("dense_2/Softmax:0", shape=(?, 8), dtype=float32) is not an element of this graph.
Solution
在初始化加载模型之后,就随便生成一个向量让 model 执行一次 predict 函数,之后再使用就不会有问题了
# 加载模型,django 会在 web 应用初始化时执行这段代码 from keras.models import load_model print 'load model...' model_COC = load_model(sys.path[0] + '/resource/cate_class_model.h5') model_COE = load_model(sys.path[0] + '/resource/emo_class_model.h5') print 'load done.' # load 进来模型紧接着就执行一次 predict 函数 print 'test model...' print model_COC.predict(np.zeros((1, len(word_index)+1))) print model_COE.predict(np.zeros((1, len(word_index)+1))) print 'test done.' # 使用模型,在得到用户输入时会调用以下两个函数进行实时文本分类 # 输入参数 comment 为经过了分词与向量化处理后的模型输入 def category_class(comment): global model_COC result_vec = model_COC.predict(comment) return result_vec def emotion_class(comment): global model_COE result_vec = model_COE.predict(comment) return result_vec