TensorFlow Estimator 教程之----快速入門

TensorFlow 版本:1.10.0 > Guide > Introduction to Estimators

Estimator 概述
本篇將介紹 TensorFlow 中的 Estimators(可極大簡化機器學習編程過程)。Estimators 中封裝了以下幾部分:

  • 訓練(training)
  • 評估(evaluation)
  • 預測(prediction)
  • 輸出模型(export for serving)

我們既可以使用內置 Estimator,也可以編寫自定義 Estimator。

注意:TensorFlow 中的 tf.contrib.learn.Estimator 已經棄用了,請不要使用該 API。

1. Estimator 的優勢

Estimator 有以下優勢:

  • 對分佈式的良好支持(不需要更改代碼)。
  • 有利於模型開發者之間的代碼分享。
  • 簡化了模型的創建工作。
  • Estimator 建立在 `tf.layers` 上,這簡化了自定義 Estimator 的編寫。
  • Estimator 會爲你創建 graph。
  • Estimator 提供了一個安全的分佈式訓練環境,其會幫我們控制這麼、何時去:

    • 建立 graph。
    • 初始化 variables。
    • 開始 queues。
    • 處理 exceptions。
    • 創建 checkpoint 文件,從失敗中恢復訓練。
    • 保存 summaries for TensorBoard。

當用 Estimator 編寫一個 application,你必須將 input pipeline 和 model 分開。這種分離簡化了在不同數據集上的 experiments。

2. 內置的 Estimator

內置的 Estimator 使得你可以在更高層面思考問題。內置的 Estimator 會爲你創建、管理 Graph 和 Session 對象。另外,內置的 Estimator 使你可以在最小的代碼修改量的情況下實驗不同的模型結構。

2.1 基於內置 Estimator 的程序的結構

使用內置 Estimator 的 TF 程序一般包含以下四步:

  1. 編寫一個或多個數據集導入函數。 例如:創建一個函數來導入訓練數據集,另一個函數來導入測試數據集。每一個數據集導入函數必須返回兩個對象:

    • 一個字典。字典的鍵名爲特徵的名字,鍵值爲 表示特徵數據的 Tensor 或 Sparse Tensor。
    • 一個 Tensor。該 Tensor 包含一個或多個 label。

    例如,下面的代碼說明了 input function 的基本框架:

    def input_fn(dataset):
       ...  # manipulate dataset, extracting the feature dict and the label
       return feature_dict, label
    

    (更多細節詳見 Importing Data。)

  2. 定義 feature columns。每一個 tf.feature_column 定義了一個 feature 的名字、類型、預處理。例如,下面的代碼片段定義了三個 feature columns 來 Hold 整數、浮點 類型的數據。前兩個 feature columns 只是簡單的定義了特徵的名字和類型。第三個 feature column 還使用了一個 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)
    
  3. 實例化相應的內置 Estimator。 例如,實例化一個 LinearClassifier

    # Instantiate an estimator, passing the feature columns.
    estimator = tf.estimator.LinearClassifier(
        feature_columns=[population, crime_rate, median_education],
        )
    
  4. 調用一個 training、evaluation、inference 方法。例如,所有的 Estimator 提供了一個 train 方法來訓練一個模型。

    # my_training_set is the function created in Step 1
    estimator.train(input_fn=my_training_set, steps=2000)
    

2.2 內置 Estimator 的好處

內置 Estimator 的代碼實現是最好的,另外其提供了以下好處:

  • 對於分佈式的支持是最好的。
  • 保存 summaries 的保存策略是最好的。

如果你不使用內置 Estimator,你必須自己編寫自定義函數來實現上面的特性。

3. 編寫自定義 Estimator

Estimator 的核心是 model function,該函數負責 training、evaluation、prediction 計算圖的建立。我們在另一個文檔介紹了自定義 Estimator 的方法。

4. 推薦的工作流程

我們推薦的工作流程如下:

  1. 如果有合適的內置 Estimator,用它來作爲你的第一個模型,將其結果作爲一個基線。
  2. 基於內置 Estimator 建立、測試整個輸入 pipeline(數據的完整性、可靠性)。
  3. 如果有更好的內置 Estimator 可用,可以根據實驗的結果來確定哪個內置 Estimator 更合適。
  4. 可能的話,通過編寫自定義 Estimator 來進一步提高模型性能。

5. 從 Keras 模型創建 Estimator

Keras 模型可以轉換爲 Estimator。這使得你的 Keras 模型能夠利用 Estimator 的優勢(比如:分佈式訓練)。轉換通過 tf.keras.estimator.model_to_estimator 完成。

# 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'] >>>>>>> Very Important <<<<<<<
# 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.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 的 feature columns 和 labels 的 name 要與 keras 模型輸入輸出的 name 保持一致。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章