【问题标题】:ValueError: Tensor:(...) is not an element of this graphValueError: Tensor:(...) 不是该图的元素
【发布时间】:2017-06-18 21:46:03
【问题描述】:

我正在使用 keras 的预训练模型,但在尝试进行预测时出现错误。我在烧瓶服务器中有以下代码:

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"))

这是完整的错误:

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

【问题讨论】:

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


    【解决方案1】:

    编辑:我在下面写的在部署应用程序时似乎不起作用(直到现在我只是在本地测试)。 app.config 中的模型似乎加载得太频繁了。 (应每个请求?)

    巧合的是,我昨天遇到了同样的问题。 TensorFlow 和 Flask 的交互似乎有些问题。不幸的是,我对其中任何一个的内部知识都不够了解,无法真正理解这个问题,但我可以提供一个帮助我让它工作的技巧。 (注意:我使用的是 Python3,但我认为这在这里没有什么不同。)

    在您的烧瓶应用程序的全局命名空间中初始化模型时似乎会​​出现此问题。因此我将模型直接加载到 app.config 中:

    app.config.update({"MODEL":VGG16(weights='imagenet', include_top=True)})
    # ...
    app.config["MODEL"].predict(x)
    

    也许您可以在 server.py 而不是 NeuralNetwork.py 中加载模型并将其与 img_path 一起传递给 getVGG16Prediction

    【讨论】:

    • 在我的情况下,问题是因为烧瓶两次加载张量流。当我改变 app.run(debug=False) 然后它工作,但我不知道为什么。这是该问题的链接:stackoverflow.com/questions/42015797/…。我不确定你的情况是否相同,但我希望它有所帮助。谢谢你的建议:)
    【解决方案2】:

    考虑后端设置为tensorflow。您应该将 Keras 会话设置为张量流图

    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)
    

    【讨论】:

    • 为我工作,只需将 from keras import backend 更改为 'from keras import backend as K`
    猜你喜欢
    • 2020-06-09
    • 2019-09-17
    • 2019-10-23
    • 2018-04-27
    • 2017-06-20
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多