我有多类别数据,标签或y列包含以下数据:
print(y.unique())
[5 6 7 4 8 3 9]在这种情况下,类别的数量等于7(在深度学习建模时),但当我执行以下独热编码时:
import kerasfrom keras.utils import np_utilsy_train =np_utils.to_categorical(y_train)y_test =np_utils.to_categorical(y_test)
维度增加到了10
print(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 npimport tensorflow as tfy = 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 npfrom sklearn.preprocessing import OneHotEncodery = 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)