Pytorch中的repeat以及repeat_interleave用法

repeat和repeat_interleave都是pytorch中用来复制的两种方法,但是二者略有不同,如下所示。

1.repeat

torch.tensor().repeat()里面假设里面有3个参数,即3,2,1,如下所示:

import torch 
x = torch.tensor([1,2,3]) 
xx = x.repeat(3,2,1)#将一维度的x向量扩展到三维

用repeat时,应当从后往前看,即先复制最后一维,依次向前。
①最后一个数字为1,复制一次,还是[1,2,3].
②倒数第二个数字为2,复制两次,得到[[1,2,3],[1,2,3]].
③倒数第三个数字为3,复制三次,得到[[[1,2,3],[1,2,3]],[[1,2,3],[1,2,3]],[[1,2,3],[1,2,3]]].
具体演示代码如下所示:

import torch
x = torch.tensor([1, 2, 3])
x1 = x.repeat(3)
print("x1:\n", x1)
x2 = x.repeat(3, 1)
print("x2:\n",x2)
x3 = x.repeat(3, 2)
print("x3:\n",x3)
x4 = x.repeat(3, 2, 1)
print("x4:\n",x4)

结果如下所示:

x1:
 tensor([1, 2, 3, 1, 2, 3, 1, 2, 3])
x2:
 tensor([[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]])
x3:
 tensor([[1, 2, 3, 1, 2, 3],
        [1, 2, 3, 1, 2, 3],
        [1, 2, 3, 1, 2, 3]])
x4:
 tensor([[[1, 2, 3],
         [1, 2, 3]],

        [[1, 2, 3],
         [1, 2, 3]],

        [[1, 2, 3],
         [1, 2, 3]]])

Process finished with exit code 0

2.repeat_interleave

repeat_interleave是将张量中的元素沿某一维度复制n次,即复制后的张量沿该维度相邻的n个元素是相同的。
repeat_interleave()中有两个参数,第一个参数N是代表复制多少次,第二个参数代表维度。
具体演示代码如下所示:

import torch

x = torch.tensor([[1, 2, 3],[4,5,6]])

x1 = x.repeat_interleave(3,0)
print("x1:\n", x1)

x2 = x.repeat_interleave(3,1)
print("x2:\n",x2)

结果如下所示:

x1:
 tensor([[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3],
        [4, 5, 6],
        [4, 5, 6],
        [4, 5, 6]])
x2:
 tensor([[1, 1, 1, 2, 2, 2, 3, 3, 3],
        [4, 4, 4, 5, 5, 5, 6, 6, 6]])

Process finished with exit code 0

努力加油a啊

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年3月28日
下一篇 2023年3月28日

相关推荐