维度变换是pytorch中的重要操作,尤其是在图片处理中。本文对pytorch中的维度变换进行讲解。
维度变换有四种操作:
(1)view/reshape (类似于numpy中的reshape操作,可在不改变数据情况下,将tensor转换shape)
(2)Squeeze/unsqueeze (前一个为删减维度,第二个为增加维度)
(3)Transpose/t/permute (矩阵的单次、多次交换操作)
(4)Expand/repeat (维度的扩展)
下面分别介绍view和reshape操作
View和reshape两者可实现相同的操作,他们之所以不同是因为他们分别出现在pytorch 0.3和 0.4版本中。
下面以具体代码介绍其功能
import torch
a = torch.rand(4, 1, 28, 28)
# 创建4张图片,一个通道(黑白照片),28*28像素点的图片
print(a.shape)
# 查看a的shape
b = a.view(4, 28*28)
# 代表将后面28*28的像素点全合并在一起,这样变为[4, 784]的shape,各个像素点失去了上下级的关系,全部被打平。这样处理的数据适合于全连接层的计算
print(b.shape)
print(b)
torch.Size([4, 1, 28, 28])
torch.Size([4, 784])
tensor([[0.0340, 0.7099, 0.4833, ..., 0.2647, 0.2162, 0.7296],
[0.3813, 0.8616, 0.8151, ..., 0.9942, 0.2087, 0.8194],
[0.9671, 0.1019, 0.7831, ..., 0.0181, 0.1157, 0.7953],
[0.5822, 0.3729, 0.2884, ..., 0.0572, 0.4267, 0.1253]])
同时也可以进行其他类型维度转换
# 进行其他类型维度转换
c = a.view(4*28, 28)
# 代表只关心行数据
print(c.shape)
print(c)
输出
torch.Size([112, 28])
tensor([[0.5150, 0.7596, 0.2775, ..., 0.5091, 0.2392, 0.8344],
[0.9011, 0.5765, 0.2927, ..., 0.5699, 0.3586, 0.8753],
[0.7888, 0.3819, 0.2285, ..., 0.0180, 0.8713, 0.2788],
...,
[0.7574, 0.8183, 0.7526, ..., 0.8110, 0.7561, 0.3782],
[0.6651, 0.1608, 0.4255, ..., 0.6095, 0.8237, 0.4504],
[0.1026, 0.9139, 0.0975, ..., 0.7457, 0.7392, 0.9503]])
在进行高维向低维进行转换时,
# 进行高维至低维时
d = c.view(8, 14, 7, 4)
print(d.shape)
print(d)
torch.Size([8, 14, 7, 4])
tensor([[[[6.1078e-01, 6.2038e-01, 4.8822e-01, 2.2785e-01],
[4.3340e-01, 7.3079e-01, 5.3903e-01, 5.7458e-01],
[2.6486e-01, 6.3135e-01, 6.4279e-01, 1.0438e-01],
...,
[9.3821e-01, 4.5505e-01, 2.4141e-01, 5.1869e-01],
[6.4698e-01, 2.9054e-01, 4.0393e-01, 3.7668e-01],
[9.6046e-03, 9.4442e-01, 2.5506e-01, 2.3018e-01]],
...,
[[5.2430e-01, 8.8357e-02, 7.4498e-01, 2.3804e-01],
[5.9681e-01, 4.2410e-01, 7.5572e-01, 6.7488e-01],
[6.7680e-01, 5.3951e-01, 1.5074e-01, 2.8085e-01],
...,
[5.3654e-01, 1.8240e-01, 2.3953e-01, 8.9576e-01],
[9.3373e-01, 4.6603e-01, 8.9729e-01, 1.0706e-01],
[7.7679e-01, 7.8289e-01, 3.5601e-01, 4.7687e-02]]]])
由此可见,只要总tensor数值相同,既可以进行任意维度上的转换。但要注意变换后的物理意义,不要随便进行转换。
总之,view和shape操作,不变的是数据本身,变的是对数据的理解方式。要时刻注意数据的排列方式(数据的batch_size、channel number、height、width),不要破坏数据。
本文分享自 python pytorch AI机器学习实践 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体分享计划 ,欢迎热爱写作的你一起参与!