torch.where 与 np.where

本文探讨了numpy和torch中where函数的使用,当不指定条件时,两者都返回非零元素的下标,包括负数。在指定条件如`c>0`后,torch.where会过滤掉不符合条件的下标,只保留正数元素的位置。这展示了这两个库在处理数组条件筛选上的相似性和差异性。

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

numpy.where 和 torch.where 如果不指定条件,返回的都是非0元素的位置(下标),

np.where

>>> a = np.array([-1, -2, 0, 1, 2])
>>> np.where(a)
(array([0, 1, 3, 4]),)

torch.where不指定条件,返回的也是非0元素的位置(下标),包括了负数。
看个例子

>>> c
tensor([[[ 0.,  0.],
         [-1., -1.],
         [-1., -2.]],

        [[ 1.,  1.],
         [ 0.,  0.],
         [ 0., -1.]],

        [[ 1.,  2.],
         [ 0.,  1.],
         [ 0.,  0.]]])
>>> torch.where(c)
(tensor([0, 0, 0, 0, 1, 1, 1, 2, 2, 2]),
 tensor([1, 1, 2, 2, 0, 0, 2, 0, 0, 1]),
 tensor([0, 1, 0, 1, 0, 1, 1, 0, 1, 1]))

竖着按列看,可看到非零元素的下标为(0, 1, 0), (0, 1, 1)等,包含了负数。
*注:(0, 1, 0)指的是第一块,第2行的第一个元素-1。

现在指定条件 > 0

>>> torch.where(c > 0)
(tensor([1, 1, 2, 2, 2]), 
 tensor([0, 0, 0, 0, 1]), 
 tensor([0, 1, 0, 1, 1]))

可以看到负数的下标不见了。

指定条件下它们也一样,见链接

根据你提供的代码,报错信息显示 index 的形状是 [112, 1],而 x 的形状是 [16, 7],因此 index x 的形状不匹配,导致了这个错误。 为了解决这个问题,你可以尝试将 LDAMLoss 类的 forward 函数中的 index 的形状改为 [x.size(0), x.size(1)],这样就能够 x 的形状匹配。同时,由于 target.data 已经被弃用,建议改为 target。修改后的代码如下: ``` class LDAMLoss(nn.Module): def __init__(self, cls_num_list, max_m=0.5, weight=None, s=30): super(LDAMLoss, self).__init__() m_list = 1.0 / np.sqrt(np.sqrt(cls_num_list)) m_list = m_list * (max_m / np.max(m_list)) m_list = torch.cuda.FloatTensor(m_list) self.m_list = m_list assert s > 0 self.s = s self.weight = weight def forward(self, x, target): index = torch.zeros_like(x, dtype=torch.uint8) index.scatter_(1, target.view(-1, 1).type(torch.int64), 1) index_float = index.type(torch.cuda.FloatTensor) batch_m = torch.matmul(self.m_list[None, :], index_float.transpose(0,1)) batch_m = batch_m.view((-1, 1)) x_m = x - batch_m output = torch.where(index, x_m, x) return F.cross_entropy(self.s*output, target, weight=self.weight) ``` 另外,你的 init 方法也存在一些错误。super 函数应该在 init 方法的第一行调用,而不是在函数体内。因此,init 方法应该改为: ``` def __init__(self, cls_num_list, max_m=0.5, weight=None, s=30): super(LDAMLoss, self).__init__() m_list = 1.0 / np.sqrt(np.sqrt(cls_num_list)) m_list = m_list * (max_m / np.max(m_list)) m_list = torch.cuda.FloatTensor(m_list) self.m_list = m_list assert s > 0 self.s = s self.weight = weight ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值