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