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

本文介绍了独热编码(One-Hot Encoding)的概念,通过PyTorch库的F.one_hot函数展示了编码过程。无num_classes参数时,编码列数根据输入张量的最大值确定;设置num_classes参数可自定义列数。独热编码常用于将分类数据转换为机器学习模型可处理的数值形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值