文章内容皆为个人理解,如有不足欢迎指正。
1、torch.reshape()
reshape()可以由torch.reshape(),也可由torch.Tensor.reshape()调用
其作用是在不改变tensor元素数目的情况下改变tensor的shape
import torch
import numpy as np
a = np.arange(24)
b = a.reshape(4,3,2)
print(np.shape(a))
print(b,np.shape(b))
'''结果
(24,)
[[[ 0 1]
[ 2 3]
[ 4 5]]
[[ 6 7]
[ 8 9]
[10 11]]
[[12 13]
[14 15]
[16 17]]
[[18 19]
[20 21]
[22 23]]] (4, 3, 2)
'''
2、view()
view()只可以由torch.Tensor.view()来调用
view()和reshape()在效果上是一样的,区别是view()只能操作contiguous的tensor,且view后的tensor和原tensor共享存储,reshape()对于是否contiuous的tensor都可以操作。
3、transpose()
torch.transpose(input, dim0, dim1) -> Tensor
将输入数据input的第dim0维和dim1维进行交换
#官方例子
>>> x = torch.randn(2, 3)
>>> x
tensor([[ 0.9068, 1.8803, -0.5021],
[-0.6576, 0.6334, -0.8961]])
>>> torch.transpose(x, 0, 1)
tensor([[ 0.9068, -0.6576],
[ 1.8803, 0.6334],
[-0.5021, -0.8961]])
4、flatten()
torch.flatten()的输入是tensor
torch.flatten(input, start_dim=0, end_dim=-1) → Tensor
其作用是将输入tensor的第start_dim维到end_dim维之间的数据“拉平”成一维tensor,
#官方例子
>>> t = torch.tensor([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
>>> torch.flatten(t)
tensor([1, 2, 3, 4, 5, 6, 7, 8])
>>> torch.flatten(t, start_dim=1)
tensor([[1, 2, 3, 4],
[5, 6, 7, 8]])
torch.nn.Flatten()可以理解为一种网络结构,类似Conv2d、Linear。一般放在卷积层和全连接层之间,将卷积层输出“拉平”成一维,
>>> m = torch.nn.Sequential(
torch.nn.Conv2d(1, 32, 5, 1, 1),
torch.nn.Flatten(),
torch.nn.Linear(160,10))
>>> m
Sequential(
(0): Conv2d(1, 32, kernel_size=(5, 5), stride=(1, 1), padding=(1, 1))
(1): Flatten()
(2): Linear(in_features=160, out_features=10, bias=True)
)
参考:
https://congluwen.top/2018/12/pytorch_reshape_view/
https://blog.csdn.net/GhostintheCode/article/details/102530451