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])

相关推荐
货拉拉技术1 小时前
货拉拉海豚平台-大模型推理加速工程化实践
人工智能·后端·架构
掘金安东尼1 小时前
国内大模型真实格局:用户规模 vs API调用量(v2026.3.6)
人工智能
前端一课1 小时前
OpenClaw 项目全面架构分析报告
前端·人工智能
小姐姐味道1 小时前
1万美金的账单,烧麻了!bull这个skills让数据推理质量更好,更省!
人工智能
苍何1 小时前
再见 Openclaw,桌面端 Agent 起飞了!
人工智能
雮尘2 小时前
让 AI Agent 高效并行开发的命令-git worktree
人工智能·git·agent
Ray Liang3 小时前
AI基于Spec开发是巨坑?
人工智能·架构设计·mindx
哔哩哔哩技术3 小时前
游戏数据分析Agent的全栈架构演进
人工智能·agent
陆通4 小时前
10分钟Windows系统安装迷你版的OpenClaw ,小小龙虾Nanobot
人工智能
老张的码4 小时前
飞书 × OpenClaw 接入指南
人工智能·后端