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]])
相关推荐
Yongqiang Cheng13 小时前
PyTorch Grid Sample
pytorch·grid sample
claem13 小时前
Mac端 Python脚本创建与理解
开发语言·python·macos
lixzest13 小时前
目标检测算法应用工程师 面试高频题 + 标准答案
python·yolo·目标检测·计算机视觉
癫狂的兔子13 小时前
【BUG】【Python】【Spider】Compound class names are not allowed.
开发语言·python·bug
木头左14 小时前
基于Backtrader框架的指数期权备兑策略实现与验证
python
李松桃14 小时前
python第三次作业
java·前端·python
m0_5613596714 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
马士兵教育14 小时前
计算机专业学生入行IT行业,编程语言如何选择?
java·开发语言·c++·人工智能·python
农场主John14 小时前
Accelerate_deepspeed使用
pytorch·llm·deepspeed