python tensorflow中的一个热门编码的类别级别



如果我有一个类似的分类标签

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_labels
print labels
// prints ['cat','dog', 'bird', 'cow', 'dog', 'bird'] 
print categorical_to_numerical(labels)
// prints [0, 1, 2, 3, 1, 2]

现在,您可以轻松使用名为tf.one_hot:的tensorflow内置函数

indices = categorical_to_numerical(labels)
detph = 4 // because you have four categories 
one_hot_labels = tf.one_hot(indices, depth) 

点击此处了解更多关于tf.one_hot的信息。

最新更新