首页 > 解决方案 > 在 Tensorflow 中,为什么只在准备导出模型时才向模型添加激活函数?

问题描述

在用于制作基本文本分类的 Tensorflow ML Basics with Keras 教程中,在准备要导出的训练模型时,该教程建议将 TextVectorization 层包含到模型中,以便它可以“处理原始字符串”。我明白为什么要这样做

但是代码片段是:

export_model = tf.keras.Sequential([
  vectorize_layer,
  model,
  layers.Activation('sigmoid')
])

为什么在准备模型导出时,教程中还包含一个新的激活层layers.Activation('sigmoid')?为什么不将此层合并到原始模型中?

标签: pythontensorflowkerasactivation-function

解决方案


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)
'''

推荐阅读