PyTorch 维度变换-Tensor基本操作

以如下 tensor a 为例,展示常用的维度变换操作

python3 复制代码
>>> a = torch.rand(4,3,28,28)
>>> a.shape
torch.Size([4, 3, 28, 28])
  • view / reshape 两者功能完全相同: a.view(shape)

    python3 复制代码
    >>> a.view(4,3,28*28)  		## a.view(4,3,28,28) 可恢复
  • squeeze / unsqueeze: a.unsqueeze(dim), a.squeeze(dim) 只能挤压 1 维度 的

    python3 复制代码
    >>> a.unsqueeze(0).shape	## a.squeeze(0) 可恢复
    torch.Size([1, 4, 3, 28, 28])
  • transpose / permute:.t() 只能用于二维矩阵

    python3 复制代码
    >>> a.transpose(0,1).shape    ## 两两交换:交换 0 1 维度
    torch.Size([3, 4, 28, 28])
    >>> a.permute(0,1,2,3).shape  ## 新置维度,非两两交换,更方便 
    torch.Size([4, 3, 28, 28])
  • expand / repeat 两者效果完全相同 expand 高效更推荐

    python3 复制代码
    >>> a.unsqueeze(0).expand(2,4,3,28,28).shape  # 只能拓展 1 维度的
    torch.Size([2, 4, 3, 28, 28])
    >>> a.unsqueeze(0).repeat(2,1,1,1,1).shape    # 不是填目标维度,而是填每个维度的重复次数   
    torch.Size([2, 4, 3, 28, 28])
  • broadcasting 自动扩张:基于已有的小维度的值 自动 进行广播拓展

    python3 复制代码
    >>> b = a+torch.tensor(1) 
    >>> b.shape
    torch.Size([4, 3, 28, 28])

相关推荐
198******126345 小时前
2026深度解读:Work Agent长程任务的技术机制与落地能力
人工智能
老金带你玩AI5 小时前
别只让AI解释,让它做个你能看懂的东西
人工智能
iffy15 小时前
Deepseek hardness 桌面版 + ollama
人工智能
Xiaofeng36935 小时前
知漫剧入门科普:一站式工作台一句话生成漫剧
人工智能
“AI国潮设计-小江”6 小时前
《Python+SDXL实战:用ControlNet精准控制“英歌舞翻糖吐司”构图,附批量生成脚本》
开发语言·人工智能·python·prompt·aigc
wenwen_chao6 小时前
Python学习与开发资源合集:实用技巧与工具推荐
python
MobotStone6 小时前
万物皆插件:DeepSeek Harness 底层揭秘,脚手架如何蜕变为产品
人工智能
youdexiang6 小时前
Android录音软件时间关键词检索功能分析
java·人工智能
WUYOUGYLU7 小时前
大模型时代:人与智能的共同进化
人工智能
netkiller-BG7NYT7 小时前
基于图像识别的人工智能中医望诊方案
人工智能·百度