随机池化(Stochastic Pooling)

news/2024/11/6 21:36:38/

前言      

       CNN中卷积完后有个步骤叫pooling, 在ICLR2013上,作者Zeiler提出了另一种pooling手段(最常见的就是mean-pooling和max-pooling),叫stochastic pooling。只需要对Feature Map中的元素按照其概率值大小随机选择,元素选中的概率与其数值大小正相关,并非如同max pooling那样直接选取最大值。这种随机池化操作不但最大化地保证了取值的Max,也部分确保不会所有的元素都被选取max值,从而提高了泛化能力。

       stochastic pooling方法非常简单,只需对feature map中的元素按照其概率值大小随机选择,即元素值大的被选中的概率也大。而不像max-pooling那样,永远只取那个最大值元素。

计算过程

  1)先将方格中的元素同时除以它们的和sum,得到概率矩阵;
  2)按照概率随机选中方格;
  3)pooling得到的值就是方格位置的值。
  使用stochastic pooling时(即test过程),其推理过程也很简单,对矩阵区域求加权平均即可。
  在反向传播求导时,只需保留前向传播已经记录被选中节点的位置的值,其它值都为0,这和max-pooling的反向传播非常类似。

  假设feature map中的pooling区域元素值如下:

      

       3*3大小的,元素值和sum=0+1.1+2.5+0.9+2.0+1.0+0+1.5+1.0=10

       方格中的元素同时除以sum后得到的矩阵元素为:

       

       每个元素值表示对应位置处值的概率,现在只需要按照该概率来随机选一个,方法是:将其看作是9个变量的多项式分布,然后对该多项式分布采样即可,theano中有直接的multinomial()来函数完成。当然也可以自己用01均匀分布来采样,将单位长度1按照那9个概率值分成9个区间(概率越大,覆盖的区域越长,每个区间对应一个位置),然后随机生成一个数后看它落在哪个区间。

  比如如果随机采样后的矩阵为:

      

       则这时候的poolng值为1.5

  使用stochastic pooling时(即test过程),其推理过程也很简单,对矩阵区域求加权平均即可。比如对上面的例子求值过程为为: 0*0+1.1*0.11+2.5*0.25+0.9*0.09+2.0*0.2+1.0*0.1+0*0+1.5*0.15+1.0*0.1=1.625 说明此时对小矩形pooling后的结果为1.625.

  在反向传播求导时,只需保留前向传播已经记录被选中节点的位置的值,其它值都为0,这和max-pooling的反向传播非常类似。

Stochastic pooling优点:

       方法简单;

  泛化能力更强;

  可用于卷积层(文章中是与Dropout和DropConnect对比的,说是Dropout和DropConnect不太适合于卷积层. 不过个人感觉这没什么可比性,因为它们在网络中所处理的结构不同);

  至于为什么stochastic pooling效果好,作者说该方法也是模型平均的一种,没怎么看懂。

  关于Stochastic Pooling的前向传播过程和推理过程的代码可参考下列代码(没包括bp过程,所以代码中pooling选择的位置没有保存下来):

