在pytorch中将索引选定张量添加到另一个具有重叠索引的张量 [英] Add a index selected tensor to another tensor with overlapping indices in pytorch

查看:29
本文介绍了在pytorch中将索引选定张量添加到另一个具有重叠索引的张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是这个问题的后续问题.我想在 pytorch 中做同样的事情.是否有可能做到这一点?如果是,如何?

导入火炬image = torch.tensor([[246, 50, 101], [116, 1, 113], [187, 110, 64]])iy = torch.tensor([[1, 0, 2], [1, 0, 2], [2, 2, 2]])ix = torch.tensor([[0, 2, 1], [1, 2, 0], [0, 1, 2]])warped_image = torch.zeros(size=image.shape)

我需要像 torch.add.at(warped_image, (iy, ix), image) 之类的东西,它给出的输出为

[[ 0. 0. 51.][246.116. 0.][300.211. 64.]]

注意 (0,1)(1,1) 处的索引指向相同的位置 (0,2).所以,我想要 warped_image[0,2] = image[0,1] + image[1,1] = 51.

解决方案

您正在寻找的是 torch.Tensor.index_put_accumulate 参数设置为 True:

<预><代码>>>>warped_image = torch.zeros_like(图像)>>>warped_image.index_put_((iy, ix), image,accumulate=True)张量([[ 0, 0, 51],[246, 116, 0],[300, 211, 64]])

或者,使用外置版本torch.index_put:

<预><代码>>>>torch.index_put(torch.zeros_like(图像),(iy,ix),图像,累积=真)张量([[ 0, 0, 51],[246, 116, 0],[300, 211, 64]])

This is a follow up question to this question. I want to do the exactly same thing in pytorch. Is it possible to do this? If yes, how?

import torch
image = torch.tensor([[246,  50, 101], [116,   1, 113], [187, 110,  64]])
iy = torch.tensor([[1, 0, 2], [1, 0, 2], [2, 2, 2]])
ix = torch.tensor([[0, 2, 1], [1, 2, 0], [0, 1, 2]])
warped_image = torch.zeros(size=image.shape)

I need something like torch.add.at(warped_image, (iy, ix), image) that gives the output as

[[  0.   0.  51.]
 [246. 116.   0.]
 [300. 211.  64.]]

Note that the indices at (0,1) and (1,1) point to the same location (0,2). So, I want warped_image[0,2] = image[0,1] + image[1,1] = 51.

解决方案

What you are looking for is torch.Tensor.index_put_ with the accumulate argument set to True:

>>> warped_image = torch.zeros_like(image)

>>> warped_image.index_put_((iy, ix), image, accumulate=True)
tensor([[  0,   0,  51],
        [246, 116,   0],
        [300, 211,  64]])

Or, using the out-place version torch.index_put:

>>> torch.index_put(torch.zeros_like(image), (iy, ix), image, accumulate=True)
tensor([[  0,   0,  51],
        [246, 116,   0],
        [300, 211,  64]])

这篇关于在pytorch中将索引选定张量添加到另一个具有重叠索引的张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