【pytorch】reshape的使用

torch.reshape 是 PyTorch 中用于改变张量形状的函数。它的作用是重新安排张量的维度,使其符合指定的形状,但不会改变数据的顺序。

Returns a tensor with the same data and number of elements as input, but with the specified shape.

基本语法

python 复制代码
input_reshape = torch.reshape(input, shape)

或者:

python 复制代码
input_reshape = input.reshape(shape)
  • input(tensor):输入张量。
  • shape(tuple of int):目标形状,可以是一个整数或一个整数元组,表示张量的新维度。

例子

python 复制代码
import torch

# 创建一个形状为 (4, 3) 的张量
x = torch.arange(12).reshape(4, 3)
print(x)

输出:

复制代码
tensor([[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11]])

你可以将这个张量重新调整成其他形状,比如将它变成一个 (2, 6) 的张量:

python 复制代码
y = x.reshape(2, 6)
print(y)

输出:

复制代码
tensor([[ 0,  1,  2,  3,  4,  5],
        [ 6,  7,  8,  9, 10, 11]])

特别的用法

使用 1 自动推算维度

如果你不确定某个维度应该是多少,可以使用 -1 来自动推算。例如,如果你只知道张量的总元素数和某些维度,可以让 PyTorch 自动计算某个维度。

A single dimension may be -1, in which case it's inferred from the remaining dimensions and the number of elements in input.

python 复制代码
z = x.reshape(2, -1)  # PyTorch 会自动推算第二维度的大小
print(z)

输出:

复制代码
tensor([[ 0,  1,  2,  3,  4,  5],
        [ 6,  7,  8,  9, 10, 11]])

torch.reshape(x, (-1,)) 将张量 展平成一维 (即向量)等效于 x.flatten()

  • 此时 PyTorch 会自动计算该维度的大小,计算公式为:

    新维度大小 = 原始张量的总元素数

  • 因为要展成向量,所以只有一个维度(表示有多少个数),所以只需要一个-1,后面空着就行

    • 所以其实也可以写成 (-1),即torch.reshape(x, (-1))推荐保留逗号

注意:这跟 (1,-1)有区别 ,(-1,)是展平成一维向量,

而(1,-1)是1*n,这被视作二维的(一个维度是1个数,另一个维度是n个数)

例子:

python 复制代码
x = torch.tensor([[0, 1],
                  [2, 3]])

x_vec = x.reshape(-1,)
print(x_vec)

x_matrix = x.reshape(1,-1)
print(x_matrix)

输出:

python 复制代码
tensor([0, 1, 2, 3])
tensor([[0, 1, 2, 3]])
  • 总元素数2 × 2 = 4

  • 执行 torch.reshape(x, (-1,)) 后:

    → 新形状为 (4,)

    → 结果:tensor([0, 1, 2, 3])

  • 执行 torch.reshape(x, (1,-1)) 后:

    → 新形状为 (1,4)

    → 结果:tensor([[0, 1, 2, 3]])

注意事项

保持元素数量一致

使用 reshape 时,新形状的元素数量必须和原形状一致。例如,原来是 (4, 3),总共有 12 个元素,不能reshape成 (3, 5) 因为会丢失元素。

python 复制代码
# 错误的 reshape
# x.reshape(3, 5)  # 会抛出错误,无法reshape

总之,要接收返回的tensor

  • reshape 不会修改原始张量,它会返回一个新的张量,除非原张量已经在内存中是以连续的方式存储。

When possible, the returned tensor will be a view of input. Otherwise, it will be a copy. Contiguous inputs and inputs with compatible strides can be reshaped without copying, but you should not depend on the copying vs. viewing behavior.

  • 如果原张量的内存布局不连续,reshape 会返回一个新的内存副本。
  • torch.viewtorch.reshape 在功能上相似,但 torch.view 要求张量是连续的,而 torch.reshape 会自动处理不连续的张量。
相关推荐
MageGojo5 小时前
10 种主题随机诗词:一个 API 解决小程序的诗词内容源
python·小程序·古诗词·api 接入
cooldream20096 小时前
使用 uv 管理 Python 虚拟环境:现代 Python 开发的高效实践
python·uv·mcp
zhangfeng11336 小时前
国家超算中心 系统自带模型 和pytorch 和cuda版本
人工智能·pytorch·python
m0_738120726 小时前
渗透测试基础——黑盒测试下的Web漏洞挖掘与利用解析(二)
服务器·前端·python·网络协议·安全·网络安全
玫幽倩6 小时前
2025FIC取证决赛wp(手机取证)
python·智能手机·手机·电子取证·计算机取证·手机取证·fic
多彩电脑6 小时前
Kivy如何自定义事件
开发语言·python
java_cj6 小时前
LangChain初入门 - 简化LLM开发难度的利器
开发语言·python·langchain
sleven fung6 小时前
llama-cpp-python 本地部署入门
开发语言·python·算法·llama
li星野6 小时前
RAG优化系列:基于用户反馈的检索权重调整(Feedback Loop)——让系统越用越聪明
python·学习
特立独行的猫a6 小时前
鸿蒙 PC 平台 Python 第三方库移植全景指南
python·华为·harmonyos·三方库移植·鸿蒙pc