池化层返回窗口的最大或平均值
缓解卷积层对位置的敏感性
Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.22.0 -- An enhanced Interactive Python. Type '?' for help. PyDev console: using IPython 7.22.0 Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] on win32 import torch from torch import nn from d2l import torch as d2l def pool2d(X, pool_size, mode='max'): p_h, p_w = pool_size Y = torch.zeros((X.shape[0] - p_h + 1, X.shape[1] - p_w + 1)) for i in range(Y.shape[0]): for j in range(Y.shape[1]): if mode == 'max': Y[i, j] = X[i: i + p_h, j: j + p_w].max() elif mode == 'avg': Y[i, j] = X[i: i + p_h, j: j + p_w].mean() return Y X = torch.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]) pool2d(X, (2, 2)) Out[4]: tensor([[4., 5.], [7., 8.]]) pool2d(X, (2, 2), 'avg') Out[5]: tensor([[2., 3.], [5., 6.]])填充和步幅
X = torch.arange(16, dtype=d2l.float32).reshape((1, 1, 4, 4)) X Out[6]: tensor([[[[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [12., 13., 14., 15.]]]]) pool2d = nn.MaxPool2d(3)#深度学习框架中的步幅与池化窗口的大小相同,后面不够了 pool2d(X) Out[7]: tensor([[[[10.]]]]) pool2d = nn.MaxPool2d(3, padding=1, stride=2) pool2d(X)#可以自己设定 Out[8]: tensor([[[[ 5., 7.], [13., 15.]]]]) pool2d = nn.MaxPool2d((2, 3), padding=(1, 1), stride=(2, 3)) pool2d(X) Out[9]: tensor([[[[ 1., 3.], [ 9., 11.], [13., 15.]]]])多个通道
X = torch.cat((X, X + 1), 1) X Out[11]: tensor([[[[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [12., 13., 14., 15.]], [[ 1., 2., 3., 4.], [ 5., 6., 7., 8.], [ 9., 10., 11., 12.], [13., 14., 15., 16.]]]]) pool2d = nn.MaxPool2d(3, padding=1, stride=2) pool2d(X) Out[12]: tensor([[[[ 5., 7.], [13., 15.]], [[ 6., 8.], [14., 16.]]]])
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)