2017-08-26 131 views
3

我已經出口了一個SavedModel,現在我用來加載它並進行預測。它是訓練有素,具有以下特點和標籤:TensorFlow:如何從SavedModel預測?

F1 : FLOAT32 
F2 : FLOAT32 
F3 : FLOAT32 
L1 : FLOAT32 

所以說,我想在值養活20.9, 1.8, 0.9得到一個FLOAT32預測。我該如何做到這一點?我已經成功地加載了模型,但我不確定如何訪問它以進行預測調用。

with tf.Session(graph=tf.Graph()) as sess: 
    tf.saved_model.loader.load(
     sess, 
     [tf.saved_model.tag_constants.SERVING], 
     "/job/export/Servo/1503723455" 
    ) 

    # How can I predict from here? 
    # I want to do something like prediction = model.predict([20.9, 1.8, 0.9]) 

此問題不是發佈的問題here的複製品。這個問題關注於對任何模型類(不僅限於tf.estimator)的SavedModel以及指定輸入和輸出節點名稱的語法執行推斷的最小示例。

+2

的可能的複製[如何使用tf.estimator導入一個保存Tensorflow火車模型和預測對輸入數據(https://stackoverflow.com/questions/46098863/how-to-import -an-saved-tensorflow-model-train-using-tf-estimator-and-predict-on) – rhaertel80

+0

查看我的最新編輯,瞭解爲什麼這不是重複的。 – jshapy8

回答

0

加載圖形後,它可在當前上下文中使用,並且可以通過它輸入輸入數據以獲取預測結果。每個用例是相當不同的,但除了您的代碼將是這個樣子:

with tf.Session(graph=tf.Graph()) as sess: 
    tf.saved_model.loader.load(
     sess, 
     [tf.saved_model.tag_constants.SERVING], 
     "/job/export/Servo/1503723455" 
    ) 

    prediction = sess.run(
     'prefix/predictions/Identity:0', 
     feed_dict={ 
      'Placeholder:0': [20.9], 
      'Placeholder_1:0': [1.8], 
      'Placeholder_2:0': [0.9] 
     } 
    ) 

    print(prediction) 

在這裏,你需要知道你的預測輸入將是什麼名字。如果您在serving_fn中沒有給他們一箇中殿,那麼他們默認爲Placeholder_n,其中n是第n個功能。

sess.run的第一個字符串參數是預測目標的名稱。這將根據您的使用情況而有所不同。

1

假設你想在Python中進行預測,SavedModelPredictor可能是加載SavedModel並獲得預測的最簡單方法。假設你保存你的模型像這樣:

# Build the graph 
f1 = tf.placeholder(shape=[], dtype=tf.float32) 
f2 = tf.placeholder(shape=[], dtype=tf.float32) 
f3 = tf.placeholder(shape=[], dtype=tf.float32) 
l1 = tf.placeholder(shape=[], dtype=tf.float32) 
output = build_graph(f1, f2, f3, l1) 

# Save the model 
inputs = {'F1': f1, 'F2': f2, 'F3': f3, 'L1': l1} 
outputs = {'output': output_tensor} 
tf.contrib.simple_save(sess, export_dir, inputs, outputs) 

(輸入可以是任何形狀,甚至不必須是在圖形佔位符,也不根節點)。

然後,在將使用SavedModel Python程序,我們可以得到的預測,像這樣:

from tensorflow.contrib import predictor 

predict_fn = predictor.from_saved_model(export_dir) 
predictions = predict_fn(
    {"F1": 1.0, "F2": 2.0, "F3": 3.0, "L1": 4.0}) 
print(predictions) 

This answer展示瞭如何獲得的Java,C++和Python(預測儘管在問題專注於估算器,答案實際上獨立於如何創建SavedModel)。

2

的人誰需要保存一個訓練有素的罐裝模型,並沒有tensorflow服務服務它的工作的例子,我在這裏記錄 https://github.com/tettusud/tensorflow-examples/tree/master/estimators

  1. 您可以從tf.tensorflow.contrib.predictor.from_saved_model(exported_model_path)
  2. 創建預測準備輸入

    tf.train.Example( 
        features= tf.train.Features(
         feature={ 
          'x': tf.train.Feature(
           float_list=tf.train.FloatList(value=[6.4, 3.2, 4.5, 1.5]) 
          )  
         } 
        )  
    ) 
    

這裏x是在輸出時在input_receiver_function中給出的輸入的名稱。 爲如:

​​