Pytorch之torch..nn.functional.one_hot()

独热编码
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])

  • 14
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值