正在学习《Python机器学习》一书中第9章的“在Web应用中嵌入机器学习模型”,于是想用keras+flask做简单的尝试,代码直接运行没问题,但是flask上跑就是报错,如下:
ValueError: Tensor Tensor("dense_2/Softmax:0", shape=(?, 192), dtype=float32) is not an element of this graph.
网上一顿搜索操作猛如虎,参考了两位大神的解决方案,简直了,就是如下简单的四行代码:
import tensorflow as tf
graph = tf.get_default_graph()
global graph
with graph.as_default():
# 执行预测函数
添加到app.py,问题解决
from flask import Flask, render_template, request
from wtforms import Form, TextAreaField, validators
import os
import tensorflow.keras as keras
import tensorflow as tf
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
app = Flask(__name__)
graph = tf.get_default_graph()
cur_dir = os.path.dirname(__file__)
model = tf.keras.models.load_model(open(os.path.join(cur_dir,'demo_tensorflow.model'), 'rb'))
def classify(X_test):
global graph
with graph.as_default():
predictions = model.predict(X_test)
return predictions
'''
以下代码省略
'''
解决方案链接:
1. ValueError: Tensor Tensor xxx is not an element of of this graph的解决方案