2016-08-13 6 views
21

単純なTensorFlowモデルを展開し、FlaskのようなRESTサービスで実行したいと考えています。 githubやここではこれまでの良い例は見つかりませんでした。 gRPC、bazel、C++コーディング、いるProtobufと私の仕事のためにやり過ぎTensorFlow RESTフロントエンド(TensorFlowサービングではありません)

私は他の記事で示唆されているようにTFサービングを使用する準備ができていないです、それはGoogleのための完璧なソリューションですが、それは...

+1

狭い質問では、セーブロードモデルの後にFlaskで結果を返す作業例がほしい – chro

答えて

5

これを行う方法はさまざまです。純粋に、テンソルフローを使用することはあまり柔軟ではありませんが、比較的簡単です。この方法の欠点は、グラフを再構築して、モデルを復元するコード内の変数を初期化する必要があることです。 tensorflow skflow/contrib learnに示されている方法がありますが、これはよりエレガントですが、現時点では機能していないようで、ドキュメントは古くなっています。

フラスコのREST展開テンソルフローモデルにGETまたはPOSTパラメータを指定する方法を示すgithub hereに簡単な例をまとめました。

メインコードは、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)) 
3

このgithub projectはAを示しますモデルチェックポイントの復元と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]) 

オンラインdemoはかなり素早く見えます。

3

私はフラスコ安らかファイル内のデータ/モデル処理に多くのコードを置くことが好きではありません。私は通常、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 

P.S.ファイルからモデルを保存/復元することは非常に長いプロセスです。ポスト/取得要求を処理しながらこれを避けてみてください

関連する問題