2017-01-23 47 views
2

我是Tensorflow(和神经网络)的新手,我正在研究一个简单的分类问题。想问2个问题。Tensorflow One-Hot

假设我有120个[1,2,3,4,5]置换的标签。在将它喂入我的图形之前,对我进行单热编码是否真的有必要?如果是的话,我应该在进入tensorflow之前进行编码吗?

如果我做单热编码,softmax预测会给[0.001 0.202 0.321 ...... 0.002 0.0003 0.0004]。运行arg_max将产生正确的索引。我如何得到张量流返回给我正确的标签,而不是一个热门的结果?

谢谢。

回答

1

因此,您的输入是{1,2,3,4,5}中的120个标签(每个标签可以是1到5之间的数字)?

# Your input, a 1D tensor of 120 elements from 1-5. 
# Better shift your label space to 0-4 instead. 
labels = labels - 1 

# Now convert to a 2D tensor of 120 x 5 onehot labels. 
onehot_labels = tf.one_hot(labels, 5) 

# Now some computations. 
.... 

# You end up with some onehot_output 
# of the same shape as your labels (120x5). 
# As you said, arg_max will give you the index of the result, 
# which is a 1D index label of 120 elements. 
output = tf.argmax(onehot_output, axis=1). 

# You might want to shift back to {1,2,3,4,5}. 
output = output + 1 
+1

嗨Guinny,谢谢你的回答。我正在尝试你的答案,但它不适用于tf.float32类型作为输入。我不得不保持这种类型,因为有些操作需要它在流中的tf.float32。我在下游计算之前尝试过tf.cast(标签,tf.float32),但这没有帮助。 – Jax