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

先前的其他两种方法