【问题标题】:Categorical level to one hot encoding in python tensorflowpython tensorflow中一种热编码的分类级别
【发布时间】:2018-12-17 20:21:21
【问题描述】:
如果我有这样的分类标签
labels = [cat,dog, bird, cow]
现在我想将它转换为一种热编码。是否可以通过使用张量流。
像这样
output_label = [[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]]
【问题讨论】:
标签:
python-3.x
tensorflow
machine-learning
【解决方案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_hothere的信息。