python - Tensorflow:从类标签创建 y 索引
问题描述
我有类标签:
y = ["class1", "class2", "class3"]
为了在模型中使用它们,我想使用 keras 和/或 tensorflow2.0 的方法将这些类转换为 y_indices 为1、2 。
我目前正在做的是:
tokenizer = tf.keras.preprocessing.text.Tokenizer()
tokenizer.fit_on_texts(y)
y_train = tokenizer.texts_to_sequences(y)
我知道标记器在这里被滥用了。有没有更好更小的解决方案将类标签转换为索引?谢谢。
解决方案
您不能为此使用 Tokenizer,因为 Tokenizer 索引从 1 开始,而不是 0。您可以使用tf.where
:
import tensorflow as tf
y = ['class3', 'class1', 'class1', 'class2', 'class3', 'class1', 'class2']
names = ["class1", "class2", "class3"]
labeler = lambda x: tf.where(tf.equal(x, names))
dataset = tf.data.Dataset.from_tensor_slices(y).map(labeler)
next(iter(dataset))
<tf.Tensor: shape=(1, 1), dtype=int64, numpy=array([[2]], dtype=int64)>
如果您想在列表或 Numpy 数组上执行此操作,可以使用 Scikit-Learn:
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
le.fit_transform(y)
array([2, 0, 0, 1, 2, 0, 1], dtype=int64)
正如我之前所说,您的实现从 1 开始索引:
[[2], [1], [1], [3], [2], [1], [3]]
这会使 Keras 在测量损失和指标时崩溃。它会返回nan
,因为您将拥有三个最终神经元,但目标是从第二个索引到第四个。tl; dr不要使用 Keras 的从 1 开始的索引。
推荐阅读
- android - android包名不可用的问题?
- node.js - 使用 npm mssql 添加标识列
- .htaccess - 如何从 URL (.htaccess) 中删除子目录的父目录
- spring - 在 bean 初始化期间使用响应式存储库 - 我需要阻止()吗?
- azure-cognitive-services - LUIS 容器“/luis/v2.0/apps/{appId}/versions/{versionId}”v2.0 端点返回“不支持的插槽名称”错误
- qt - Qt QSpinBox:如何显示大写十六进制数
- python-3.x - 在 Python 3.7 中格式化打印输出
- python - 有效地配对列表的随机元素
- php - phpseclib 2.0 的安装过程不起作用
- apache-kafka - kafka 如何知道是“前滚还是回滚”事务?