首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >tensorflow: bn层 的 decay参数项

tensorflow: bn层 的 decay参数项

作者头像
JNingWei
发布于 2018-09-28 07:39:59
发布于 2018-09-28 07:39:59
2.2K00
代码可运行
举报
文章被收录于专栏:JNing的专栏JNing的专栏
运行总次数:0
代码可运行

实验:

探究 batch normalization 过程中的 decay 参数项 在 train 和 test 过程中的不同作用。

结论:

  1. train 过程改变参数,而 test 过程不改变参数;
  2. test过程中直接沿用了train出来的参数进行计算;
  3. decay参数项目虽然在 train 和 test 过程中都有,在train过程中,不对求解结果产生影响,只对求解结束时参数项的偏移程度产生影响;
  4. 当 decay=1 时,train求解过程结束后,虽然计算结果是正确的,但是内存中的参数项没有得到相应的偏移,直接导致了调用这些参数项的test过程无法进行归一化计算。

验证代码:

  在 decay=0 (即移动偏移无损失)时:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import tensorflow as tf


def func(in_put, layer_name, is_training=True):
    with tf.variable_scope(layer_name, reuse=tf.AUTO_REUSE):
        bn = tf.contrib.layers.batch_norm(inputs=in_put,
                                          decay=0,
                                          is_training=is_training,
                                          updates_collections=None)
    return bn

def main():

    with tf.Graph().as_default():
        # input_x:只使用一套input_x,以控制变量进行对照试验
        input_x = tf.placeholder(dtype=tf.float32, shape=[1, 4, 4, 1])
        import numpy as np
        i_p = np.random.uniform(low=0, high=255, size=[1, 4, 4, 1])
        # outputs:画好 train 和 test 状态下不同的数据流图,分别放在outputs[0]和outputs[1]里
        outputs = [0, 0]
        for i, is_training in enumerate([True, False]):
            outputs[i] = func(input_x, 'my', is_training=is_training)
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            # 先 train ,再用 train 训练好的 'my/BatchNorm/moving_mean:0''my/BatchNorm/moving_variance:0' 去跑 test
            for i in xrange(2):
                # 跑 train/test 之前的参数
                print '\n\n-------------\n\n'
                for (x, y) in zip(tf.global_variables(), sess.run(tf.global_variables())):
                    print '\n', x, ':\n', y
                # 跑 train/test
                t = sess.run(outputs[i], feed_dict={input_x:i_p})
                print t
                # 跑完 train/test 之后的参数
                for (x, y) in zip(tf.global_variables(), sess.run(tf.global_variables())):
                    print '\n', x, ':\n', y

if __name__ == "__main__":
    main()

观察:由以下打印出的 output 可知,经过train之后,’my/BatchNorm/moving_mean:0’ 变成了[ 114.78817749]、’my/BatchNorm/moving_variance:0’ 变成了[ 5496.60107422]。

结论: 1. train 过程改变参数,而 test 过程不改变参数; 2. test过程中直接沿用了train出来的参数进行计算。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
2017-09-29 09:08:27.739093: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1052] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: GeForce GTX 1070, pci bus id: 0000:01:00.0, compute capability: 6.1)


------------- # train


<tf.Variable 'my/BatchNorm/beta:0' shape=(1,) dtype=float32_ref> :
[ 0.]

<tf.Variable 'my/BatchNorm/moving_mean:0' shape=(1,) dtype=float32_ref> :
[ 0.]

<tf.Variable 'my/BatchNorm/moving_variance:0' shape=(1,) dtype=float32_ref> :
[ 1.]
[[[[ 0.27311635]
   [-0.7590425 ]
   [-0.4103117 ]
   [-1.40655911]]

  [[-0.25747275]
   [ 0.40145767]
   [ 0.46040225]
   [ 1.17546725]]

  [[-1.32714963]
   [-1.20369065]
   [-0.08007884]
   [-0.7148838 ]]

  [[ 1.18637156]
   [ 1.85863471]
   [-0.70913869]
   [ 1.51287651]]]]

<tf.Variable 'my/BatchNorm/beta:0' shape=(1,) dtype=float32_ref> :
[ 0.]

# 经过train之后,'my/BatchNorm/moving_mean:0' 变成了[ 114.78817749]、
# 'my/BatchNorm/moving_variance:0'  变成了[ 5496.60107422]<tf.Variable 'my/BatchNorm/moving_mean:0' shape=(1,) dtype=float32_ref> :
[ 114.78817749]

<tf.Variable 'my/BatchNorm/moving_variance:0' shape=(1,) dtype=float32_ref> :
[ 5496.60107422]


------------- # test


# test过程中直接沿用了train出来的参数进行计算。
<tf.Variable 'my/BatchNorm/beta:0' shape=(1,) dtype=float32_ref> :
[ 0.]

<tf.Variable 'my/BatchNorm/moving_mean:0' shape=(1,) dtype=float32_ref> :
[ 114.78817749]

<tf.Variable 'my/BatchNorm/moving_variance:0' shape=(1,) dtype=float32_ref> :
[ 5496.60107422]
[[[[ 0.27311635]
   [-0.7590425 ]
   [-0.4103117 ]
   [-1.40655911]]

  [[-0.25747275]
   [ 0.40145767]
   [ 0.46040225]
   [ 1.17546725]]

  [[-1.32714963]
   [-1.20369065]
   [-0.08007884]
   [-0.7148838 ]]

  [[ 1.18637156]
   [ 1.85863471]
   [-0.70913869]
   [ 1.51287651]]]]

<tf.Variable 'my/BatchNorm/beta:0' shape=(1,) dtype=float32_ref> :
[ 0.]

# test过程中,'my/BatchNorm/moving_mean:0'、
# 'my/BatchNorm/moving_variance:0' 不发生变化。
<tf.Variable 'my/BatchNorm/moving_mean:0' shape=(1,) dtype=float32_ref> :
[ 114.78817749]

<tf.Variable 'my/BatchNorm/moving_variance:0' shape=(1,) dtype=float32_ref> :
[ 5496.60107422]

Process finished with exit code 0

  在 decay=1 (即移动偏移全损失)时:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import tensorflow as tf


def func(in_put, layer_name, is_training=True):
    with tf.variable_scope(layer_name, reuse=tf.AUTO_REUSE):
        bn = tf.contrib.layers.batch_norm(inputs=in_put,
                                          decay=1,
                                          is_training=is_training,
                                          updates_collections=None)
    return bn


def main():

    with tf.Graph().as_default():
        # input_x
        input_x = tf.placeholder(dtype=tf.float32, shape=[1, 4, 4, 1])
        import numpy as np
        i_p = np.random.uniform(low=0, high=255, size=[1, 4, 4, 1])
        # outputs
        outputs = [0, 0]
        for i, is_training in enumerate([True, False]):
            outputs[i] = func(input_x, 'my', is_training=is_training)
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            for i in xrange(2):
                print '\n\n-------------\n\n'
                for (x, y) in zip(tf.global_variables(), sess.run(tf.global_variables())):
                    print '\n', x, ':\n', y
                t = sess.run(outputs[i], feed_dict={input_x:i_p})
                print t
                for (x, y) in zip(tf.global_variables(), sess.run(tf.global_variables())):
                    print '\n', x, ':\n', y
                # print (sess.run(tf.get_variable('my/BatchNorm/beta:0')))

if __name__ == "__main__":
    main()

观察:由以下打印出的 output 可知,decay=1时,经过train之后,’my/BatchNorm/moving_mean:0’ 变成了[ 114.78817749]、 ‘my/BatchNorm/moving_variance:0’ 变成了[ 5496.60107422]。test过程中沿用了train过程中改变的参数值,但是test结果并没有被归一化。

结论: 1. decay参数项目虽然在 train 和 test 过程中都有,在train过程中,不对求解结果产生影响,只对求解结束时参数项的偏移程度产生影响。当 decay=1 时,train求解过程结束后,虽然计算结果是正确的,但是内存中的参数项没有得到相应的偏移,直接导致了调用这些参数项的test过程无法进行归一化计算。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
2017-09-29 09:10:34.590984: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1052] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: GeForce GTX 1070, pci bus id: 0000:01:00.0, compute capability: 6.1)


