在使用 Keras 進行基本文本分類的 Tensorflow ML Basics 教程中,在準備匯出的訓練模型時,該教程建議將 TextVectorization 層包含到模型中,以便它可以“處理原始字串”。我明白為什么要這樣做。
但隨后的代碼片段是:
export_model = tf.keras.Sequential([
vectorize_layer,
model,
layers.Activation('sigmoid')
])
為什么在準備匯出模型時,教程還包括一個新的激活層layers.Activation('sigmoid')?為什么不將此層合并到原始模型中?
uj5u.com熱心網友回復:
在TextVectorization引入圖層之前,您必須手動編輯原始字串。這通常意味著洗掉標點符號、小寫字母、標記化等:
#Raw String
"Furthermore, he asked himself why it happened to Billy?"
#Remove punctuation
"Furthermore he asked himself why it happened to Billy"
#Lower-case
"furthermore he asked himself why it happened to billy"
#Tokenize
['furthermore', 'he', 'asked', 'himself', 'why', 'it', 'happened', 'to', 'billy']
如果TextVectorization在匯出時將圖層包含在模型中,則基本上可以將原始字串輸入模型進行預測,而無需先清理它們。
關于你的第二個問題:我也覺得sigmoid沒有使用激活函式很奇怪。我想最后一層由于資料集及其樣本而具有“線性激活函式”。樣本可以分為兩類,解決線性可分問題。
推理期間線性激活函式的問題在于它可以輸出負值:
# With linear activation function
examples = [
"The movie was great!",
"The movie was okay.",
"The movie was terrible..."
]
export_model.predict(examples)
'''
array([[ 0.4543204 ],
[-0.26730654],
[-0.61234593]], dtype=float32)
'''
例如,該值-0.26730654可以指示評論“電影還可以”。是否定的,但情況并非一定如此。人們真正想要預測的是特定樣本屬于特定類別的概率。因此,在推理中使用 sigmoid 函式將輸出值壓縮在 0 和 1 之間。然后可以將輸出解釋為樣本x屬于類的概率n:
# With sigmoid activation function
examples = [
"The movie was great!",
"The movie was okay.",
"The movie was terrible..."
]
export_model.predict(examples)
'''
array([[0.6116659 ],
[0.43356845],
[0.35152423]], dtype=float32)
'''
uj5u.com熱心網友回復:
有時您想在 sigmoid 之前知道模型的答案,因為它可能包含有用的資訊,例如,關于分布形狀及其演變。在這種情況下,將最終縮放作為一個單獨的物體是很方便的。否則將不得不洗掉/添加 sigmoid 層——更多的代碼行,更多可能的錯誤。因此,在最后應用 sigmoid 可能是一個很好的做法 - 就在保存/匯出之前。或者只是一個協議。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/330646.html
