独热编码 one_hot(tensor, num_classes=-1) -> LongTensor
tensor:要编码的张量
num_calsses:类别数,就是下面例子中的列数
import torch
from torch.nn import functional as F
1、无num_classes?
列数与最大值有关:0 -> max,比如下面例子中最大值为8,所以0 -> 8,共9列(相当于labels共9类) 行数与数的个数有关,该例子共8个数,所以8行。 所以shape=(8,9)
x = torch.tensor([1, 1, 1, 3, 3, 4, 8, 5])
y1 = F.one_hot(x) # 只有一个参数张量x
print(f'x = ',x)
print(f'x_shape = ',x.shape)
print(f'y1 = ',y1)
print(f'y1_shape = ',y1.shape)
结果?
x = tensor([1, 1, 1, 3, 3, 4, 8, 5])
x_shape = torch.Size([8])
y = tensor([[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 1, 0, 0, 0]])
y_shape = torch.Size([8, 9])
?
2、有num_classes
num_classes参数可以自行设置列数
y2 = F.one_hot(x, num_classes = 10) # 这里num_classes设置为10,其中 10 > max{x}
print(f'x = ',x) # 输出 x
print(f'x_shape = ',x.shape) # 查看 x 的形状
print(f'y2 = ',y2) # 输出 y
print(f'y2_shape = ',y2.shape)
结果
x = tensor([1, 1, 1, 3, 3, 4, 8, 5])
x_shape = torch.Size([8])
y2 = tensor([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0]])
y2_shape = torch.Size([8, 10])
|