Pytorch下 label 的 one-hot 形式轉換方法


2020.10.1 發現最新的 pytorch 已經原生支持 one-hot 操作
torch.nn.functional.one_hot()pytorch 官方文檔鏈接

只需如下一行代碼:
label_one_hot = torch.nn.functional.one_hot(labels, self.num_classes).float().to(self.device)

也可用如下的方法:

def encode_onehot(labels):
    classes = set(labels)
    classes_dict = {c: np.identity(len(classes))[i, :] for i, c in
                    enumerate(classes)}
    labels_onehot = np.array(list(map(classes_dict.get, labels)),
                             dtype=np.int32)
    return labels_onehot

先前的其他兩種方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM