MENU

Pytorch 定义 Pooling Layer 以及 ReLU Layer

January 10, 2020 • Read: 3590 • Deep Learning阅读设置

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 的效果
ch

之前有介绍过 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)
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment