【问题标题】:Left shift tensor in PyTorchPyTorch 中的左移张量
【发布时间】:2021-02-06 05:56:08
【问题描述】:

我有一个形状为(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]]]

我的问题是,有没有更简单的方法可以做到这一点?谢谢。

【问题讨论】:

    标签: python-3.x torch


    【解决方案1】:

    您实际上不需要先压缩并执行操作,然后再取消压缩输入张量 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方法吧?
    • 据我所知,没有。
    猜你喜欢
    • 2021-10-11
    • 2021-02-07
    • 2019-07-12
    • 2022-10-17
    • 2019-07-09
    • 2019-09-30
    • 2019-07-10
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多