------------- # train


<tf.Variable 'my/BatchNorm/beta:0' shape=(1,) dtype=float32_ref> :
[ 0.]

<tf.Variable 'my/BatchNorm/moving_mean:0' shape=(1,) dtype=float32_ref> :
[ 0.]

<tf.Variable 'my/BatchNorm/moving_variance:0' shape=(1,) dtype=float32_ref> :
[ 1.]
# decay参数项 不影响 train 过程的计算结果
[[[[ 1.58194923]
   [ 1.092067  ]
   [ 0.90377307]
   [-0.54407573]]

  [[-1.40420842]
   [-1.2678678 ]
   [-2.07936239]
   [-0.7029525 ]]

  [[ 0.66369891]
   [ 0.8902123 ]
   [-0.08132553]
   [-0.80555594]]

  [[ 0.52472615]
   [ 0.6974256 ]
   [ 0.22497487]
   [ 0.30652118]]]]

<tf.Variable 'my/BatchNorm/beta:0' shape=(1,) dtype=float32_ref> :
[ 0.]

# decay参数项 会影响 train过程的 参数值 变化
<tf.Variable 'my/BatchNorm/moving_mean:0' shape=(1,) dtype=float32_ref> :
[ 0.]

<tf.Variable 'my/BatchNorm/moving_variance:0' shape=(1,) dtype=float32_ref> :
[ 1.]


------------- # test


<tf.Variable 'my/BatchNorm/beta:0' shape=(1,) dtype=float32_ref> :
[ 0.]

<tf.Variable 'my/BatchNorm/moving_mean:0' shape=(1,) dtype=float32_ref> :
[ 0.]

<tf.Variable 'my/BatchNorm/moving_variance:0' shape=(1,) dtype=float32_ref> :
[ 1.]
# 由于从train继承来的参数值的缘故,test过程中的计算变成了 非归一化计算
[[[[ 223.02729797]
   [ 193.41201782]
   [ 182.02893066]
   [  94.50087738]]

  [[  42.50252914]
   [  50.74484634]
   [   1.68685985]
   [  84.89615631]]

  [[ 167.51550293]
   [ 181.2091217 ]
   [ 122.47590637]
   [  78.69338226]]

  [[ 159.11407471]
   [ 169.5544281 ]
   [ 140.99295044]
   [ 145.92274475]]]]

<tf.Variable 'my/BatchNorm/beta:0' shape=(1,) dtype=float32_ref> :
[ 0.]

<tf.Variable 'my/BatchNorm/moving_mean:0' shape=(1,) dtype=float32_ref> :
[ 0.]

<tf.Variable 'my/BatchNorm/moving_variance:0' shape=(1,) dtype=float32_ref> :
[ 1.]

Process finished with exit code 0


