繁体   English   中英

TensorFlow REST前端但不是TensorFlow服务

[英]TensorFlow REST Frontend but not TensorFlow Serving

我想部署一个简单的TensorFlow模型,并在像Flask这样的REST服务中运行它。 到目前为止还没有找到github或这里的好例子。

我不准备像其他帖子中所建议的那样使用TF服务,这对谷歌来说是完美的解决方案,但是对于我的任务而言,gRPC,bazel,C ++编码,protobuf ......

有不同的方法来做到这一点。 纯粹地说,使用张量流不是很灵活,但相对简单。 此方法的缺点是您必须重建图形并初始化恢复模型的代码中的变量。 tensorflow skflow / contrib中有一种方法显示更优雅,但是目前这似乎不起作用且文档已经过时。

我把一个简单的例子一起在github 这里将告诉您如何命名GET或POST参数,加入烧瓶中REST部署tensorflow模型。

然后主代码在一个函数中,该函数根据POST / GET数据获取字典:

@app.route('/model', methods=['GET', 'POST'])
@parse_postget
def apply_model(d):
    tf.reset_default_graph()
    with tf.Session() as session:
        n = 1
        x = tf.placeholder(tf.float32, [n], name='x')
        y = tf.placeholder(tf.float32, [n], name='y')
        m = tf.Variable([1.0], name='m')
        b = tf.Variable([1.0], name='b')
        y = tf.add(tf.mul(m, x), b) # fit y_i = m * x_i + b
        y_act = tf.placeholder(tf.float32, [n], name='y_')
        error = tf.sqrt((y - y_act) * (y - y_act))
        train_step = tf.train.AdamOptimizer(0.05).minimize(error)

        feed_dict = {x: np.array([float(d['x_in'])]), y_act: np.array([float(d['y_star'])])}
        saver = tf.train.Saver()
        saver.restore(session, 'linear.chk')
        y_i, _, _ = session.run([y, m, b], feed_dict)
    return jsonify(output=float(y_i))

这个github项目展示了一个恢复模型检查点和使用Flask的工作示例。

@app.route('/api/mnist', methods=['POST'])
def mnist():
    input = ((255 - np.array(request.json, dtype=np.uint8)) / 255.0).reshape(1, 784)
    output1 = simple(input)
    output2 = convolutional(input)
    return jsonify(results=[output1, output2])

在线演示似乎很快。

我不喜欢在flask restful文件中添加大量数据/模型处理代码。 我通常有tf模型类等等。 它可能是这样的:

# model init, loading data
cifar10_recognizer = Cifar10_Recognizer()
cifar10_recognizer.load('data/c10_model.ckpt')

@app.route('/tf/api/v1/SomePath', methods=['GET', 'POST'])
def upload():
    X = []
    if request.method == 'POST':
        if 'photo' in request.files:
            # place for uploading process workaround, obtaining input for tf
            X = generate_X_c10(f)

        if len(X) != 0:
            # designing desired result here
            answer = np.squeeze(cifar10_recognizer.predict(X))
            top3 = (-answer).argsort()[:3]
            res = ([cifar10_labels[i] for i in top3], [answer[i] for i in top3])

            # you can simply print this to console
            # return 'Prediction answer: {}'.format(res)

            # or generate some html with result
            return fk.render_template('demos/c10_show_result.html',
                                      name=file,
                                      result=res)

    if request.method == 'GET':
        # in html I have simple form to upload img file
        return fk.render_template('demos/c10_classifier.html')

cifar10_recognizer.predict(X)是简单的func,它在tf会话中运行预测操作:

    def predict(self, image):
        logits = self.sess.run(self.model, feed_dict={self.input: image})
        return logits

ps从文件中保存/恢复模型是一个非常漫长的过程,在提供post / get请求时尽量避免这种情况

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM