将tensorflow模型部署到服务器上 - 方法2

一年多前写过一篇类似文章,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,可以看到结果

在这里插入图片描述

完结撒花❀❀❀

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值