本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年09月29日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
tensorflow: bn层
可视化 batch normalization 过程中的 tensor演化(以输入一张[1, 4 , 4, 1]的图片为例)
JNingWei
2018/09/28
1.1K0
tensorflow: 打印内存中的变量
法一: 循环打印 模板 for (x, y) in zip(tf.global_variables(), sess.run(tf.global_variables())): print '\n', x, y 实例 # coding=utf-8 import tensorflow as tf def func(in_put, layer_name, is_training=True): with tf.variable_scope(layer_name, reuse=tf.AUT
JNingWei
2018/09/28
2.1K0
tensorflow编程: Layers (contrib)
min(max(features, 0), 6)。即对 tf.nn.relu 的优化,防止 relu过后 某些 极端值 依然 大于6
JNingWei
2018/09/28
8630
tensorflow使用BN—Batch Normalization
本文介绍了TensorFlow中的BN-Batch Normalization在卷积神经网络中的使用,包括训练和测试阶段。在训练阶段,使用BN层对数据进行归一化,可以加速网络的收敛,提高模型的泛化能力。在测试阶段,使用BN层对测试数据进行归一化,可以提高模型对数据的敏感性,从而更好地评估模型的性能。
MachineLP
2018/01/09
2.8K0
Tensorflow BN详解:4_使用tf.nn.batch_normalization实现BN
Evacloud 参考文献吴恩达deeplearningai课程课程笔记Udacity课程 """ 大多数情况下,您将能够使用高级功能,但有时您可能想要在较低的级别工作。例如,如果您想要实现一个新特性—一些新的内容,那么TensorFlow还没有包括它的高级实现, 比如LSTM中的批处理规范化——那么您可能需要知道一些事情。 这个版本的网络的几乎所有函数都使用tf.nn包进行编写,并且使用tf.nn.batch_normalization函数进行标准化操作 'fully_connected'函数的
演化计算与人工智能
2020/08/14
2K0
TensorFlow_Tutorial_v3b——improving NN performance测验
Welcome to this week's programming assignment. Until now, you've always used numpy to build neural networks. Now we will step you through a deep learning framework that will allow you to build neural networks more easily. Machine learning frameworks like TensorFlow, PaddlePaddle, Torch, Caffe, Keras, and many others can speed up your machine learning development significantly. All of these frameworks also have a lot of documentation, which you should feel free to read. In this assignment, you will learn to do the following in TensorFlow:
列夫托尔斯昊
2020/08/25
1.4K0
TensorFlow_Tutorial_v3b——improving NN performance测验
深度残差网络(ResNet)论文学习(附代码实现)
本文结合50层深度残差网络的实现学习何博士的大作-Deep Residual Learning for Image Recognition。理论上,深层网络结构包含了浅层网络结构所有可能的解空间,但是实际网络训练中,随着网络深度的增加,网络的准确度出现饱和,甚至下降的现象,这个现象可以在下图直观看出来:56层的网络比20层网络效果还要差。但是这种退化并不是因为过拟合导致的,因为56层的神经网络的训练误差同样高。
YoungTimes
2022/04/28
7970
深度残差网络(ResNet)论文学习(附代码实现)
深度学习解决手写数字的图片识别
本篇使用TensorFlow框架,利用MNIST手写数字数据集来演示深度学习的入门概念。其训练集共有60000个样本(图片和标签),测试集有10000个样本。手写数字的图片都是尺寸为28*28的二值图:
用户6021899
2019/11/07
1.9K0
深度学习解决手写数字的图片识别
Batch Normalization怎么加入batch normalization
Batch Normalization 会使你的参数搜索问题变得很容易,使神经网络对超参数的选择更加稳定,超参数的范围会更加庞大,工作效果也很好,也会使你的训练更加容易,甚至是深层网络。
小飞侠xp
2018/08/29
8470
tf.contrib.layers.batch_norm
Adds a Batch Normalization layer from http://arxiv.org/abs/1502.03167
狼啸风云
2019/11/03
2.3K0
Tensorflow使用的预训练的resnet_v2_50,resnet_v2_101,resnet_v2_152等模型预测,训练
本文介绍了如何通过超分辨率网络,针对极低分辨率的人脸图像进行超分辨率重建,并给出了详细的训练、评估方法和代码实现。
MachineLP
2018/01/09
3.4K0
黑猿大叔-译文 | TensorFlow实现Batch Normalization
原文:Implementing Batch Normalization in Tensorflow(https://r2rt.com/implementing-batch-normalization-in-tensorflow.html) 来源:R2RT 译者注:本文基于一个最基础的全连接网络,演示如何构建Batch Norm层、如何训练以及如何正确进行测试,玩转这份示例代码是理解Batch Norm的最好方式。 文中代码可在jupyter notebook环境下运行: nn_withBN.ipy
用户1332428
2018/03/07
1.2K0
黑猿大叔-译文 | TensorFlow实现Batch Normalization
卷积神经网络处理图像识别(三)
下面是测试Batch的总Loss和验证集上的准确率的收敛趋势图。由于我的电脑性能不好,所以我大幅度削减了待训练参数个数。尽管如此,2000轮训练之后,在验证集上5000个图片的预测正确率已达98.3%。如若不削减参数,准确率可达99.4%。
用户6021899
2019/11/25
9110
卷积神经网络处理图像识别(三)
TensorFlow-实战Google深度学习框架 笔记(上)
TensorFlow 是一种采用数据流图(data flow graphs),用于数值计算的开源软件库。在 Tensorflow 中,所有不同的变量和运算都是储存在计算图,所以在我们构建完模型所需要的图之后,还需要打开一个会话(Session)来运行整个计算图 通常使用import tensorflow as tf来载入TensorFlow 在TensorFlow程序中,系统会自动维护一个默认的计算图,通过tf.get_default_graph函数可以获取当前默认的计算图。除了使用默认的计算图,可以使用tf.Graph函数来生成新的计算图,不同计算图上的张量和运算不会共享 在TensorFlow程序中,所有数据都通过张量的形式表示,张量可以简单的理解为多维数组,而张量在TensorFlow中的实现并不是直接采用数组的形式,它只是对TensorFlow中运算结果的引用。即在张量中没有真正保存数字,而是如何得到这些数字的计算过程 如果对变量进行赋值的时候不指定类型,TensorFlow会给出默认的类型,同时在进行运算的时候,不会进行自动类型转换 会话(session)拥有并管理TensorFlow程序运行时的所有资源,所有计算完成之后需要关闭会话来帮助系统回收资源,否则可能会出现资源泄漏问题 一个简单的计算过程:
范中豪
2019/09/10
7030
TensorFlow-实战Google深度学习框架 笔记(上)
TensorFlow修炼之道(2)——变量(Variable)
变量(Variable)是 TensorFlow 中程序处理的共享持久状态的最佳方法。与常量不同的时,常量创建后,值便无法更改,但是变量创建后 可以修改。并且修改后的值在多个Session中都是可以看见的。
abs_zero
2018/04/11
1.3K0
谈谈Tensorflow的Batch Normalization
tensorflow中关于BN(Batch Normalization)的函数主要有两个,分别是: tf.nn.moments tf.nn.batch_normalization 关于这两个函数,官方API中有详细的说明,具体的细节可以点链接查看,关于BN的介绍可以参考这篇论文(https://arxiv.org/abs/1502.03167),我来说说自己的理解。 不得不吐槽一下,tensorflow的官方API很少给例子,太不人性化了,人家numpy做的就比tensorflow强。 对了,moments
用户1332428
2018/03/30
1.4K0
谈谈Tensorflow的Batch Normalization
DeepLab v3_deeplab模型导出
大年初一我居然在更博客。今年过年由于病毒横行,没有串门没有聚餐,整个人闲的没事干。。。医生真是不容易,忙得团团转还有生命危险,新希望他们平安。
全栈程序员站长
2022/11/09
3190
DeepLab v3_deeplab模型导出
TensorFlow指南(三)——深度神经网络(初级)
由于本系列博文主要专注于Tensorflow本身,所以还是老样子不会过多讲解神经网络的理论知识。 可以参阅这篇博文来先理解下神经网络:http://blog.csdn.net/u011239443/article/details/76680704
小爷毛毛_卓寿杰
2019/02/13
4440
使用自己的数据集训练GoogLenet InceptionNet V1 V2 V3模型(TensorFlow)「建议收藏」
【尊重原创,转载请注明出处】https://blog.csdn.net/guyuealian/article/details/81560537
全栈程序员站长
2022/09/21
1.3K0
使用自己的数据集训练GoogLenet InceptionNet V1 V2 V3模型(TensorFlow)「建议收藏」
tensorflow编程: Variables
tf.moving_average_variables tf.global_variables_initializer tf.local_variables_initializer tf.variables_initializer tf.is_variable_initialized tf.report_uninitialized_variables tf.assert_variables_initialized tf.assign tf.assign_add tf.assign_sub
JNingWei
2018/09/28
7800
推荐阅读
相关推荐
tensorflow: bn层
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档