2017-01-23 45 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