本文說明如何使用 tf.transform 進行常用轉換。
我們假設您已根據範例建構 Beam 管線,並且僅說明需要新增至 preprocessing_fn
和可能的模型中的內容。
使用字串/類別資料
以下 preprocessing_fn
將計算特徵 x
值的詞彙表,並依頻率降序排列符記、將特徵 x
值轉換為其在詞彙表中的索引,並最終對輸出執行單熱編碼。
這在標籤特徵是類別字串的使用案例中很常見。產生的單熱編碼已準備好用於訓練。
def preprocessing_fn(inputs):
integerized = tft.compute_and_apply_vocabulary(
inputs['x'],
num_oov_buckets=1,
vocab_filename='x_vocab')
one_hot_encoded = tf.one_hot(
integerized,
depth=tf.cast(tft.experimental.get_vocabulary_size_by_name('x_vocab') + 1,
tf.int32),
on_value=1.0,
off_value=0.0)
return {
'x_out': one_hot_encoded,
}
遺失資料的平均值插補
在此範例中,特徵 x
是選用特徵,在 preprocessing_fn
中表示為 tf.SparseTensor
。為了將其轉換為密集張量,我們計算其平均值,並在執行個體中遺失時將平均值設定為預設值。
產生的密集張量形狀為 [None, 1]
,None
代表批次維度,而第二個維度是每個執行個體 x
可以擁有的值數量。在此案例中為 1。
def preprocessing_fn(inputs):
return {
'x_out': tft.sparse_tensor_to_dense_with_shape(
inputs['x'], default_value=tft.mean(x), shape=[None, 1])
}