如果我有一个这样的分类标签
labels = [cat,dog, bird, cow]
现在我想把它转换成独热编码。是否可以使用TensorFlow来实现这样的转换
output_label = [[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]
回答:
首先,您需要将分类数据转换为数值格式。您可以这样做,例如:
def categorical_to_numerical(labels): num_labels=[] for k in labels: if k == 'cat': num_labels.append(0) if k == 'dog': num_labels.append(1) if k == 'bird': num_labels.append(2) if k == 'cow': num_labels.append(3) return num_labelsprint labels// prints ['cat','dog', 'bird', 'cow', 'dog', 'bird'] print categorical_to_numerical(labels)// prints [0, 1, 2, 3, 1, 2]
现在您可以轻松使用TensorFlow内置的tf.one_hot
函数:
indices = categorical_to_numerical(labels)detph = 4 // because you have four categories one_hot_labels = tf.one_hot(indices, depth)
了解更多关于tf.one_hot
的信息,请点击这里。