keras.np_utils.to_categorical()其作用是將整形的標(biāo)簽轉(zhuǎn)換為onehot編碼竖共。第二個(gè)參數(shù)num_class的作用是指定標(biāo)簽總類別京革,若不指定則默認(rèn)绳泉。
```
import keras
ohl=keras.utils.to_categorical([1,3])
# ohl=keras.utils.to_categorical([[1],[3]])
print(ohl)
"""
[[0. 1. 0. 0.]
[0. 0. 0. 1.]]
"""
ohl=keras.utils.to_categorical([1,3],num_classes=5)
print(ohl)
"""
[[0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0.]]
"""
```
這部分的源碼如下
```
def to_categorical(y, num_classes=None, dtype='float32'):
? ? """Converts a class vector (integers) to binary class matrix.
? ? E.g. for use with categorical_crossentropy.
? ? # Arguments
? ? ? ? y: class vector to be converted into a matrix
? ? ? ? ? ? (integers from 0 to num_classes).
? ? ? ? num_classes: total number of classes.
? ? ? ? dtype: The data type expected by the input, as a string
? ? ? ? ? ? (`float32`, `float64`, `int32`...)
? ? # Returns
? ? ? ? A binary matrix representation of the input. The classes axis
? ? ? ? is placed last.
? ? """
? ? y = np.array(y, dtype='int')
? ? input_shape = y.shape
? ? if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
? ? ? ? input_shape = tuple(input_shape[:-1])
? ? y = y.ravel()
? ? if not num_classes:
? ? ? ? num_classes = np.max(y) + 1
? ? n = y.shape[0]
? ? categorical = np.zeros((n, num_classes), dtype=dtype)
? ? categorical[np.arange(n), y] = 1
? ? output_shape = input_shape + (num_classes,)
? ? categorical = np.reshape(categorical, output_shape)
? ? return categorical
```
源碼里面可以看出冠跷,若不指定num_class合是,則其結(jié)果就是max(y)+1衫樊。