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 Requests库教程
自动化测试·python·requests库
copyer_xyf5 小时前
LangChain 调用 LLM
后端·python·agent
copyer_xyf5 小时前
Prompt 组织管理
后端·python·agent
pythonpioneer6 小时前
PyTorch3D:基于 PyTorch 的高效 3D 深度学习工具库
pytorch·深度学习·其他·3d
shimly1234566 小时前
python3 uvicorn 是啥?
python
CTA量化套保7 小时前
期货量化程序 time.sleep 卡死:天勤单线程与 deadline 替代
python·区块链
GIS数据转换器7 小时前
城市排水生命线安全运行监测平台深度解析
java·运维·人工智能·python·安全·数据挖掘·无人机
贤哥哥yyds7 小时前
GBK转UTF\-8编码自动转换工具 使用文档
python
数量技术宅8 小时前
2026量化前沿:从Reddit热帖到Python实战,如何用赫斯特指数(Hurst)狙击虚假突破?
开发语言·python
华如锦8 小时前
面了很多 Java转AI Agent方向,一些面试题总结
java·开发语言·人工智能·python·ai