我尝试使用两个不同的模型来预测类别。这些模型是通过.json和.h5文件保存和加载的。
我遇到的问题是,有50%的时间一切正常运行,两个模型都能正确创建并进行预测。
但另一半时间似乎在创建模型时出现了问题,因为当我尝试进行预测时,会出现如下错误:
InvalidArgumentError: You must feed a value for placeholder tensor 'input_1_1' with dtype float and shape [?,10693] [[{{node input_1_1}} = Placeholder[dtype=DT_FLOAT, shape=[?,10693], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
如果分别运行这两个模型,或者不同时运行它们,效果非常完美,没有任何问题。
经过一些谷歌搜索,我发现Keras会保持模型的全局图,这可能是导致错误的原因。我觉得我已经尝试了网上找到的大多数建议,但仍然无法解决在程序中同时使用两个不同模型的问题。
所以,根据给定的参数,我希望能够使用model1或model2进行预测:
def predict_using_cnn(text, model, tokenizer, to_predict):
if to_predict == 'functiegroep':
with graph.as_default():
sequences_test = tokenizer.texts_to_sequences([text])
X_test = pad_sequences(sequences_test, maxlen=6616) # TODO fix this hardcoded thingy
y_pred = model.predict(X_test)
return build_response(y_pred, to_predict)
elif to_predict == 'kernfunctie':
with graph.as_default():
sequences_test = tokenizer.texts_to_sequences([text])
X_test = pad_sequences(sequences_test, maxlen=10693) # TODO fix this hardcoded thingy
y_pred = model.predict(X_test)
return build_response(y_pred, to_predict)
有时程序会进入第一个if语句,认为它需要10693的输入,这是另一个模型的输入。因此,程序似乎会随机混淆这些内容。
两个模型都是使用相同的函数加载的(当然,它们被保存到两个不同的变量中)
def load_cnn_model(model_name):
print("loading" + str(model_name))
json_file = open(str(model_name) + '.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)
model.load_weights(str(model_name) + '.h5')
return model
任何能帮助我解决这个问题的建议都将非常受欢迎!
回答:
最终我通过以下方式解决了这个问题:
graph = tf.Graph()
with graph.as_default():
session = tf.Session()
with session.as_default():
graph_fg = graph
session_fg = session
cnn_fg_model = predict.load_cnn_model('models/cnn/new_model_fg/new_model_fg')
with graph.as_default():
session = tf.Session()
with session.as_default():
graph_kf = graph
session_kf = session
cnn_kf_model = predict.load_cnn_model('models/cnn/new_model_kf/new_model_kf')
with graph.as_default():
with session.as_default():
if to_predict == 'functiegroep':
sequences_test = tokenizer.texts_to_sequences([text])
X_test = pad_sequences(sequences_test, maxlen=6616) # TODO fix this hardcoded thingy
y_pred = model.predict(X_test)
return build_response_cnn(y_pred, to_predict)
elif to_predict == 'kernfunctie':
sequences_test = tokenizer.texts_to_sequences([text])
X_test = pad_sequences(sequences_test, maxlen=10693) # TODO fix this hardcoded thingy
y_pred = model.predict(X_test)
return build_response_cnn(y_pred, to_predict)