【问题标题】:ValueError: Tensor Tensor(...) is not an element of this graph. When using global variable keras modelValueError: Tensor Tensor(...) 不是该图的元素。使用全局变量keras模型时
【发布时间】:2017-06-20 04:03:32
【问题描述】:

我正在使用烧瓶运行 Web 服务器,当我尝试使用 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)

这是完整的错误:

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

【问题讨论】:

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


    【解决方案1】:

    看看avitalthis github issue上的回答。在此引用相关部分:

    在加载或构建模型后,立即保存 TensorFlow 图:

    graph = tf.get_default_graph()
    

    在另一个线程中(或者可能在异步事件处理程序中),执行:

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

    我对此进行了一些修改,并将图形存储在我的应用程序的配置对象中,而不是使其成为全局对象。

    get_default_graphTensorFlow documentation 解释了为什么这是必要的:

    注意:默认图是当前线程的属性。如果您创建一个新线程,并希望在该线程中使用默认图,则必须在该线程的函数中显式添加一个 with g.as_default():。

    【讨论】:

      猜你喜欢
      • 2017-06-18
      • 2020-06-09
      • 2019-09-17
      • 2019-10-23
      • 1970-01-01
      • 2018-04-27
      • 2019-04-22
      • 1970-01-01
      • 2019-06-21
      相关资源
      最近更新 更多