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

相关推荐
喜欢打篮球的普通人2 分钟前
AI 编译器内存分配算法:从静态/动态划分到内存复用
人工智能·算法
又蓝6 分钟前
【元宝搜索开发者征文大赛】用 FastAPI + Vue3 做了个 AI 炒股工具,接了六个分析师和腾讯元宝搜索
人工智能·python·ai·fastapi
2601_966949658 分钟前
为什么不应该把 QuantDash API Key 直接写进公开代码仓库?从 Git 提交历史理解凭证泄露风险
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
在世修行8 分钟前
智学文枢:文科分析引擎
python·ai·pyside·文科分析
LittroInno12 分钟前
边缘AI模组选型:把视频带宽、压缩和推理吞吐分别算清
人工智能·音视频·边缘计算·视频编码·模组选型·视频带宽·tofu6
niucloud-admin17 分钟前
NIUCLOUD PHP SAAS上门家政使用文档:机构报表
前端·人工智能
AI小百科21 分钟前
Embedding 是什么?为什么它是 AI 的“翻译官“
人工智能·embedding
进击的横打24 分钟前
【人工智能】AI 落地:先理流程,再做 Agent
人工智能
虎鲸不是鱼24 分钟前
AI 自动化逆向(二十二)换行比峰值法:让 AI 自己发现图像的宽度
人工智能·自动化·大模型·逆向·ai逆向
包小黑26 分钟前
Python 转 EXE (实用工具)
开发语言·python