pytorch标签转onehot形式实例

yipeiwu_com6年前Python基础

代码:

import torch

class_num = 10
batch_size = 4
label = torch.LongTensor(batch_size, 1).random_() % class_num
print(label.size())

one_hot = torch.zeros(batch_size, class_num).scatter_(1, label, 1)
print(one_hot)

输出:

torch.Size([4, 1])
tensor([[0., 0., 0., 0., 0., 0., 0., 1., 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., 1.]])

注意:

label的形状必须是[n,1]的,也就是必须是二维的,且第二个维度长度为1,如果是一维度的,则需要升维度,代码如下:

import torch

class_num = 10
batch_size = 4
label = torch.LongTensor(batch_size).random_() % class_num
print(label.size())
label = torch.unsqueeze(label,dim=1)
print(label.size())

以上这篇pytorch标签转onehot形式实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

用python打印1~20的整数实例讲解

用python打印1~20的整数实例讲解

while语句打印1-20的整数,并且每行打印五个数,为了实现每行5个数,我们使用一个if判断语句来实现,判断当打印出5个数之后,自动换行打印出来,直至完全输出来。希望对正在学习pyth...

对python3中的RE(正则表达式)-详细总结

对python3中的RE(正则表达式)-详细总结

1.引入正则模块(Regular Expression) 要使用python3中的RE则必须引入 re模块 import re #引入正则表达式 2.主要使用的方法 match()...

python判断图片宽度和高度后删除图片的方法

本文实例讲述了python判断图片宽度和高度后删除图片的方法。分享给大家供大家参考。具体分析如下: Image对象有open方法却没有close方法,如果打开图片,判断图片高度和宽度,判...

Python实现图片拼接的代码

具体代码如下所示: import os from PIL import Image UNIT_SIZE = 220 # the size of image save_path = '...

Python开发WebService系列教程之REST,web.py,eurasia,Django

在Bioinformatics(生物信息学)领域,WebService是很重要的一种数据交换技术,未来必将更加重要。目前EBI所提供的WebService就分别有SOAP和REST两种方...