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