pytorch masked_fill

本文详细解析了PyTorch中masked_fill函数的使用方法及常见错误处理,包括如何正确创建mask并应用于张量,同时展示了如何利用该函数进行特定元素的替换操作。
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:\pycharm\PyCharm 2019.1.1\helpers\pydev\pydevconsole.py:8: UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument.
  start_new_thread = thread.start_new_thread
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必须是一个 ByteTensor 而且shape必须和 a一样 并且元素只能是 0或1 。

函数作用:将 mask中为1的元素所在的索引,在a中相同的索引处替换为 value  ,mask value必须同为tensor 

原文链接:https://blog.youkuaiyun.com/qq_40210472/article/details/88826821

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值