pytorch中 torch.nn.functional 中的one_hot 函数
In [23]:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import torch.nn.functional as F
import torch
a = torch.tensor([[1,2],[1,5],[1,2],[1,2]])
F.one_hot(a) # 依次对张量i中的每个元素进行one hot 编码, 返回的形状为 (*, num_classes), 类似与 位置编码, 新增一个维度
# 当不传入 num_classes 参数, torch会自动判断,使用最小分类数,如上面所示, 最小分类数为5, 即表示[0,5]的所有分类, 总共6个数字
Out[23]:
tensor([[[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0]],
[[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1]],
[[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0]],
[[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0]]])
In [16]:
# 同样可以指定分类数
a = torch.tensor([[1,2],[1,2],[1,2],[1,2]])
F.one_hot(a, num_classes=4)
Out[16]:
tensor([[[0, 1, 0, 0],
[0, 0, 1, 0]],
[[0, 1, 0, 0],
[0, 0, 1, 0]],
[[0, 1, 0, 0],
[0, 0, 1, 0]],
[[0, 1, 0, 0],
[0, 0, 1, 0]]])
知识是我们已知的
也是我们未知的
基于已有的知识之上
我们去发现未知的
由此,知识得到扩充
我们获得的知识越多
未知的知识就会更多
因而,知识扩充永无止境