我想部署一个简单的 TensorFlow 模型并在 Flask 等 REST 服务中运行它。 到目前为止在 github 或这里没有找到好的例子。
我还没有准备好按照其他帖子中的建议使用 TF Serving,它对 Google 来说是完美的解决方案,但它对我的 gRPC、bazel、C++ 编码、protobuf 的任务来说太过分了......
最佳答案
有不同的方法可以做到这一点。纯粹来说,使用 tensorflow 不是很灵活,但是相对简单。这种方法的缺点是您必须在恢复模型的代码中重建图形并初始化变量。 tensorflow skflow/contrib learn中显示了一种方法哪个更优雅,但是目前这似乎不起作用,并且文档已过时。
我在github上放了一个简短的例子here这显示了如何将 GET 或 POST 参数命名为 flask 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))
关于python - TensorFlow REST 前端,但不是 TensorFlow Serving,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38935428/