How two rows can be swapped in a torch tensor?(如何在 Torch 张量中交换两行?)
问题描述
var = [[0, 1, -4, 8],[2, -3, 2, 1],[5, -8, 7, 1]]var = torch.Tensor(var)这里,var 是一个 3 x 4 (2d) 张量.如何交换第一行和第二行以获得以下二维张量?2, -3, 2, 10, 1, -4, 85, -8, 7, 1
解决方案 其他答案 不起作用,因为有些维度在复制之前被覆盖:
<预><代码>>>>var = [[0, 1, -4, 8],[2, -3, 2, 1],[5, -8, 7, 1]]>>>x = Torch.tensor(var)>>>index = torch.LongTensor([1, 0, 2])>>>x[索引] = x>>>X张量([[ 0, 1, -4, 8],[ 0, 1, -4, 8],[ 5, -8, 7, 1]])
对我来说,创建一个新的张量(具有单独的底层存储)来保存结果就足够了:
<预><代码>>>>x = Torch.tensor(var)>>>index = torch.LongTensor([1, 0, 2])>>>y = torch.zeros_like(x)>>>y[索引] = x或者,您可以使用 index_copy_
(遵循 discuss.pytorch.org),尽管目前我认为这两种方式都没有优势.
var = [[0, 1, -4, 8],
[2, -3, 2, 1],
[5, -8, 7, 1]]
var = torch.Tensor(var)
Here, var
is a 3 x 4 (2d) tensor. How the first and second row can be swapped to get the following 2d tensor?
2, -3, 2, 1
0, 1, -4, 8
5, -8, 7, 1
The other answer does not work, as some dimensions get overwritten before they are copied:
>>> var = [[0, 1, -4, 8],
[2, -3, 2, 1],
[5, -8, 7, 1]]
>>> x = torch.tensor(var)
>>> index = torch.LongTensor([1, 0, 2])
>>> x[index] = x
>>> x
tensor([[ 0, 1, -4, 8],
[ 0, 1, -4, 8],
[ 5, -8, 7, 1]])
For me, it suffices to create a new tensor (with separate underlying storage) to hold the result:
>>> x = torch.tensor(var)
>>> index = torch.LongTensor([1, 0, 2])
>>> y = torch.zeros_like(x)
>>> y[index] = x
Alternatively, you can use index_copy_
(following this explanation in discuss.pytorch.org), although I don't see an advantage for either way at the moment.
这篇关于如何在 Torch 张量中交换两行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Torch 张量中交换两行?


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01