
如何快速實現REST API集成以優化業務流程
借助預創建的 Estimator,您能夠在比基本 TensorFlow API 高級很多的概念層面上進行操作。由于 Estimator 會為您處理所有 “ 管道工作 ”,因此您不必再為創建計算圖或會話而操心。也就是說,預創建的 Estimator 會為您創建和管理 Graph(https://tensorflow.google.cn/api_docs/python/tf/Graph?hl=zh-CN)和 Session(https://tensorflow.google.cn/api_docs/python/tf/Session?hl=zh-CN)對象。此外,借助預創建的 Estimator,您只需稍微更改下代碼,就可以嘗試不同的模型架構。例如,DNNClassifier 是一個預創建的 Estimator 類(https://tensorflow.google.cn/api_docs/python/tf/estimator/DNNClassifier?hl=zh-CN),它根據密集的前饋神經網絡訓練分類模型。
依賴預創建的 Estimator 的 TensorFlow 程序通常包含下列四個步驟:
編寫一個或多個數據集導入函數。
例如,您可以創建一個函數來導入訓練集,并創建另一個函數來導入測試集。每個數據集導入函數都必須返回兩個對象 :
例如,以下代碼展示了輸入函數的基本框架:
def input_fn(dataset):
... # manipulate dataset, extracting the feature dict and the label
return feature_dict, label
(要了解完整的詳細信息,請參閱導入數據(https://tensorflow.google.cn/guide/datasets?hl=zh-CN)。)
定義特征列。
每個 tf.feature_column(https://tensorflow.google.cn/api_docs/python/tf/feature_column?hl=zh-CN)都標識了特征名稱、特征類型和任何輸入預處理操作。例如,以下代碼段創建了三個存儲整數或浮點數據的特征列。前兩個特征列僅標識了特征的名稱和類型。第三個特征列還指定了一個 lambda,該程序將調用此 lambda 來調節原始數據:
# Define three numeric feature columns.
population = tf.feature_column.numeric_column('population')
crime_rate = tf.feature_column.numeric_column('crime_rate')
median_education = tf.feature_column.numeric_column('median_education',
normalizer_fn=lambda x: x - global_education_mean)
例如,下面是對名為 LinearClassifier 的預創建 Estimator 進行實例化的示例代碼:
# Instantiate an estimator, passing the feature columns.
estimator = tf.estimator.LinearClassifier(
feature_columns=[population, crime_rate, median_education],
)
例如,所有 Estimator 都提供訓練模型的 train 方法。
# my_training_set is the function created in Step 1
estimator.train(input_fn=my_training_set, steps=2000)
預創建的 Estimator 會編碼最佳做法,從而具有下列優勢:
如果您不使用預創建的 Estimator,則必須自行實現上述功能。
利用Estimator如何把Python庫導出,可以通過以下幾種方式實現:
tf.estimator.export
:tf.estimator.export
模塊,它包含了一系列用于導出Estimator的類和函數。你可以使用tf.estimator.export.build_parsing_serving_input_receiver_fn
和tf.estimator.export.build_raw_serving_input_receiver_fn
來構建輸入接收函數,然后使用tf.estimator.Estimator.export_saved_model
方法將模型導出為SavedModel格式。tf.saved_model.save
函數,你可以將模型保存到指定的目錄。在需要載入SavedModel文件時,使用tf.saved_model.load
函數即可。tf.keras.estimator.model_to_estimator
:tf.keras.estimator.model_to_estimator
將Keras模型轉換為Estimator,這樣你的Keras模型就可以利用Estimator的優勢,例如分布式訓練。tf.estimator.Exporter
:tf.estimator.Exporter
是一個表示模型導出類型的類,它允許你將Estimator導出為特定格式。通過實現export
方法,你可以將Estimator導出為不同格式,包括SavedModel。tf.train.Saver
來保存和恢復模型的檢查點。檢查點包含了模型的結構和參數權重,可以通過saver.save
和saver.restore
方法來導出和加載。pickle.dump
函數將模型保存到文件,使用pickle.load
函數加載模型。這些方法提供了不同的方式來將Estimator和Python庫導出,可以根據具體的需求和環境選擇合適的導出方式。
每個 Estimator(無論是預創建還是自定義)的核心都是其模型函數,這是一種為訓練、評估和預測構建圖的方法。如果您使用預創建的 Estimator,則有人已經實現了模型函數。如果您使用自定義 Estimator,則必須自行編寫模型函數。隨附文檔介紹了如何編寫模型函數(https://tensorflow.google.cn/guide/custom_estimators?hl=zh-CN)。
我們推薦以下工作流程:
您可以將現有的 Keras 模型轉換為 Estimator。這樣做之后,Keras 模型就可以利用 Estimator 的優勢,例如分布式訓練。調用
tf.keras.estimator.model_to_estimator(https://tensorflow.google.cn/api_docs/python/tf/keras/estimator/model_to_estimator?hl=zh-CN),如下例所示:
# Instantiate a Keras inception v3 model.
keras_inception_v3 = tf.keras.applications.inception_v3.InceptionV3(weights=None)
# Compile model with the optimizer, loss, and metrics you'd like to train with.
keras_inception_v3.compile(optimizer=tf.keras.optimizers.SGD(lr=0.0001, momentum=0.9),
loss='categorical_crossentropy',
metric='accuracy')
# Create an Estimator from the compiled Keras model. Note the initial model
# state of the keras model is preserved in the created Estimator.
est_inception_v3 = tf.keras.estimator.model_to_estimator(keras_model=keras_inception_v3)
# Treat the derived Estimator as you would with any other Estimator.
# First, recover the input name(s) of Keras model, so we can use them as the
# feature column name(s) of the Estimator input function:
keras_inception_v3.input_names # print out: ['input_1']
# Once we have the input name(s), we can create the input function, for example,
# for input(s) in the format of numpy ndarray:
train_input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn(
x={"input_1": train_data},
y=train_labels,
num_epochs=1,
shuffle=False)
# To train, we call Estimator's train function:
est_inception_v3.train(input_fn=train_input_fn, steps=2000)
請注意,Keras Estimator 的特征列名稱和標簽來自經過編譯的對應 Keras 模型。例如,上面的 train_input_fn 的輸入鍵名稱可以從 keras_inception_v3.input_names 獲得;同樣,預測的輸出名稱可以從 keras_inception_v3.output_names 獲得。
要了解詳情,請參閱 tf.keras.estimator.model_to_estimator 的文檔(https://tensorflow.google.cn/api_docs/python/tf/keras/estimator/model_to_estimator?hl=zh-CN)。
文章轉自微信公眾號@TensorFlow