《人工智能实践:Tensorflow笔记》听课笔记20_5.2模块化搭建神经网络八股

附:课程链接

第五讲.全连接网络基础
5.2模块化搭建神经网络八股

由于个人使用Win7系统,并未完全按照课程所讲,以下记录的也基本是我的结合课程做的Windows系统+PyCharm操作。且本人有python基础,故一些操作可能简略。并未完全按照网课。

记住编写代码时,除注释内容外,字符均使用英文格式。

本节目标:搭建神经网络,在MNIST数据集上训练模型,输出手写数字识别准确率。

四、回顾:模块化搭建神经网络八股
前向传播forward.py

#对于前向传播而言,要搭建神经网络
def forward(x,regularizer)
    w = 		#要定义参数w
    b = 		#要定义参数b
    y = 		#要给出推算y的网络结构
    return y

参数w用def get_weight(shape,regularizer): 函数实现;
参数b用get_bias(shape): 函数实现。

反向传播backward.py

#对于反向传播而言,要训练网络参数
def backward(mnist):
    x = tf.placeholder()    #给输入x占位
    y_ = tf.placeholder()   #给y_占位
    y = forward.forward(x,REGULARIZER)  #用forward模块复现前向传播设计的网络结构,计算求得的结果y
    global_step = tf.Variable(0,trainable=False)    #定义轮数计算器
    loss =  #定义损失函数loss
    """
    正则化、指数衰减学习率、滑动平均如果用到,有相关的代码可以插入,这些具体的代码在之后将会给出
    """
    train_step = 	
    实例化saver
    with tf.Session() as sess:
    	初始化
    	for i in range(STEPS):
    		sess.run(train_step,feed_dict = {x: ,y_: })
    		if i%轮数 == 0:
    			print()
    			saver.save()	#保存模型

如果损失函数loss中要加入正则化regularization
需在backward.py文件中定义:

ema = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = y,labels = tf.argmax(y_,1))   #实现softmax和交叉熵的协同使用
cem = tf.reduce_mean(ce)
loss = cem + tf.add_n(tf.get_collection('losses'))  #把参数w的正则化加入到总loss中

在forward.py文件中,定义w时需要加上:

"""
    如果使用正则化(regularizer != None),则把每一个w的正则化计入到总losses
"""
if regularizer != None:tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))

在训练模型时,使用指数衰减学习率可以使模型在训练的前期快速收敛接近较优解,又可以保证模型在训练后期不会有太大波动。
如果使用衰减学习率,在backward.py文件中定义:

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

如果使用滑动平均,在backward.py文件中加入:

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

测试模型准确率时,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
                ckpt = tf.train.get_checkpoint_state(存储路径)
                #如果已有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()

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

你可能感兴趣的:(人工智能)