machine-learning - 一种热编码增加了目标数据的大小
问题描述
我有多类数据、标签或 y 列包含以下数据:
print(y.unique())
[5 6 7 4 8 3 9] 在这种情况下,类数等于 7(在深度学习建模时),但是当我像这样进行一次热编码时:
import keras
from keras.utils import np_utils
y_train =np_utils.to_categorical(y_train)
y_test =np_utils.to_categorical(y_test)
维度增加到 10
打印(y_train.shape):(4547、10)
可能是因为我们的数字最多为 9 并且 (0,1,2) 也包括在内(实际上它没有在原始数据中表示),我该如何解决这个问题?
解决方案
该函数tf.keras.utils.to_categorical
要求输入是“从 0 到整数num_classes
”(参见文档)。你有一组标签{3, 4, 5, 6, 7, 8, 9}
。总共有七个标签,从值 3 开始。要将其转换为 [0, 7) 中的一组标签,可以从每个标签中减去 3。
y_ints = y - 3
结果可以传递给tf.keras.utils.to_categorical
.
import numpy as np
import tensorflow as tf
y = np.array([3, 4, 5, 6, 7, 8, 9])
y_ints = y - 3 # [0, 1, 2, 3, 4, 5, 6]
tf.keras.utils.to_categorical(y_ints)
输出是
array([[1., 0., 0., 0., 0., 0., 0.],
[0., 1., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0.],
[0., 0., 0., 1., 0., 0., 0.],
[0., 0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 0., 1.]], dtype=float32)
另一种选择是使用 scikit-learn 广泛的预处理方法,特别是sklearn.preprocessing.OneHotEncoder
.
import numpy as np
from sklearn.preprocessing import OneHotEncoder
y = np.array([3, 4, 5, 6, 7, 8, 9])
y = y.reshape(-1, 1) # reshape to (n_samples, n_labels).
encoder = OneHotEncoder(sparse=False, dtype="float32")
encoder.fit_transform(y)
输出是
array([[1., 0., 0., 0., 0., 0., 0.],
[0., 1., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0.],
[0., 0., 0., 1., 0., 0., 0.],
[0., 0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 0., 1.]], dtype=float32)
推荐阅读
- javascript - 为什么在JS中使用for循环遍历数组时页面会报错?
- javascript - 赛普拉斯:在 JSON 响应中存根特定键
- python - 如何将 sympy“向量”转换为 numpy 数组?
- python - 如何在 Dask 中舍入无索引数据框?
- android - Android Room:创建一对一关系实体
- c++ - fib 函数与模板有什么区别?
- javascript - 单击嵌套元素时如何触发相同的事件
- android - 为什么只有某些编译器应用程序才能写入内部存储?
- jquery - 想要选中的下拉菜单
- ssas-tabular - 部署 ssas 表格多维数据集后,我在任何文件夹下都看不到任何对象。你能帮我解决这个问题吗