Pytorch学习笔记【4】---tensor维度变换

Pytorch【4】—tensor维度变换

Pytorch笔记目录:点位进入

1. view()

torch.view()的作用是改变tensor的维度,且改变前后的所有维度的相乘的结果相同

a = torch.rand(4,1,28,28)
print(a.shape)
out:
torch.Size([4, 1, 28, 28])
a.view(4,28*28).shape
out:
torch.Size([4, 784])

你可以改变他的维度,前提是不改变数值的总数量

# a.view()的方法并不会概念原有的tensor,但是你可以用一个变量去接收他
b = a.view(4,28,28)

unsqueeze()

unsqueeze()的作用是在某个维度上添加一个维度

a.unsqueeze(0).shape
out:
torch.Size([1, 4, 1, 28, 28])
a.unsqueeze(-1).shape
out:
torch.Size([4, 1, 28, 28, 1])
b = a.view(4,28,28) 
b = b.unsqueeze(0).unsqueeze(1).unsqueeze(0)
print(b.shape)
out:
 torch.Size([1, 1, 1, 4, 28, 28])

squeeze()

squeeze()的作用是在删除维度数量为1的维度,如果不填的话就是删除所有的

b.squeeze().shape
out:
torch.Size([4, 28, 28])
b.squeeze(0).shape
out:
torch.Size([1, 1, 4, 28, 28])

expand()

expand()是在某一个维度上扩展,也就是横向扩展

a = torch.rand(3,1)
a.expand(3,4)
out:
tensor([[0.0246, 0.0246, 0.0246, 0.0246],
            [0.1753, 0.1753, 0.1753, 0.1753],
            [0.6476, 0.6476, 0.6476, 0.6476]])

.t()

.t()就是线代里面矩阵的转置

a.t()
out:
tensor([[0.6535, 0.3542, 0.8209]])

repeat()

repeat()的作用就是把每个维度按照自己设定的数值来复制

在这里插入图片描述

transpose()和permute()

transpose()的作用就是把某两个维度的给调换
permute()是给每个维度都制定需要调换到的维度
在这里插入图片描述

原创文章 113 获赞 80 访问量 3万+

猜你喜欢

转载自blog.csdn.net/python_LC_nohtyp/article/details/106033081