pytorch | pytorch改变tensor维度的方法

pytorch 的 Tensor 类有很多方法可以用来改变 tensor 的维度。这里介绍几种常用的方法:

  • view(shape):返回一个新的 tensor,它具有给定的形状。如果元素总数不变,则可以用它来改变 tensor 的维度。例如:
bash 复制代码
import torch

t = torch.tensor([
    [1, 2, 3],
    [4, 5, 6]
])
print(t.shape)  # torch.Size([2, 3])

t_view = t.view(3, 2)
print(t_view.shape)  # torch.Size([3, 2])
  • unsqueeze(dim):返回一个新的 tensor,它的指定位置插入了一个新的维度。例如:
bash 复制代码
import torch

t = torch.tensor([
    [1, 2, 3],
    [4, 5, 6]
])
print(t.shape)  # torch.Size([2, 3])

t_unsqueeze = t.unsqueeze(0)
print(t_unsqueeze.shape)  # torch.Size([1, 2, 3])

t_unsqueeze = t.unsqueeze(1)
print(t_unsqueeze.shape)  # torch.Size([2, 1, 3])

t_unsqueeze = t.unsqueeze(2)
print(t_unsqueeze.shape)  # torch.Size([2, 3, 1])
  • squeeze(dim):返回一个新的 tensor,它的指定位置的维度的大小为 1 的维度被删除。例如:
bash 复制代码
import torch

t = torch.tensor([
    [[1], [2], [3]],
    [[4], [5], [6]]
])
print(t.shape)  # torch.Size([2, 3, 1])

t_squeeze = t.squeeze(2)
print(t_squeeze.shape)  # torch.Size([2, 3])

t_squeeze = t.squeeze()
print(t_squeeze.shape)  # torch.Size([2, 3])
  • transpose(dim0, dim1):返回一个新的 tensor,它的排列被交换。例如:
bash 复制代码
import torch

t = torch.tensor([
    [1, 2, 3],
    [4, 5, 6]
])
print(t.shape)  # torch.Size([2, 3])

t_transpose = t.transpose(0, 1)
print(t_transpose.shape)  # torch.Size([3, 2])

t_transpose = t.transpose(1, 0)
print(t_transpose.shape)  # torch.Size([3, 2])

还有一些其他的方法,例如 permute() 和 contiguous(),可以用来改变 tensor 的维度。有关这些方法的更多信息,可以参考 pytorch 官方文档:https://pytorch.org/docs/stable/tensors.html。

相关推荐
木叶子---几秒前
Spring 枚举转换器冲突问题分析与解决
java·python·spring
lizz6669 分钟前
Hermes-Agent:配置gateway网关,chat交互入口(钉钉Dingtalk)
人工智能
༒࿈南林࿈༒12 分钟前
链家二手房数据自动化点选验证码
python·自动化·点选验证码
财经汇报13 分钟前
从AI到抗量子:下一代金融基础设施正在发生什么变化?
人工智能·量子计算
IT_陈寒29 分钟前
Vite静态资源加载把我坑惨了
前端·人工智能·后端
后端小肥肠31 分钟前
我把自己蒸馏成小肥肠.skill,相关答疑全能做,一人公司终于能聚焦核心业务
人工智能·agent
天一生水water1 小时前
Time-Series-Library 仓库的使用
人工智能
HeteroCat1 小时前
DeepSeek V4 来了:我熬了一中午,把技术报告啃完了
人工智能
阿杰学AI1 小时前
AI核心知识135—大语言模型之 OpenClaw(简洁且通俗易懂版)
人工智能·ai·语言模型·自然语言处理·aigc·ai编程·openclaw
薛定e的猫咪1 小时前
多智能体强化学习求解 FJSP 变体全景:动态调度、AGV 运输、绿色制造与开源代码导航
人工智能·学习·性能优化·制造