tensorflow - ValueError : Tensor Tensor(. ..) 不是该图的元素。使用全局变量 keras 模型时

标签 tensorflow neural-network keras conv-neural-network keras-layer

我正在使用 Flask 运行 Web 服务器,当我尝试使用 vgg16 时出现错误,vgg16 是 keras 的预训练 VGG16 模型的全局变量。我不知道为什么会出现这个错误,也不知道它是否与 Tensorflow 后端有关。
这是我的代码:

vgg16 = VGG16(weights='imagenet', include_top=True)

def getVGG16Prediction(img_path):
    global 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 = vgg16.predict(x)
    return x, sort(decode_predictions(pred, top=3)[0])

@app.route("/uploadMultipleImages", methods=["POST"])
def uploadMultipleImages():
    uploaded_files = request.files.getlist("file[]")
    for file in uploaded_files:
        path = os.path.join(STATIC_PATH, file.filename)
        pInput, result = getVGG16Prediction(path)

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

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

最佳答案

看看avitalthis github issue 的回答.在这里引用相关部分:

Right after loading or constructing your model, save the TensorFlow graph:

graph = tf.get_default_graph()

In the other thread (or perhaps in an asynchronous event handler), do:

global graph
with graph.as_default():
    (... do inference here ...)


我稍微修改了一下,并将图表存储在我的应用程序的配置对象中,而不是使其成为全局对象。

TensorFlow documentationget_default_graph解释为什么这是必要的:

NOTE: The default graph is a property of the current thread. If you create a new thread, and wish to use the default graph in that thread, you must explicitly add a with g.as_default(): in that thread's function.

关于tensorflow - ValueError : Tensor Tensor(. ..) 不是该图的元素。使用全局变量 keras 模型时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42013138/

相关文章:

docker - 有自定义操作时如何使用docker image tensorflow/serving服务tensorflow模型?

python - 占位符的尺寸如何用于 tensorflow ?

python - 通过全批量训练将字母图像训练到神经网络

tensorflow - Keras 中的多输入深度学习如何工作?

python - 如何保存 Keras 的训练历史以进行交叉验证(循环)?

python - TimeDistributed 一次多个层

python - 在 TensorFlow 中展平数据集

c++ - C/C++ TensorFlow hello_tf.c :(. text+0xa): 未定义对 `TF_Version' 的引用

python - 如何在 Keras 函数式 API 中使用逐元素乘法训练来组合 2 个向量?

python - 如何将声音作为神经网络的输入?