如何使用TensorFlow和Estimator定義用於資料集訓練和評估的輸入函式?


TensorFlow和Estimator可用於定義用於資料集訓練和評估的輸入函式,該函式使用特徵和標籤生成字典。這是使用“from_tensor_slices”方法實現的。此函式還將對資料集中資料進行混洗,並定義訓練步驟的數量。最後,此函式將資料集的組合資料作為輸出返回。此函式透過向其傳遞訓練資料集來呼叫。

閱讀更多: 什麼是TensorFlow以及Keras如何與TensorFlow一起建立神經網路?

我們將使用Keras Sequential API,它有助於構建順序模型,該模型用於處理簡單的層堆疊,其中每一層只有一個輸入張量和一個輸出張量。

包含至少一層卷積層的神經網路稱為卷積神經網路。我們可以使用卷積神經網路構建學習模型。

我們正在使用Google Colaboratory執行以下程式碼。Google Colab或Colaboratory有助於在瀏覽器上執行Python程式碼,無需任何配置,並可免費訪問GPU(圖形處理單元)。Colaboratory構建在Jupyter Notebook之上。

讓我們瞭解如何使用 Estimators。

Estimator是TensorFlow對完整模型的高階表示。它旨在易於擴充套件和非同步訓練。

我們將使用tf.estimator API訓練一個邏輯迴歸模型。該模型用作其他演算法的基線。我們使用泰坦尼克號資料集,目標是根據性別、年齡、等級等特徵預測乘客的生存情況。

Estimator使用特徵列來描述模型如何解釋原始輸入特徵。Estimator期望一個數值輸入向量,特徵列將有助於描述模型應該如何轉換資料集中每個特徵。

示例

print("The entire batch of dataset is used since it is small")
NUM_EXAMPLES = len(y_train)
print("Function that iterates through the dataset, in memory training")
def make_input_fn(X, y, n_epochs=None, shuffle=True):
def input_fn():
dataset = tf.data.Dataset.from_tensor_slices((dict(X), y))
if shuffle:
   dataset = dataset.shuffle(NUM_EXAMPLES)
   dataset = dataset.repeat(n_epochs)
   dataset = dataset.batch(NUM_EXAMPLES)
   return dataset
return input_fn
print("Training and evaluation input function have been defined")
train_input_fn = make_input_fn(dftrain, y_train)
eval_input_fn = make_input_fn(dfeval, y_eval, shuffle=False, n_epochs=1)

程式碼來源 −https://www.tensorflow.org/tutorials/estimator/boosted_trees

輸出

The entire batch of dataset is used since it is small
Function that iterates through the dataset, in memory training
Training and evaluation input function have been defined

解釋

  • 需要建立輸入函式。
  • 它指定資料將如何讀取到模型中以進行訓練和推理。
  • tf.data API中的from_tensor_slices方法用於直接從Pandas庫讀取資料。
  • 這適用於較小的記憶體中資料集。
  • 如果資料集很大,可以使用tf.data API,因為它支援各種檔案格式。

更新於:2021年2月25日

瀏覽量:117

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.