简体   繁体   English

从 torch.Tensor 中删除一个元素

[英]Delete an element from torch.Tensor

I'm trying to delete an item from a tensor.我正在尝试从张量中删除一个项目。

In the example below, How can I remove the third item from the tensor?在下面的示例中,如何从张量中删除第三项?

tensor([[-5.1949, -6.2621, -6.2051, -5.8983, -6.3586, -6.2434, -5.8923, -6.1901,
         -6.5713, -6.2396, -6.1227, -6.4196, -3.4311, -6.8903, -6.1248, -6.3813,
         -6.0152, -6.7449, -6.0523, -6.4341, -6.8579, -6.1961, -6.5564, -6.6520,
         -5.9976, -6.3637, -5.7560, -6.7946, -5.4101, -6.1310, -3.3249, -6.4584,
         -6.2202, -6.3663, -6.9293, -6.9262]], grad_fn=<SqueezeBackward1>)

You can first filter array through indices and then concat both您可以先通过索引过滤数组,然后将两者连接起来

t.shape
torch.Size([1, 36])

t = torch.cat((t[:,:3], t[:,4:]), axis = 1)

t.shape
torch.Size([1, 35])

You can use numpy`s r_ indexing trick您可以使用 numpy 的r_索引技巧

y = x[:, np.r_[:3, 4:36]]

I think that doing this with indexing is more readable.我认为使用索引执行此操作更具可读性。

t[t!=t[0,3]]

The result is the same as with the cat solution from above.结果与上面的cat解决方案相同。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM