Pytorch框架之one_hot编码函数

one_hot方法

  • one_hot编码定义
  • Pytorch中one_hot转换

                         QQ:3020889729                                                                                 小蔡

one_hot编码定义

在一个给定的向量中,按照设定的最值–可以是向量中包含的最大值(作为最高分类数),有也可以是自定义的最大值,设计one_hot编码的长度:最大值+1【详见举的例子吧】。

然后按照最大值创建一个1*(最大值+1)的维度大小的全零零向量:[0, 0, 0, …] => 共最大值+1对应的个数

接着按照向量中的值,从第0位开始索引,将向量中值对应的位置设置为1,其他保持为0.

eg:
假设设定one_hot长度为4(最大值) –
且当前向量中值为1对应的one_hot编码:
[0, 1, 0, 0]
当前向量中值为2对应的one_hot编码:
[0, 0, 1, 0]

eg:
假设设定one_hot长度为6(等价最大值+1) –
且当前向量中值为4对应的one_hot编码:
[0, 0, 0, 0, 1, 0]
当前向量中值为2对应的one_hot编码:
[0, 0, 1, 0, 0, 0]

eg:
targets = [4, 1, 0, 3] => max_value=4=>one_hot的长度为(4+1)
假设设定one_hot长度为5(最大值) –
且当前向量中值为4对应的one_hot编码:
[0, 0, 0, 0, 1]
当前向量中值为1对应的one_hot编码:
[0, 1, 0, 0, 0]

Pytorch中one_hot转换

import torch

targets = torch.tensor([5, 3, 2, 1])

targets_to_one_hot = torch.nn.functional.one_hot(targets)   # 默认按照targets其中的最大值+1作为one_hot编码的长度
# result: 
# tensor(
# [0, 0, 0, 0, 0, 1],
# [0, 0, 0, 1, 0, 0],
# [0, 0, 1, 0, 0, 0],
# [0, 1, 0, 0, 0, 0]
#)

targets_to_one_hot = torch.nn.functional.one_hot(targets, num_classes=7)  3# 指定one_hot编码长度为7
# result: 
# tensor(
# [0, 0, 0, 0, 0, 1, 0],
# [0, 0, 0, 1, 0, 0, 0],
# [0, 0, 1, 0, 0, 0, 0],
# [0, 1, 0, 0, 0, 0, 0]
#)

总结:one_hot编码主要用于分类时,作为一个类别的编码–方便判别与相关计算;
【1. 如同类别数统计,只需要将one_hot编码相加得到一个一维向量就知道了一批数据中所有类别的预测或真实的分布情况;
2. 相比于预测出具体的类别数–43等,用向量可以使用向量相关的算法进行时间上的优化等等】

你可能感兴趣的:(pytorch,python,人工智能,深度学习,pytorch)