python-2.7 - ValueError : Tensor:(. ..) 不是该图的元素

标签 python-2.7 neural-network keras conv-neural-network keras-layer

我正在使用 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"))

这是完整的错误: enter image description here

非常感谢任何评论或建议。谢谢。

最佳答案

考虑到后端设置为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/

相关文章:

python - 无法在 Robotframework 中使用点符号访问字典

python - 如何检查一个字符串中的两个连续值是否是另一个字符串中的字符

neural-network - 我们应该为 adam 优化器做学习率衰减吗

python - 可重用的 Tensorflow 卷积网络

machine-learning - 为什么我的早期纪元比后续纪元花费的时间更长?

python - Talos 多 GPU 功能

基于 Python Rate Limit 类的 View Flask

optimization - 神经网络优化

python - Keras,如何使用移除最后一层的模型进行预测

python - 检查元素是否在列表中