"""
An implementation of stochastic max-pooling, based onStochastic Pooling for Regularization of Deep Convolutional Neural Networks
Matthew D. Zeiler, Rob Fergus, ICLR 2013
"""__authors__ = "Mehdi Mirza"
__copyright__ = "Copyright 2010-2012, Universite de Montreal"
__credits__ = ["Mehdi Mirza", "Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "Mehdi Mirza"
__email__ = "mirzamom@iro"import numpy
import theano
from theano import tensor
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from theano.gof.op import get_debug_valuesdef stochastic_max_pool_bc01(bc01, pool_shape, pool_stride, image_shape, rng = None):"""Stochastic max pooling for training as defined in:Stochastic Pooling for Regularization of Deep Convolutional Neural NetworksMatthew D. Zeiler, Rob Fergusbc01: minibatch in format (batch size, channels, rows, cols),IMPORTANT: All values should be poitiviepool_shape: shape of the pool region (rows, cols)pool_stride: strides between pooling regions (row stride, col stride)image_shape: avoid doing some of the arithmetic in theanorng: theano random stream"""r, c = image_shapepr, pc = pool_shapers, cs = pool_stridebatch = bc01.shape[0] #总共batch的个数channel = bc01.shape[1] #通道个数if rng is None:rng = RandomStreams(2022)# Compute index in pooled space of last needed pool# (needed = each input pixel must appear in at least one pool)def last_pool(im_shp, p_shp, p_strd):rval = int(numpy.ceil(float(im_shp - p_shp) / p_strd))assert p_strd * rval + p_shp >= im_shpassert p_strd * (rval - 1) + p_shp < im_shpreturn rval #表示pool过程中需要移动的次数return T.dot(x, self._W)# Compute starting row of the last poollast_pool_r = last_pool(image_shape[0] ,pool_shape[0], pool_stride[0]) * pool_stride[0] #最后一个pool的起始位置# Compute number of rows needed in image for all indexes to work outrequired_r = last_pool_r + pr #满足上面pool条件时所需要image的高度last_pool_c = last_pool(image_shape[1] ,pool_shape[1], pool_stride[1]) * pool_stride[1]required_c = last_pool_c + pc# final result shaperes_r = int(numpy.floor(last_pool_r/rs)) + 1 #最后pool完成时图片的shaperes_c = int(numpy.floor(last_pool_c/cs)) + 1for bc01v in get_debug_values(bc01):assert not numpy.any(numpy.isinf(bc01v))assert bc01v.shape[2] == image_shape[0]assert bc01v.shape[3] == image_shape[1]# padding,如果不能整除移动,需要对原始图片进行扩充padded = tensor.alloc(0.0, batch, channel, required_r, required_c)name = bc01.nameif name is None:name = 'anon_bc01'bc01 = tensor.set_subtensor(padded[:,:, 0:r, 0:c], bc01)bc01.name = 'zero_padded_' + name# unravelingwindow = tensor.alloc(0.0, batch, channel, res_r, res_c, pr, pc)window.name = 'unravlled_winodows_' + namefor row_within_pool in xrange(pool_shape[0]):row_stop = last_pool_r + row_within_pool + 1for col_within_pool in xrange(pool_shape[1]):col_stop = last_pool_c + col_within_pool + 1win_cell = bc01[:,:,row_within_pool:row_stop:rs, col_within_pool:col_stop:cs]window  =  tensor.set_subtensor(window[:,:,:,:, row_within_pool, col_within_pool], win_cell) #windows中装的是所有的pooling数据块# find the normnorm = window.sum(axis = [4, 5]) #求和当分母用 norm = tensor.switch(tensor.eq(norm, 0.0), 1.0, norm) #如果norm为0,则将norm赋值为1norm = window / norm.dimshuffle(0, 1, 2, 3, 'x', 'x') #除以norm得到每个位置的概率# get probprob = rng.multinomial(pvals = norm.reshape((batch * channel * res_r * res_c, pr * pc)), dtype='float32') #multinomial()函数能够按照pvals产生多个多项式分布,元素值为0或1# selectres = (window * prob.reshape((batch, channel, res_r, res_c,  pr, pc))).max(axis=5).max(axis=4) #window和后面的矩阵相乘是点乘,即对应元素相乘,numpy矩阵符号res.name = 'pooled_' + namereturn tensor.cast(res, theano.config.floatX)def weighted_max_pool_bc01(bc01, pool_shape, pool_stride, image_shape, rng = None):"""This implements test time probability weighted pooling defined in:Stochastic Pooling for Regularization of Deep Convolutional Neural NetworksMatthew D. Zeiler, Rob Fergusbc01: minibatch in format (batch size, channels, rows, cols),IMPORTANT: All values should be poitiviepool_shape: shape of the pool region (rows, cols)pool_stride: strides between pooling regions (row stride, col stride)image_shape: avoid doing some of the arithmetic in theano"""r, c = image_shapepr, pc = pool_shapers, cs = pool_stridebatch = bc01.shape[0]channel = bc01.shape[1]if rng is None: rng = RandomStreams(2022) # Compute index in pooled space of last needed pool # (needed = each input pixel must appear in at least one pool)def last_pool(im_shp, p_shp, p_strd):rval = int(numpy.ceil(float(im_shp - p_shp) / p_strd))assert p_strd * rval + p_shp >= im_shpassert p_strd * (rval - 1) + p_shp < im_shpreturn rval# Compute starting row of the last poollast_pool_r = last_pool(image_shape[0] ,pool_shape[0], pool_stride[0]) * pool_stride[0]# Compute number of rows needed in image for all indexes to work outrequired_r = last_pool_r + prlast_pool_c = last_pool(image_shape[1] ,pool_shape[1], pool_stride[1]) * pool_stride[1]required_c = last_pool_c + pc# final result shaperes_r = int(numpy.floor(last_pool_r/rs)) + 1res_c = int(numpy.floor(last_pool_c/cs)) + 1for bc01v in get_debug_values(bc01):assert not numpy.any(numpy.isinf(bc01v))assert bc01v.shape[2] == image_shape[0]assert bc01v.shape[3] == image_shape[1]# paddingpadded = tensor.alloc(0.0, batch, channel, required_r, required_c)name = bc01.nameif name is None:name = 'anon_bc01'bc01 = tensor.set_subtensor(padded[:,:, 0:r, 0:c], bc01)bc01.name = 'zero_padded_' + name# unravelingwindow = tensor.alloc(0.0, batch, channel, res_r, res_c, pr, pc)window.name = 'unravlled_winodows_' + namefor row_within_pool in xrange(pool_shape[0]):row_stop = last_pool_r + row_within_pool + 1for col_within_pool in xrange(pool_shape[1]):col_stop = last_pool_c + col_within_pool + 1win_cell = bc01[:,:,row_within_pool:row_stop:rs, col_within_pool:col_stop:cs]window  =  tensor.set_subtensor(window[:,:,:,:, row_within_pool, col_within_pool], win_cell)# find the normnorm = window.sum(axis = [4, 5])norm = tensor.switch(tensor.eq(norm, 0.0), 1.0, norm)norm = window / norm.dimshuffle(0, 1, 2, 3, 'x', 'x')# averageres = (window * norm).sum(axis=[4,5]) #前面的代码几乎和前向传播代码一样,这里只需加权求和即可res.name = 'pooled_' + namereturn res.reshape((batch, channel, res_r, res_c))

小Tips:

概率是频率随样本趋于无穷的极限

期望是平均数随样本趋于无穷的极限


http://www.ppmy.cn/news/358978.html

相关文章

内核实验(二):自定义一个迷你Linux ARM系统,基于Kernel v5.15.102, Busybox,Qemu

文章目录 一、篇头二、内核部分2.1 源码下载2.1.1 官网2.1.2 镜像站点2.1.3 代码下载 2.2 编译2.2.1 设置工具链2.2.2 配置2.2.3 make2.2.4 编译成功 三、busybox部分3.1 源码下载3.2 编译3.2.1 配置3.2.3 编译3.2.4 查看编译结果 四、制作根文件系统4.1 回顾busybox4.2 修改bu…

BC1.2

► BC1.2规范颁布之前 在2007年第一个电池充电规范颁布之前&#xff0c;尝试为电池充电本质上是一种冒险——结果非常难以预测。当2000年 出现USB 2.0时&#xff0c;外设默认吸收100mA电流&#xff0c;除非明确协商将电流增大至最高500mA。如果总线上经过一段延迟后 没有数据活…

Fabric

1 安装Go、docker、docker-compose 1.1 安装Go 获取go的安装包并解压到/usr/local文件夹下&#xff1a; sudo wget -P /usr/local https://studygolang.com/dl/golang/go1.15.linux-amd64.tar.gz cd /usr/local sudo tar -zxvf go1.15.linux-amd64.tar.gz添加环境变量 vim …

BCC入门

简介 BPF编译器集合&#xff08;BPF Compiler Collection&#xff0c;简称BCC&#xff09;。项目地址https://github.com/iovisor/bcc&#xff0c;是一个用于创建高效内核跟踪和操作程序的工具包&#xff0c;包括几个有用的工具和示例。它利用了扩展的 BPF&#xff08;伯克利包…

【NLP】第3章 微调 BERT 模型

&#x1f50e;大家好&#xff0c;我是Sonhhxg_柒&#xff0c;希望你看完之后&#xff0c;能对你有所帮助&#xff0c;不足请指正&#xff01;共同学习交流&#x1f50e; &#x1f4dd;个人主页&#xff0d;Sonhhxg_柒的博客_CSDN博客 &#x1f4c3; &#x1f381;欢迎各位→点赞…

内核实验(三):编写简单Linux内核模块,使用Qemu加载ko做测试

文章目录 一、篇头二、QEMU&#xff1a;挂载虚拟分区2.1 创建 sd.ext4.img 虚拟分区2.2 启动 Qemu2.3 手动挂载 sd.ext4.img三、实现一个简单的KO3.1 目录文件3.2 Makefile3.3 编译3.3.1 编译打印3.3.2 生成文件 3.4 检查&#xff1a;objdump3.4.1 objdump -dS test\_1.ko3.4.2…

B001_简介篇

&#x1f3c6;一、Oracle的历史和发展 Oracle公司成立于1977年&#xff0c;由拉里埃里森&#xff08;Larry Ellison&#xff09;、鲍勃明特&#xff08;Bob Miner&#xff09;和埃德奥茨&#xff08;Ed Oates&#xff09;共同创立。起初&#xff0c;公司的主要业务是开发和销售…

如何计算一个实例占用多少内存?

我们都知道CPU和内存是程序最为重要的两类指标&#xff0c;那么有多少人真正想过这个问题&#xff1a;一个类型&#xff08;值类型或者引用类型&#xff09;的实例在内存中究竟占多少字节&#xff1f;我们很多人都回答不上来。其实C#提供了一些用于计算大小的操作符和API&#…