pytorch | pytorch改变tensor维度的方法

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

  • view(shape):返回一个新的 tensor,它具有给定的形状。如果元素总数不变,则可以用它来改变 tensor 的维度。例如:
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,它的指定位置插入了一个新的维度。例如:
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 的维度被删除。例如:
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,它的排列被交换。例如:
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。

相关推荐

  1. pytorch | pytorch改变tensor方法

    2024-03-27 09:52:03       20 阅读
  2. Pytorch Tensor 变换学习记录

    2024-03-27 09:52:03       39 阅读
  3. 张量改变总结

    2024-03-27 09:52:03       21 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-27 09:52:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-27 09:52:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-27 09:52:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-27 09:52:03       20 阅读

热门阅读

  1. 前端学习-CSS基础-Day1

    2024-03-27 09:52:03       14 阅读
  2. leetcode88-Merge Sorted Array

    2024-03-27 09:52:03       19 阅读
  3. ubuntu安装pyenv

    2024-03-27 09:52:03       19 阅读
  4. 对Flex布局的理解及其使用场景

    2024-03-27 09:52:03       21 阅读