one hot 编码
One Hot编码,又称为一位有效编码,主要是采用N位状态寄存器来对N个状态进行编码,每个状态都由他独立的寄存器位,并且在任意时候只有一位有效。
One Hot编码是分类变量作为二进制向量的表示。这首先要求将分类值映射到整数值。然后,每个整数值被表示为二进制向量,除了整数的索引之外,它都是零值,它被标记为1。
import torch
x = torch.tensor([[0.9413, 0.9476, 0.1104, 0.9898, 0.6443],
[0.6913, 0.8924, 0.7530, 0.8874, 0.0557]])
result = torch.zeros(3, 5)
indices = torch.tensor([[0, 1, 2, 0, 0],
[2, 0, 0, 1, 2]])
result.scatter_(0, indices, x)
# 输出
tensor([[0.9413, 0.8924, 0.7530, 0.9898, 0.6443],
[0.0000, 0.9476, 0.0000, 0.8874, 0.0000],
[0.6913, 0.0000, 0.1104, 0.0000, 0.0557]])
上例中,dim=0,所以根据这个规则来self[ index[i][j] ] [j] = src[i][j]来确定替换规则。
index中的值决定了src中的值在result中的放置位置。
dim=0时,则将列固定起来,先看第0列:
对于第0行,首先找到x的第0列第0行的值为0.9413,然后在用index[0][0]的值来找将要在result中放置的位置。
在这个例子中,index[0][0]=0, 所以0.9413将放置在result[0][0]这个位置。
对于result中的各项,他们的寻址过程如下:
x[0][1] = 0.9476 -> indices[0][1]=1 -> result[ index = 1 ][1] = 0.9476
x[1][3] = 0.8874 -> indices[1][3]=1 -> result[ index = 1 ][3] = 0.8874
x = torch.tensor([[0.9413, 0.9476, 0.1104, 0.9898, 0.6443],
[0.6913, 0.8924, 0.7530, 0.8874, 0.0557]])
result = torch.zeros(3, 5)
indices = torch.tensor([[0, 1, 2, 0, 0],
[2, 0, 0, 1, 2]])
result.scatter_(1, indices, x)
# 输出
tensor([[0.6443, 0.9476, 0.1104, 0.0000, 0.0000],
[0.7530, 0.8874, 0.0557, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000]])
x[0][0] = 0.9413 -> indices[0][0]=0 -> result[0][index = 0] = 0.9413
x[0][3] = 0.9898 -> indices[0][3]=0 -> result[0][index = 0] = 0.9898 ## 将上一步的值覆盖了
x[0][4] = 0.6443 -> indices[0][4]=0 -> result[0][index = 0] = 0.6443 ## 再次将上一步的值覆盖了
因此result[0][0]的值为0.6443.