批量归一化batch_normalization
为了解决在深度神经网络训练初期降低梯度消失/爆炸问题,Sergey loffe和Christian Szegedy提出了使用批量归一化的技术的方案,该技术包括在每一层激活函数之前在模型里加一个操作,简单零中心化和归一化输入,之后再通过每层的两个新参数(一个缩放,另一个移动)缩放和移动结果,话句话说,这个操作让模型学会最佳模型和每层输入的平均值
批量归一化原理
(1)\(\mu_B = \frac{1}{m_B}\sum_{i=1}^{m_B}x^{(i)}\) #经验平均值,评估整个小批量B
(2)\(\theta_B = \frac{1}{m_B}\sum_{i=1}^{m_b}(x^{(i)} - \mu_B)^2\) #评估整个小批量B的方差
(3)\(x_{(i)}^* = \frac{x^{(i)} - \mu_B}{\sqrt{\theta_B^2+\xi}}\)#零中心化和归一化
(4)\(z^{(i)} = \lambda x_{(i)}^* + \beta\)#将输入进行缩放和移动
在测试期间,没有小批量的数据来计算经验平均值和标准方差,所有可以简单地用整个训练集的平均值和标准方差来代替,在训练过程中可以用变动平均值有效计算出来
但是,批量归一化的确也给模型增加了一些复杂度和运行代价,使得神经网络的预测速度变慢,所以如果逆需要快速预测,可能需要在进行批量归一化之前先检查以下ELU+He初始化的表现如何
tf.layers.batch_normalization使用
函数原型
def batch_normalization(inputs,
axis=-1,
momentum=0.99,
epsilon=1e-3,
center=True,
scale=True,
beta_initializer=init_ops.zeros_initializer(),
gamma_initializer=init_ops.ones_initializer(),
moving_mean_initializer=init_ops.zeros_initializer(),
moving_variance_initializer=init_ops.ones_initializer(),
beta_regularizer=None,
gamma_regularizer=None,
beta_constraint=None,
gamma_constraint=None,
training=False,
trainable=True,
name=None,
reuse=None,
renorm=False,
renorm_clipping=None,
renorm_momentum=0.99,
fused=None,
virtual_batch_size=None,
adjustment=None):
使用注意事项
(1)使用batch_normalization需要三步:
a.在卷积层将激活函数设置为None
b.使用batch_normalization
c.使用激活函数激活
例子:
inputs = tf.layers.dense(inputs,self.n_neurons,
kernel_initializer=self.initializer,
name = 'hidden%d'%(layer+1))
if self.batch_normal_momentum:
inputs = tf.layers.batch_normalization(inputs,momentum=self.batch_normal_momentum,train=self._training)
inputs = self.activation(inputs,name = 'hidden%d_out'%(layer+1))
(2)在训练时,将参数training设置为True,在测试时,将training设置为False,同时要特别注意update_ops的使用
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
需要在每次训练时更新,可以使用sess.run(update_ops)
也可以:
with tf.control_dependencies(update_ops):
train_op = tf.train.AdamOptimizer(learning_rate).minimize(loss)
使用mnist数据集进行简单测试
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
mnist = input_data.read_data_sets('MNIST_data',one_hot=True)
x_train,y_train = mnist.train.images,mnist.train.labels
x_test,y_test = mnist.test.images,mnist.test.labels
Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
he_init = tf.contrib.layers.variance_scaling_initializer()
def dnn(inputs,n_hiddens=1,n_neurons=100,initializer=he_init,activation=tf.nn.elu,batch_normalization=None,training=None):
for layer in range(n_hiddens):
inputs = tf.layers.dense(inputs,n_neurons,kernel_initializer=initializer,name = 'hidden%d'%(layer+1))
if batch_normalization is not None:
inputs = tf.layers.batch_normalization(inputs,momentum=batch_normalization,training=training)
inputs = activation(inputs,name = 'hidden%d'%(layer+1))
return inputs
tf.reset_default_graph()
n_inputs = 28*28
n_hidden = 100
n_outputs = 10
X = tf.placeholder(tf.float32,shape=(None,n_inputs),name='X')
Y = tf.placeholder(tf.int32,shape=(None,n_outputs),name='Y')
training = tf.placeholder_with_default(False,shape=(),name='tarining')
dnn_outputs = dnn(X)
logits = tf.layers.dense(dnn_outputs,n_outputs,kernel_initializer = he_init,name='logits')
y_proba = tf.nn.softmax(logits,name='y_proba')
xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y,logits=y_proba)
loss = tf.reduce_mean(xentropy,name='loss')
train_op = tf.train.AdamOptimizer(learning_rate=0.01).minimize(loss)
correct = tf.equal(tf.argmax(Y,1),tf.argmax(y_proba,1))
accuracy = tf.reduce_mean(tf.cast(correct,tf.float32))
epoches = 20
batch_size = 100
np.random.seed(42)
init = tf.global_variables_initializer()
rnd_index = np.random.permutation(len(x_train))
n_batches = len(x_train) // batch_size
with tf.Session() as sess:
sess.run(init)
for epoch in range(epoches):
for batch_index in np.array_split(rnd_index,n_batches):
x_batch,y_batch = x_train[batch_index],y_train[batch_index]
feed_dict = {X:x_batch,Y:y_batch,training:True}
sess.run(train_op,feed_dict=feed_dict)
loss_val,accuracy_val = sess.run([loss,accuracy],feed_dict={X:x_test,Y:y_test,training:False})
print('epoch:{},loss:{},accuracy:{}'.format(epoch,loss_val,accuracy_val))
批量归一化batch_normalization的更多相关文章
- 第十八节,TensorFlow中使用批量归一化(BN)
在深度学习章节里,已经介绍了批量归一化的概念,详情请点击这里:第九节,改善深层神经网络:超参数调试.正则化以优化(下) 神经网络在进行训练时,主要是用来学习数据的分布规律,如果数据的训练部分和测试部分 ...
- TensorFlow——批量归一化操作
批量归一化 在对神经网络的优化方法中,有一种使用十分广泛的方法——批量归一化,使得神经网络的识别准确度得到了极大的提升. 在网络的前向计算过程中,当输出的数据不再同一分布时,可能会使得loss的值非常 ...
- 深度学习面试题21:批量归一化(Batch Normalization,BN)
目录 BN的由来 BN的作用 BN的操作阶段 BN的操作流程 BN可以防止梯度消失吗 为什么归一化后还要放缩和平移 BN在GoogLeNet中的应用 参考资料 BN的由来 BN是由Google于201 ...
- Batch Normalization批量归一化
BN的深度理解:https://www.cnblogs.com/guoyaohua/p/8724433.html BN: BN的意义:在激活函数之前将输入归一化到高斯分布,控制到激活函数的敏感区域,避 ...
- 从头学pytorch(十九):批量归一化batch normalization
批量归一化 论文地址:https://arxiv.org/abs/1502.03167 批量归一化基本上是现在模型的标配了. 说实在的,到今天我也没搞明白batch normalize能够使得模型训练 ...
- 机器学习(ML)十三之批量归一化、RESNET、Densenet
批量归一化 批量归一化(batch normalization)层,它能让较深的神经网络的训练变得更加容易.对图像处理的输入数据做了标准化处理:处理后的任意一个特征在数据集中所有样本上的均值为0.标准 ...
- [ DLPytorch ] 批量归一化与残差网络
批量归一化 通常来说,数据标准化预处理对于浅层模型就足够有效了.随着模型训练的进行,当每层中参数更新时,靠近输出层的输出较难出现剧烈变化.但对深层神经网络来说,即使输入数据已做标准化,训练中模型参数的 ...
- 【python实现卷积神经网络】批量归一化层实现
代码来源:https://github.com/eriklindernoren/ML-From-Scratch 卷积神经网络中卷积层Conv2D(带stride.padding)的具体实现:https ...
- L18 批量归一化和残差网络
批量归一化(BatchNormalization) 对输入的标准化(浅层模型) 处理后的任意一个特征在数据集中所有样本上的均值为0.标准差为1. 标准化处理输入数据使各个特征的分布相近 批量归一化(深 ...
随机推荐
- HDU-4123-树形dp+rmq+尺取
Bob’s Race Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total ...
- JavaScript---js的模块化
js的模块模式被定义为给类提供私有和公共封装的一种方法,也就是我们常说的“模块化”. 怎么实现“模块化”? 通过闭包的原理来实现“模块化” ,具体实现:1.必须有外部的封闭函数,该函数必须至少被调用 ...
- 轮播图插件 SuperSlide2.1滑动门jQuery插件
http://down.admin5.com/demo/code_pop/18/562/ SuperSlide2.1滑动门jQuery插件
- C#学习历程(六)[ref 关键字的使用]
ref 关键字的使用 ref 关键字通过引用(而非值)传递参数. 通过引用传递的效果是,对所调用方法中的参数进行的任何更改都反映在调用方法中. 例如,如果调用方传递本地变量表达式或数组元素访问表达式, ...
- nodejs之log4js日志记录模块简单配置使用
在我的一个node express项目中,使用了log4js来生成日志并且保存到文件里,生成的文件如下: 文件名字叫:access.log 如果在配置log4js的时候允许了同时存在多个备份log文件 ...
- 使用LeakCanary进行内存泄漏追踪
LeakCanary使用 1.在build.gradle 中 dependencies { //添加 debugCompile 'com.squareup.leakcanary:lea ...
- 【这些年】Linux C/C++软件开发用过的工具
这些年一直从事Linux下C/C++软件开发,学习工作中用到了不少开发工具,一直想做个总结,却总是因为这个原因那个原因,未能动笔.趁今天天气凉爽,空气清新,花点儿功夫,做一个小结啦,防止以 ...
- Python中的数据结构 --- 列表(list)
列表(list)是Python中最基本的.最常用的数据结构(相当于C语言中的数组,与C语言不同的是:列表可以存储任意数据类型的数据). 列表中的每一个元素分配一个索引号,且索引的下标是从0开始. ...
- oracle和sql server 比较
Oracle SQLServer 比较 字符数据类型 CHAR CHAR 都是固定长度字符资料但oracle里面最大度为2kb,SQLServer里面最大长度为8kb 变长字符数据类型 ...
- Apache .htaccess文件
今天在将ThinkPHP的URL模式由普通模式(URL_MODE=1)http://localhost/mythinkphp/index.php/Index/user/id/1.html改为重写模式 ...