torch.repeat函数介绍

repeat

在 PyTorch 中,repeat() 函数用于复制张量的维度。它会将输入张量按照指定的次数重复,以生成一个新的张量。

这是 repeat() 函数的基本语法:

python 复制代码
repeat(*sizes)
  • sizes: 重复每个维度的次数。如果你只想在某些维度上重复,可以在对应位置填入 1。

下面是一个简单的例子,说明了 repeat() 函数的用法:

python 复制代码
import torch

# 创建一个张量
x = torch.tensor([[1, 2],
                  [3, 4]])

# 在每个维度上分别重复 2 次
y = x.repeat(2, 2)

print(y)

输出结果是:

复制代码
tensor([[1, 2, 1, 2],
        [3, 4, 3, 4],
        [1, 2, 1, 2],
        [3, 4, 3, 4]])

在这个例子中,原始张量 x 是一个 2x2 的矩阵。通过 x.repeat(2, 2),我们在每个维度上分别重复了 2 次,得到了一个新的 4x4 的张量 y。

python 复制代码
a = torch.tensor(
    [[1,2,3],
    [4,5,6]]
)

print(a)


x = a.repeat(1,1)

print(x)

x = a.repeat(1,2)

print(x)

x = a.repeat(2,1)

print(x)
复制代码
tensor([[1, 2, 3],
        [4, 5, 6]])
tensor([[1, 2, 3],
        [4, 5, 6]])
tensor([[1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6]])
tensor([[1, 2, 3],
        [4, 5, 6],
        [1, 2, 3],
        [4, 5, 6]])
相关推荐
外收内放5 小时前
面向对象高级(实战案例)
开发语言·python·学习
专业程序开发源5 小时前
springboot欧缇蔓月子中心管理系统82697-计算机课程设计、毕业设计
java·spring boot·后端·python·spring·django·课程设计
FPGA小迷弟6 小时前
用 Claude Code 重构遗留系统:从评估到落地的完整实践指南
c++·python·ai·plotly·django·ai编程·claude
卷无止境6 小时前
面向arm64桌面客户端开发全景:语言、框架与生态
后端·python
fanruitian6 小时前
python else用法
开发语言·python
Thinker QAQ6 小时前
并发编程(十一):Shared Memory 与 Message Passing——关系与组合使用
java·python·go·并发编程·shared memory·message passing
用户8356290780516 小时前
如何使用 Python 对 Excel 数据进行分组和分级显示
后端·python
vx_Biye_Design7 小时前
django房屋租赁推荐系统78455-计算机课程设计、毕业设计
vue.js·spring boot·后端·python·django·课程设计·express
学Linux的语莫8 小时前
python中类的常见写法
开发语言·python·状态模式
垆边人似月.9 小时前
Python中如何使用get函数实现频次查询
服务器·前端·python