【函数小trick】torch中scatter()、scatter_()详解(多标签one-hot向量生成)

1. 背景

可以先看torch官方文档介绍:

主要作用是根据索引值index,向tensor中指定dim维度的index位置写入scr所对应的数值,可以用来生成one-hot向量和特定mask,熟练使用该函数,就不用暴力for循环啦。

2. 函数应用

(1)one-hot向量生成

将图像的标签值转换为一组只有0和1组成的向量,这是DL领域常用到的。

import torch
targets=torch.zeros(3,5)
index = torch.LongTensor([[3],[2],[5]])
targets.scatter_(1,index-1,1)
print(targets.size(),index.size())
print(targets)

要注意维度:

(2)多标签或mask的one-hot向量生成

import torch
targets=torch.zeros(3,5)
index1 = torch.LongTensor([[3],[2],[5]])
index2 = torch.LongTensor([[1],[2],[4]])
targets.scatter_(1,index1-1,1)
targets.scatter_(1,index2-1,1)
print(targets)

结果:

(3)根据位置插入指定值

import torch
targets=torch.zeros(3,5)
scr1=torch.Tensor([[0.1],[0.2],[0.3]])
scr2=torch.Tensor([[0.6],[0.5],[0.4]])
index1 = torch.LongTensor([[3],[2],[5]])
index2 = torch.LongTensor([[1],[2],[4]])
targets.scatter_(1,index1-1,scr1)
targets.scatter_(1,index2-1,scr2)
print(targets)

结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值