gpt4 book ai didi

python-3.x - PyTorch 中的左移张量

转载 作者:行者123 更新时间:2023-12-04 03:50:25 26 4
gpt4 key购买 nike

我有一个张量 a形状(1, N, 1) .我需要沿维度左移张量 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]]]

关于python-3.x - PyTorch 中的左移张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64495404/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com