ValueError:Tensor:(...)不是此图的元素 [英] ValueError: Tensor:(...) is not an element of this graph

查看:99
本文介绍了ValueError:Tensor:(...)不是此图的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用keras的预训练模型,尝试获取预测时出现错误.我在Flask服务器中有以下代码:

I am using keras' pre-trained model and the error came up when trying to get predictions. I have the following code in flask server:

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文件中的内容:

This is what I have in my NeuralNetwork.py file:

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

但是,在下面运行此代码不会产生任何错误:

However, running this code below, does not create any error:

if __name__ == "__main__":
    STATIC_PATH = os.getcwd()+"/static"
    print(preTrainedModel["VGG16"](STATIC_PATH+"/18.jpg"))

这是完整的错误:

任何评论或建议,我们将不胜感激.谢谢.

Any comment or suggestion is greatly appreciated. Thank you.

推荐答案

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

Considering the backend is set to tensorflow. You should set the Keras session to the graph of 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)

这篇关于ValueError:Tensor:(...)不是此图的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