python - 在 Tensorflow 中,为什么只在准备导出模型时才向模型添加激活函数?
问题描述
在用于制作基本文本分类的 Tensorflow ML Basics with Keras 教程中,在准备要导出的训练模型时,该教程建议将 TextVectorization 层包含到模型中,以便它可以“处理原始字符串”。我明白为什么要这样做。
但是代码片段是:
export_model = tf.keras.Sequential([
vectorize_layer,
model,
layers.Activation('sigmoid')
])
为什么在准备模型导出时,教程中还包含一个新的激活层layers.Activation('sigmoid')
?为什么不将此层合并到原始模型中?
解决方案
在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)
'''
推荐阅读
- java - 在 Spring Boot 应用程序中为 Datadog 配置跟踪
- javascript - 从 Javascript 代码中删除鼠标控件
- reactjs - 如何使用 Google API 只让城镇和地址出现在搜索下拉列表中?
- python - 如何在maya python或mel的导出文件中将变换坐标(如移动到游戏导出器中的原点)归零?
- mysql - 如何在我的 SQL 表中找到总销售额?
- github - Github API 令牌在 Github 页面中的使用
- twilio - Twilio SMS 到多个国家
- amazon-web-services - AWS API Gateway - 通过公司代理发送请求
- c++ - 在 Eclipse 中调试 C - “找不到源文件”
- bash - 多个 gz 文件的第一行