【Pytorch | Tensorflow】--- label與one-hot獨熱編碼向量之間的相互轉換

在多分類任務中,通常將目標轉換成獨熱編碼來進行訓練,本文將介紹

一. Pytorch操作

1.1. label \rightarrow one-hot向量

使用 scatter_() 來轉換:

如使用獨熱進行編碼:

label = torch.LongTensor([[1], [5], [7], [2], [9]])
'''
tensor([[1.],
        [5.],
        [7.],
        [2.],
        [9.]])
'''

one_hot_label = torch.zeros(5, 10).scatter_(1, label, 1)
'''
tensor([[0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],
        [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]])
'''

1.2. one-hot編碼 \rightarrow label

通過 argmax() 得到先前的向量。

如:

results = one_hot_label.argmax(dim=1, keepdim=True)
'''
tensor([[1],
        [5],
        [7],
        [2],
        [9]])
'''

於是就成功復原了


二. tensorflow操作

2.1. label \rightarrow one-hot向量


import tensorflow as tf

label = tf.stack(5)
one_hot_label = tf.one_hot(label, 10)

sess = tf.Session()
print("label: ", sess.run(label))
print("one_hot_label: ", sess.run(one_hot_label))
# 輸出
label:  5
one_hot_label:  [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章