keras中的keras.utils.to_categorical方法

参考链接:https://blog.csdn.net/nima1994/article/details/82468965

参考链接:https://blog.csdn.net/gdl3463315/article/details/82659378

to_categorical(y, num_classes=None, dtype='float32')

将整型的类别标签转为onehot编码。y为int数组,num_classes为标签类别总数,大于max(y)(标签从0开始的)。

返回:如果num_classes=None,返回len(y) * [max(y)+1](维度,m*n表示m行n列矩阵,下同),否则为len(y) * num_classes。

  1. import keras

  2. ohl=keras.utils.to_categorical([1,3])

  3. # ohl=keras.utils.to_categorical([[1],[3]])

  4. print(ohl)

  5. """

  6. [[0. 1. 0. 0.]

  7. [0. 0. 0. 1.]]

  8. """

  9. ohl=keras.utils.to_categorical([1,3],num_classes=5)

  10. print(ohl)

  11. """

  12. [[0. 1. 0. 0. 0.]

  13. [0. 0. 0. 1. 0.]]

  14. """

该部分keras源码如下:

  1. def to_categorical(y, num_classes=None, dtype='float32'):

  2. """Converts a class vector (integers) to binary class matrix.

  3. E.g. for use with categorical_crossentropy.

  4. # Arguments

  5. y: class vector to be converted into a matrix

  6. (integers from 0 to num_classes).

  7. num_classes: total number of classes.

  8. dtype: The data type expected by the input, as a string

  9. (`float32`, `float64`, `int32`...)

  10. # Returns

  11. A binary matrix representation of the input. The classes axis

  12. is placed last.

  13. """

  14. y = np.array(y, dtype='int')

  15. input_shape = y.shape

  16. if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:

  17. input_shape = tuple(input_shape[:-1])

  18. y = y.ravel()

  19. if not num_classes:

  20. num_classes = np.max(y) + 1

  21. n = y.shape[0]

  22. categorical = np.zeros((n, num_classes), dtype=dtype)

  23. categorical[np.arange(n), y] = 1

  24. output_shape = input_shape + (num_classes,)

  25. categorical = np.reshape(categorical, output_shape)

  26. return categorical

简单来说:**keras.utils.to_categorical函数:是把类别标签转换为onehot编码(categorical就是类别标签的意思,表示现实世界中你分类的各类别), 而onehot编码是一种方便计算机处理的二元编码。**