operation
view/reshape
squeeze/unsqueeze
transpose/ t / permute
expand/ repeat
1.view/reshape
import torch
a = torch.rand(4, 1, 28, 28)
# 使用rand随机均匀初始化一个4维的tensor
# 在minist中可以理解为load进了4张灰度图片,长宽各为28
a.shape
output:
torch.Size([4, 1, 28, 28])
下面进行view操作:
a.view(4, 28 * 28)
# 4 1 * 28 * 28
output:
tensor([[0.1915, 0.9915, 0.4148, ..., 0.3582, 0.4939, 0.7734],
[0.7373, 0.5476, 0.0908, ..., 0.2784, 0.0220, 0.3247],
[0.6855, 0.1770, 0.6714, ..., 0.3116, 0.5055, 0.1866],
[0.0151, 0.9768, 0.4203, ..., 0.7694, 0.7458, 0.2084]])
(view必须满足物理意义,否则会导致数据的”污染“)
打印shape
a.view(4, 28 * 28).shape
output
torch.Size([4, 784])
b = a.view(4, 784)
# 这个时造成了数据的污染,b.view(4, 28, 28, 1)这样子也等