Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x PyTorch中的左移张量_Python 3.x_Torch - Fatal编程技术网

Python 3.x PyTorch中的左移张量

Python 3.x PyTorch中的左移张量,python-3.x,torch,Python 3.x,Torch,我有一个形状为(1,N,1)的张量a。我需要将张量沿维度1左移,并添加一个新值作为替换。我已经找到了一种方法来实现这一点,下面是代码 a = torch.from_numpy(np.array([1, 2, 3])) a = a.unsqueeze(0).unsqeeze(2) # (1, 3, 1), my data resembles this shape, therefore the two unsqueeze # want to left shift a along dim 1 and

我有一个形状为(1,N,1)的张量
a
。我需要将张量沿维度
1
左移,并添加一个新值作为替换。我已经找到了一种方法来实现这一点,下面是代码

a = torch.from_numpy(np.array([1, 2, 3]))
a = a.unsqueeze(0).unsqeeze(2)  # (1, 3, 1), my data resembles this shape, therefore the two unsqueeze
# want to left shift a along dim 1 and insert a new value at the end
# I achieve the required shifts using the following code
b = a.squeeze
c = b.roll(shifts=-1)
c[-1] = 4
c = c.unsqueeze(0).unsqueeze(2)
# c = [[[2], [3], [4]]]

我的问题是,有没有更简单的方法?谢谢。

您实际上不需要先压缩并执行操作,然后再松开输入张量
a
。相反,您可以直接执行以下两个操作:

# No need to squeeze
c = torch.roll(a, shifts=-1, dims=1)
c[:,-1,:] = 4
# No need to unsqeeze
# c = [[[2], [3], [4]]]

没有结合这些操作的torch方法,对吗?据我所知,没有。