我一直在關注這里的 tensorflow 演練來創建我自己的分類 OHE 層。建議的層在下面,我非常密切地按照前面的步驟操作指南:
def get_category_encoding_layer(name, dataset, dtype, max_tokens=None):
# Create a StringLookup layer which will turn strings into integer indices
if dtype == 'string':
index = preprocessing.StringLookup(max_tokens=max_tokens)
else:
index = preprocessing.IntegerLookup(max_tokens=max_tokens)
# Prepare a Dataset that only yields our feature
feature_ds = dataset.map(lambda x, y: x[name])
# Learn the set of possible values and assign them a fixed integer index.
index.adapt(feature_ds)
# Create a Discretization for our integer indices.
encoder = preprocessing.CategoryEncoding(num_tokens=index.vocabulary_size())
# Apply one-hot encoding to our indices. The lambda function captures the
# layer so we can use them, or include them in the functional model later.
return lambda feature: encoder(index(feature))
但是,輸出與指南不一致。當我對該層的輸入是一個包含 n 個字串的串列,而不是輸出是形狀(n,詞匯大小)時,我收到的是形狀(1,詞匯大小)的輸出,其中多個類別被錯誤地標記為“1”。例如,使用 n=2 和詞匯量大小=3 而不是得到 OHE [[1, 0, 0], [0, 1, 0]],而是得到[1, 1, 0].
我的代碼與指南完全相同,但看起來該層正在“合并”我輸入的每個元素的編碼。他們提供的層是否有問題,或者有人可以指出我可以測驗的內容嗎?
uj5u.com熱心網友回復:
默認情況下,CategoryEncoding 使用 output_mode="multi_hot"。這就是為什么您得到大小為 (1, vocab_size) 的輸出。要獲得大小 (n, vocab_size) 的 OHE,請在您的代碼中進行此更改
encoder = preprocessing.CategoryEncoding(num_tokens=index.vocabulary_size(), output_mode='one_hot')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/318302.html
