python将标签转化为one-hot(独热编码)

问题描述:在利用categorical_crossentropy作为损失函数时,需要将标签设定为one-hot格式,即每个标签的长度应转换为一个长度为类别数的向量,该向量除了所属的类别位置为1之外,其他位置值为0.

from keras.utils.np_utils import to_categorical
categorical_labels = to_categorical(int_labels, num_classes=None)

示例:

import numpy as np
int_labels = np.array([2,1,3,5])
from keras.utils.np_utils import to_categorical
categorical_labels = to_categorical(int_labels, num_classes=None)
print(categorical_labels)

python将标签转化为one-hot(独热编码)_第1张图片

你可能感兴趣的:(python将标签转化为one-hot(独热编码))