Pytorch定义Pooling Layer以及ReLU Layer
-
Pooling
Pooling的讲解可以看我的这篇文章CS231n 笔记:通俗理解 CNN
这里主要讲解一下如何用 pytorch定义Pooling层,有两种方式,具体看下面代码
import torch import torch.nn as nn import torch.nn.functional as F x = torch.rand(1, 16, 14, 14) # 第一种方式 layer = nn.MaxPool2d(2, stride=2) # 第一个参数是:窗口的大小 2*2 out = layer(x) print(out.shape) # 第二种方式 out = F.avg_pool2d(x, 2, stride=2)
除了下采样,Pytorch还可以实现上采样
上图从左至右的过程为上采样过程,将原数据进行复制即得到新的数据
import torch import torch.nn as nn import torch.nn.functional as F x = torch.rand(1, 16, 28, 28) out = F.interpolate(x, scale_factor=2, mode='nearest') # 上采样的API为:.interpolate # 括号内参数为输入的tensor、放大的倍率、模式为紧邻差值法 print(out.shape) # torch.Size([1, 16, 56, 56])
上采样不改变channel,而会把原来的大小放大指定的倍数
ReLU
最后再简单介绍一下ReLU的效果
之前有介绍过ReLU函数时将低于某个阈值的输出全部归为0,高于阈值的线性输出。上图就是使用ReLU之后的效果,黑色区域全部被消除了
import torch import torch.nn as nn import torch.nn.functional as F x = torch.rand(1, 16, 7, 7) # 第一种方式 layer = nn.ReLU(inplace=True) # inpalce设为True会同时改变输入的参数x,若设为false则不会 out = layer(x) print(out.shape) # torch.Size([1, 16, 7, 7]) # 第二种方式 out = F.relu(x)