首页 > 解决方案 > 一种热编码增加了目标数据的大小

问题描述

我有多类数据、标签或 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) 也包括在内(实际上它没有在原始数据中表示),我该如何解决这个问题?

标签: machine-learningkeras

解决方案


该函数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)

推荐阅读