简体   繁体   English

Pytorch:如何在二维张量的每一行中找到第一个非零元素的索引?

[英]Pytorch: How can I find indices of first nonzero element in each row of a 2D tensor?

I have a 2D tensor with some nonzero element in each row like this:我有一个二维张量,每行都有一些非零元素,如下所示:

import torch
tmp = torch.tensor([[0, 0, 1, 0, 1, 0, 0],
                    [0, 0, 0, 1, 1, 0, 0]], dtype=torch.float)

I want a tensor containing the index of first nonzero element in each row:我想要一个包含每行中第一个非零元素索引的张量:

indices = tensor([2],
                 [3])

How can I calculate it in Pytorch?我如何在 Pytorch 中计算它?

I have simplified Iman's approach to do the following:我简化了 Iman 的方法来执行以下操作:

idx = torch.arange(tmp.shape[1], 0, -1)
tmp2= tmp * idx
indices = torch.argmax(tmp2, 1, keepdim=True)

I could find a tricky answer for my question:我可以为我的问题找到一个棘手的答案:

  tmp = torch.tensor([[0, 0, 1, 0, 1, 0, 0],
                     [0, 0, 0, 1, 1, 0, 0]], dtype=torch.float)
  idx = reversed(torch.Tensor(range(1,8)))
  print(idx)

  tmp2= torch.einsum("ab,b->ab", (tmp, idx))

  print(tmp2)

  indices = torch.argmax(tmp2, 1, keepdim=True)
  print(indeces)

The result is:结果是:

tensor([7., 6., 5., 4., 3., 2., 1.])
tensor([[0., 0., 5., 0., 3., 0., 0.],
       [0., 0., 0., 4., 3., 0., 0.]])
tensor([[2],
        [3]])

All the nonzero values are equal, so argmax returns the first index.所有非零值都相等,因此argmax返回第一个索引。

tmp = torch.tensor([[0, 0, 1, 0, 1, 0, 0],
                    [0, 0, 0, 1, 1, 0, 0]])
indices = tmp.argmax(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 PyTorch:索引具有2D张量行索引的2D张量 - PyTorch: index 2D tensor with 2D tensor of row indices 如何从 2D pytorch 张量获取最大元素的行和列索引? - how to get the row and column indices of the maximum element from a 2D pytorch tensor? 查找二维数组中具有非零元素的列的索引 - Find Indices Of Columns Having Some Nonzero Element In A 2d array 如何从该行的所有元素中减去2D张量每一行的max元素 - How do I subtract the max element of each row of a 2D tensor from all elements of that row 如何根据索引列表从二维列表中的每个一维列表中选择一个元素? - How can I pick an element from each 1D list inside a 2D list according to a list of indices? 在 TensorFlow 中,如何从 python 的张量中获取非零值及其索引? - In TensorFlow, how can I get nonzero values and their indices from a tensor with python? 如何在pytorch中将3D张量转换为2D张量? - How to convert 3D tensor to 2D tensor in pytorch? 如何将函数应用于二维张量的每个元素? - How to apply function to each element of a 2d tensor? 2d numpy,有效地为非行索引[row,col]分配[row,row]和[col,col]的最小值 - 2d numpy, efficiently assign nonzero indices [row,col] the minimum of [row,row] and [col,col] 遮罩PyTorch中3D张量中的前k个元素(每行不同k) - mask first k elements in a 3D tensor in PyTorch (different k for each row)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM