我正在使用 keras 的预训练模型,在尝试获取预测时出现错误。我在 Flask 服务器中有以下代码:
from NeuralNetwork import *
@app.route("/uploadMultipleImages", methods=["POST"])
def uploadMultipleImages():
uploaded_files = request.files.getlist("file[]")
getPredictionfunction = preTrainedModel["VGG16"]
for file in uploaded_files:
path = os.path.join(STATIC_PATH, file.filename)
result = getPredictionfunction(path)
这是我的 NeuralNetwork.py 文件中的内容:
vgg16 = VGG16(weights='imagenet', include_top=True)
def getVGG16Prediction(img_path):
model = vgg16
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
pred = model.predict(x) #ERROR HERE
return sort(decode_predictions(pred, top=3)[0])
preTrainedModel["VGG16"] = getVGG16Prediction
但是,运行下面的代码不会产生任何错误:
if __name__ == "__main__":
STATIC_PATH = os.getcwd()+"/static"
print(preTrainedModel["VGG16"](STATIC_PATH+"/18.jpg"))
非常感谢任何评论或建议。谢谢。
最佳答案
考虑到后端设置为tensorflow。您应该将 Keras session 设置为 tensorflow 图
from tensorflow import Graph, Session
from keras import backend
model = 'model path'
graph1 = Graph()
with graph1.as_default():
session1 = Session(graph=graph1)
with session1.as_default():
model_1.load_model(model) # depends on your model type
model2 = 'model path2'
graph2 = Graph()
with graph2.as_default():
session2 = Session(graph=graph2)
with session2.as_default():
model_2.load_model(model2) # depends on your model type
并用于预测
K.set_session(session#)
with graph#.as_default():
prediction = model_#.predict(img_data)
关于python-2.7 - ValueError : Tensor:(. ..) 不是该图的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41991756/