栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Pytorch中的repeat以及repeat

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Pytorch中的repeat以及repeat

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啊

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1012911.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号