0
点赞
收藏
分享

微信扫一扫

极智AI | pytorch改变tensor维度的方法


大家好,我是极智视界,本文介绍一下 pytorch改变tensor维度的方法

在 pytorch 中,tensor 是基本的操作数据结构。在很多的时候,咱们需要改变 tensor 的维度来适应咱们的计算,包括升维、降维、变维。在 pytorch 中有很多方法可以用来改变 tensor 的维度。

极智AI | pytorch改变tensor维度的方法_pytorch

这里我把几种常用的方法进行了一下汇总:

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

另外还有一些其他的方法可以改变tensor的维度,例如 permute() 和 contiguous()。

好了,以上分享了 pytorch中改变tensor维度的方法,希望我的分享能对你的学习有一点帮助。

 


极智AI | pytorch改变tensor维度的方法_tensor_02

举报

相关推荐

0 条评论