pytorch masked_fill

本文介绍如何在PyTorch中使用masked_fill方法来修改张量中的特定元素,并给出一个具体的例子,展示了如何将mask为1的位置用特定值替换,并进行softmax操作。

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

import torch.nn.functional as F
import numpy as np
a = torch.Tensor([1,2,3,4])
a = a.masked_fill(mask = torch.ByteTensor([1,1,0,0]), value=-np.inf)

print(a)
b = F.softmax(a)
print(b)

tensor([-inf, -inf, 3., 4.])
d:/pycharmdaima/star-transformer/ceshi.py:8: UserWarning: Implicit dimension choice for softmax has been deprecated. Change
the call to include dim=X as an argument.
  b = F.softmax(a)
tensor([0.0000, 0.0000, 0.2689, 0.7311])

容易报错: Expected object of scalar type Byte but got scalar type Long for argument #2 'mask'

 

原因,mask = torch.LongTensor()

解决方法:mask = torch.ByteTensor()

 

mask值为1的位置处用value填充。mask的元素个数需和本tensor相同,但尺寸可以不同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值