Tensorflow的LRN是怎么做的

时间:2022-05-06
本文章向大家介绍Tensorflow的LRN是怎么做的,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

LRN全称是local response normalization,局部响应归一化,想了解原理的点这个AlexNet(http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks)。

看了Alex写的论文,里面介绍了LRN,稀里糊涂的,第一遍根本没看懂,于是我就想,先看看tensorflow怎么做的LRN吧,然后我就看明白了,但我貌似讲不太明白。。。。首先,公式是这样的:

LRN

其次,官方API的介绍是这样的:

sqr_sum[a, b, c, d] = sum(input[a,b, c, d - depth_radius : d + depth_radius + 1] ** 2) output = input / (bias +alpha * sqr_sum) ** beta

以alexnet的论文为例,输入暂且定为 [batch_size, 224, 224, 96],这里224×224是图片的大小,经过第一次卷积再经过ReLU,就是LRN函数的输入。

注意上面API说明里的sum函数,意思就是,可能解释起来比较拗口,针对batch里每一个图的后3维向量,[224, 224, d - depth_radius : d + depth_radius + 1],对它按照半径 depth_radius求每个图里的每个像素的平方,再把这2× depth_radius+1个平方过后的图片加起来,就得到了这个batch的sqr_sum。

不得不说,上面一段解释太差强人意了,貌似还不太对,于是我又思考了一下,从新解释,顺便给出一个小程序以验证,程序如下:

import numpy as npimport tensorflow as tf a = 2 * np.ones([2, 2, 2, 3]) b = tf.nn.local_response_normalization(a, 1, 0, 1, 1) sess = tf.Session()print sess.run(b)

为了简化,上面的程序中令depth_radius=1,bias=0,alpha=1,beta=1,这样算出的结果就相当于:

output = input / sqr_sum

实际运行的结果是这样的:

# a的原始值
array([[[[ 2.,  2.,  2.],            
[ 2.,  2.,  2.]],         
 [[ 2.,  2.,  2.],         
 [ 2.,  2.,  2.]]],          
[[[ 2.,  2.,  2.],         
 [ 2.,  2.,  2.]],         
 [[ 2.,  2.,  2.],         
 [ 2.,  2.,  2.]]]]
# a经过LRN之后的值
array([[[[ 0.25      ,  0.16666667,  0.25      ],  
         [ 0.25      ,  0.16666667,  0.25      ]],          
[[ 0.25      ,  0.16666667,  0.25      ],          
[ 0.25      ,  0.16666667,  0.25      ]]],          
[[[ 0.25      ,  0.16666667,  0.25      ],          
[ 0.25      ,  0.16666667,  0.25      ]],         
 [[ 0.25      ,  0.16666667,  0.25      ],          
[ 0.25      ,  0.16666667,  0.25      ]]]], dtype=float32)

这样就很明显了,针对上面的例子,解释如下:

先求某个图(就叫图A吧)周围1半径内(这个半径在第四个维度上,包括图A本身)的图的像素的平方和S,S是三个图像素平方和相加的结果,S的shape是[2, 2],然后A除以S,如下

A = [[2, 2], S = [[12, 12], [2, 2]] [12, 12]] O = A/S = [[0.16666667, 0.16666667], [0.16666667, 0.16666667]]

这就是上面0.16666667这个数的由来了,总的来讲,当depth_radius=1,bias=0,alpha=1,beta=1时,LRN就是“每个图”除以“半径以内的其他图对应像素的平方和”,就是结果啦!

只能解释到这里了。。

最后还想再说一句,根据Stanford的CS231(http://cs231n.github.io/)所讲,最近LRN用的并不多,因为效果不好吧。