您必须确保您的列表中确实只有 6 个不同的标签,并且它们从 0 开始,并且范围仅到 num_classes-1。
tf.keras.utils.to_categorical(y, num_classes=None, dtype='float32')
参数:
- y :要转换为矩阵的类向量(从 0 到 num_classes 的整数)。
- num_classes :类的总数。如果没有,这将被推断为(y 中的最大数)+ 1
© TensorFlow:异构系统上的大规模机器学习,2015 年。(CC BY 4.0),来源:https://www.tensorflow.org/api_docs/python/tf/keras/utils/to_categorical
否则会失败。此外,tf.utils.keras 在您的函数调用中可能是错误的方式。
>>>import tensorflow as tf
>>>tf.keras.utils.to_categorical([0,1,2,3,4,5], 6)
array([[1., 0., 0., 0., 0., 0.],
[0., 1., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0.],
[0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 1.]], dtype=float32)
有效,但是
>>>tf.keras.utils.to_categorical([0, 200, 210, 220, 230, 240], 6)
IndexError: index 200 is out of bounds for axis 1 with size 6
失败。您还可以将 num_classes 设置为 None。这会起作用,但它也会将您的一个热编码标签的长度增加到max([0, 200, 210, 220, 230, 240]) + 1
>>>tf.keras.utils.to_categorical([0, 200, 210, 220, 230, 240], None)
array([[1., 0., 0., ..., 0., 0., 0.], ... ], dtype=float32)
# with
# len([1., 0., 0., ..., 0., 0., 0.]) == 241
您可以使用sklearn.preprocessing.LabelEncoder 来准备/规范您的标签:
>>>from sklearn import preprocessing
>>>le = preprocessing.LabelEncoder()
>>>le.fit([1, 2, 2, 6])
LabelEncoder()
>>>le.classes_
array([1, 2, 6])
>>>le.transform([1, 1, 2, 6])
array([0, 0, 1, 2]...)
>>>le.inverse_transform([0, 0, 1, 2])
array([1, 1, 2, 6])
© 2007 - 2020,scikit-learn 开发人员(BSD 许可证),来源:https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html