一年多前写过一篇类似文章,https://blog.csdn.net/qq_17190121/article/details/99696768#comments_14242069
从反馈上看,有部分小伙伴表示没看懂,所以这次用另一种更简单的方式编写。
环境
python 3.8.3
tensorflow 2.4.0
制作测试模型
注意: tensorflow版本1和版本2的接口不同, 我这里套用原来的代码, 修改部分需要兼容的代码.比如 tf.placeholder() --> tf.compat.v1.placeholder()。如果你用的是版本1则不用修改
import tensorflow as tf
import numpy as np
import os
# 文件夹不存在时,会报utf-8解析错误
if not os.path.exists('./model'):
os.mkdir('./model')
tf.compat.v1.disable_eager_execution()
x = tf.compat.v1.placeholder(tf.float32, name='inputX')
feed = np.random.rand(100)
y = 2 * x + 1
w = tf.Variable(0.)
b = tf.Variable(0.)
y_ = tf.add(tf.multiply(w, x), b, name='outputY')
loss = tf.reduce_mean(tf.square(y - y_))
optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.2)
train = optimizer.minimize(loss)
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
sess.run(init)
for i in range(200):
sess.run(train, feed_dict={x: feed})
if i % 5 == 0:
print(i, sess.run([w, b]))
constant_graph = tf.compat.v1.graph_util.convert_variables_to_constants(sess, sess.graph_def, ['outputY'])
with tf.compat.v1.gfile.FastGFile('./model/linear.pb', mode='wb') as f:
f.write(constant_graph.SerializeToString())
部署上线
这里使用python的web服务器框架Flask,很容易上手的,而且Pycharm在创建项目时就能选择。
这里直接贴代码
app.py
import tensorflow as tf
from flask import Flask
from flask import request
app = Flask(__name__)
with tf.compat.v1.gfile.FastGFile('./model/linear.pb', 'rb') as f:
graph_def = tf.compat.v1.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
sess = tf.compat.v1.Session()
output = sess.graph.get_tensor_by_name('outputY:0')
@app.route('/predict', methods=["GET"])
def testPredict():
inputX = request.args.get("inputX")
return str(sess.run(output, feed_dict={'inputX:0': inputX}))
if __name__ == '__main__':
app.run()
验证结果
程序启动后,默认监听的是5000端口,我们用浏览器访问 http://localhost:5000/predict?inputX=2,可以看到结果
完结撒花❀❀❀