如何在一维 Torch 张量之间添加元素?

问题描述 投票:0回答:2

我有一个维度为 ([384]) 的一维火炬张量。我想在这个张量的每个奇数索引后面放置零或其他数字,并最终将其维度加倍到 ([768])。 更具体地说,将

[0, 1, 2,..., 382, 383]
视为我的 Torch 张量的索引。假设 * 是零/数字的索引,我想插入并制作一个像
[0, 1, *, 2, 3, *,...]
这样的张量。

我唯一的解决方案是将这些元素插入 for 循环中,但这会很耗时。由于我必须对数百个张量进行这些更改,我想知道 PyTorch 或 NumPy 是否有更快的函数来执行此操作!

python numpy pytorch tensor
2个回答
0
投票

是的,您可以使用类似于这篇文章的串联技巧。让我们让

A
成为长度为
a
的张量(在您的情况下
a =384). Let's say you want to add a new element every 
n
elements (in your case
n = 2
). First, we reshape the list into a 2D array with 
n` 列: A = torch.rand(384) # 例如

a = A.shape[0]                 # 384
n = 2
insert_value = 10              # for example
A.shape                        #  shape is [384]


A = A.reshape(n-1,-1)          # shape is [192,2]
new = np.zeros([A.shape[0],1]) # shape is [192,1]
new += insert_value            # shape is [192,1]
B = torch.cat((A,new),dim = 1) # shape is [192,3]

这是逻辑上唯一不平凡的一点。如果我们将

B
视为或重塑为一维张量/列表,pytorch 首先沿第 0 维移动,然后沿第 1 维移动,依此类推。这意味着对于 3D 数组,我们最终会得到一个行列列表,而对于 2D 数组(正如我们所拥有的),我们最终会得到一个行列表。这给了我们所需的顺序。

result = B.reshape(-1) # shape is [576]

print(result)

>>> [rand,rand,10,rand,rand,10,rand,rand,10,...] 

如果您想在

A
的现有元素之间添加多个元素,可以将
new
的形状更改为
[a,num_elem]
,其中
num_elem
是您要插入的元素数量。


0
投票

我不知道有什么直接的方法可以做到你所要求的。我认为以下代码(使用 torch.tensor 索引)比您正在寻找的代码更复杂,但为了以防万一它对您有帮助,我还是将其留在这里。

import torch
import numpy as np

# Original tensor
your_1D_tensor_length = 6
original_tensor = torch.tensor(range(your_1D_tensor_length))

new_tensor = torch.zeros(size=(int(np.floor(original_tensor.shape[0]*(3/2))),))
new_tensor[0::3] = original_tensor[0::2]
new_tensor[1::3] = original_tensor[1::2]

print(original_tensor)
print(new_tensor)

输出:

tensor([0, 1, 2, 3, 4, 5])
tensor([0., 1., 0., 2., 3., 0., 4., 5., 0.])
© www.soinside.com 2019 - 2024. All rights reserved.