0
点赞
收藏
分享

微信扫一扫

全连接网络基础2模块化搭建神经网络

神经网络八股包括前向传播过程、反向传播过程、反向传播过程中用到的正则化、
指数衰减学习率、滑动平均方法的设置、以及测试模块

前向传播过程(f orward.py )
前向传播过程完成神经网络的搭建,结构如下:

def forward(x, regularizer):
    w=
    b=
    y=
    return y
def get_weight(shape,  regularizer):
def get_bias(shape):

前向传播过程中,需要定义神经网络中的参数 w 和偏置 b,定义由输入到输出的
网络结构。通过定义函数 get_weight()实现对参数 w 的设置,包括参数 w 的形
状和是否正则化的标志。同样,通过定义函数 get_bias()实现对偏置 b 的设置。

√ 反向传播过程(back word.py
反向传播过程完成网络参数的训练,结构如下:

def backward( mnist ):
x =  tf.placeholder(d d type , shape ) )
y_ =  tf.placeholder( dtype , shape ) )
# 定义前向传播函数
y  =  forward( ( ) )
global_step =
loss =
train_step = = tf.train .GradientDescentOptimizer( learning_rate).
        minimize(loss, global_step=global_step)
# 实例化 s sr aver  对象
saver = tf.train.Saver()
with  tf.Session() as sess:
tf.initialize_all_variables().run()
# # 训练模型
for i in range(STEPS):
        sess.run(train_step, feed_dict={x: , y_: })
        if i %  轮数 == 0:
            print
            saver.save( )

反向传播过程中,用tf.placeholder(dtype, shape)函数实现训练样本 x 和样
本标签 y_占位,函数参数 dtype 表示数据的类型,shape 表示数据的形状;y 表
示定义的前向传播函数 forward;loss 表示定义的损失函数,一般为预测值与样
本标签的交叉熵(或均方误差)与正则化损失之和;train_step 表示利用优化算
法 对 模 型 参 数 进 行 优 化 , 常 用 优 化 算 法 GradientDescentOptimizer
AdamOptimizerMomentumOptimizer 算法,在上述代码中使用的 GradientDes
centOptimizer优化算法。接着实例化saver对象,其中利用 tf.initialize_all_variables().run() 函数实例化所有参数模型,利用 sess.run( )函数实
现模型的训练优化过程,并每间隔一定轮数保存一次模型。

√ 正则化、指数衰减学习率、滑动平均方法的设置

① 正则化项 regularization
当在前向传播过程中即 forward.py 文件中,设置正则化参数 regularization
1 时,则表明在反向传播过程中优化模型参数时,需要在损失函数中加入正则化
项。
结构如下:
首先,需要在前向传播过程即 forward.py文件中加入

if regularizer != None: tf.add_to_collection('losses',
tf.contrib.layers.l2_regularizer(regularizer)(w))

其次,需要在反向传播过程即 backword.py 文件中加入


ce  = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y,
labels=tf.argmax(y_, 1))
cem = tf.reduce_mean(ce)
loss = cem + tf.add_n(tf.get_collection('losses'))

其中,tf.nn.sparse_softmax_cross_entropy_with_logits() 表示 softmax()
数与交叉熵一起使用

②指数衰减学习率
在训练模型时,使用指数衰减学习率可以使模型在训练的前期快速收敛接近较优
解,又可以保证模型在训练后期不会有太大波动。
运用指数衰减学习率,需要在反向传播过程即 backword.py 文件中加入 :

learning_rate = tf.train.exponential_decay(
LEARNING_RATE_BASE,
global_step,
LEARNING_RATE_STEP, LEARNING_RATE_DECAY,
staircase=True)

③滑动平均
在模型训练时引入滑动平均可以使模型在测试数据上表现的更加健壮。
需要在反向传播过程即 backword.py 文件中加入 :

ema = tf.train .ExponentialMovingAverage(MOVING_AVERAGE_DECAY,
global_step)
ema_op = ema.apply(tf.trainable_variables())
with tf.control_dependencies([train_step, ema_op]):
    train_op = tf.no_op(name='train')

测试过程( test .py)

当神经网络模型训练完成后,便可用于测试数据集,验证神经网络的性能。结构
如下

首先,制定模型测试函数 test()

def test( mnist ):
with tf.Graph( ).as_default( ) as g:
        # 给 x  y_ 占位
        x = tf.placeholder( dtype, , shape) )
        y_ = tf.placeholder( dtype, , shape) )

        # 前向传播得到预测结果 y 
    y = mnist_forward.forward(x, None ) 
    # 前向传播得到 y 
    # # 实例化可还原滑动平均的 saver
    ema =  tf.train.ExponentialMovingAverage( 滑动衰减率) )
    ema_restore = ema.variables_to_restore()
    saver = tf.train.Saver(ema_restore)

    # 计算正确率

    correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,
    1))
    accuracy = tf.reduce_mean(tf.cast( correct_prediction,
    tf.float32))
    while True:
        with tf.Session() as sess:
        # 加载训练好的模型
        ckpt = tf.train.get_checkpoint_state( 存储路径) )
        # 如果已有 t ckpt  模型则恢复
        if ckpt and ckpt.model_checkpoint_path:
            #  恢复会话
            saver.restore(sess, ckpt.model_checkpoint_path)
            #  恢复轮数
            global_ste = = ckpt.model_checkpoint_path.split
            ('/')[- - 1].split('- - ')[- - 1]
            # 计算准确率
            accuracy_score = sess.run(accuracy, feed_dict=
            {x: 测试数据 , y_: 测试数据标签 })
            # 打印提示
            print("After %s training step(s), test accuracy=
            %g" % (global_step, accuracy_score ))
            # 如果没有模型
        else:
             print('No checkpoint file found') # # 模型不存在 提示
              return

其次,制定 main( () ) 函数

def main():
    # # 加载测试数据集
    mnist = input_data.read_data_sets ("./data/", one_hot=True)
    # # 调用定义好的测试函数 test
    test(mnist)
if __name__ == '__main__':
    main()

通过对测试数据的预测得到准确率,从而判断出训练出的神经网络模型的性能好
坏。当准确率低时,可能原因有模型需要改进,或者是训练数据量太少导致过拟
合。

举报

相关推荐

神经网络基础

0 条评论