如何使用 Estimators 在 TensorFlow 中建立特徵列和輸入函式?


TensorFlow 可以結合 Estimators 使用 one-hot 編碼方法來建立特徵列和輸入函式。“feature_column.indicator_column” 用於返回此 one-hot 編碼技術的輸出。

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

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

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

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

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

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

示例

CATEGORICAL_COLUMNS = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck', 'embark_town', 'alone']
NUMERIC_COLUMNS = ['age', 'fare']
print("The method to use one hot encoding technique")
def one_hot_cat_column(feature_name, vocab):
return tf.feature_column.indicator_column(
tf.feature_column.categorical_column_with_vocabulary_list(feature_name, vocab))
feature_columns = []
print("One hot encode categorical features")
for feature_name in CATEGORICAL_COLUMNS:
vocabulary = dftrain[feature_name].unique()
feature_columns.append(one_hot_cat_column(feature_name, vocabulary))
for feature_name in NUMERIC_COLUMNS:
feature_columns.append(tf.feature_column.numeric_column(feature_name, dtype=tf.float32))

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

輸出

The method to use one hot encoding technique
One hot encode categorical features

解釋

  • CATEGORICAL_COLUMNS 中的欄位從分類列轉換為 one-hot 編碼列。

  • 在此之前,它首先被轉換為指示符列。

  • 獲取分類特徵。

更新於:2021年2月25日

98 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.