LeNet-5的实现
1.tf.nn.bias_add
https://blog.csdn.net/chezhai/article/details/75627789?utm_source=blogxgwz2
即两个列维度相同的向量相加
2.
发现你的定义的前向库函数 import导入不进来 好像是带数字的函数名称不行
3.发现自己写的又有问题 loss在第二次输出结果突然变得很大
自己写的:
#author MJY
#mnist_inference.py的基础上改的LeNet-5_inference
# -------------------------------------------------------------------------------------
import tensorflow as tf
#定义初始经验值
INPUT_NODE=784
OUTPUT_NODE=10
IMAGE_SIZE=28
NUM_CHANNELS=1
NUM_LABELS=10
#第一层卷积层的尺寸和深度
CONV1_DEEP=32#三十二个卷积核
CONV1_SIZE=5#5×5的卷积核尺寸
#第二层卷积层的尺寸和深度
CONV2_DEEP=64#六十四个卷积核
CONV2_SIZE=5#5×5的卷积核尺寸
#全连接层的节点个数
FC_SIZE=512
#-------------------------------------------------------------------------------------
#定义前向传播过程 train是新定义的参数 用于区分训练过程和测试过程
#运用了dropout防止过拟合
def inference(input_tensor, train, regularizer):
with tf.variable_scope('layer1-conv1'):
conv1_weights=tf.get_variable(
"weight",[CONV1_SIZE,CONV1_SIZE,NUM_CHANNELS,CONV1_DEEP],
initializer=tf.truncated_normal_initializer(stddev=0.1))
conv1_biases=tf.get_variable(
"bias",[CONV1_DEEP],initializer=tf.constant_initializer(0.0))
#进行卷积,移动的步长为1且用padding
conv1=tf.nn.conv2d(
input_tensor,conv1_weights,strides=[1,1,1,1],padding='SAME')
relu1=tf.nn.relu(tf.nn.bias_add(conv1,conv1_biases))#即两个列维度相同的向量相加
#28*28*32
# -------------------------------------------------------------------------------------
#进行池化,padding且步长2
with tf.variable_scope('layer2-pool1'):
pool1=tf.nn.max_pool(
relu1,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
#14*14*32
# -------------------------------------------------------------------------------------
# 再次卷积 第三层
with tf.variable_scope('layer3-conv2'):
conv2_weights=tf.get_variable(
"weight",[CONV2_SIZE,CONV2_SIZE,CONV1_DEEP,CONV2_DEEP],
initializer=tf.truncated_normal_initializer(stddev=0.1))
conv2_biases=tf.get_variable(
"bias",[CONV2_DEEP],
initializer=tf.constant_initializer(0.0))
# 进行卷积,移动的步长为1且用padding
conv2=tf.nn.conv2d(
pool1,conv2_weights,strides=[1,1,1,1],padding='SAME')
relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases)) # 即两个列维度相同的向量相加
#14*14*64
# -------------------------------------------------------------------------------------
# 进行池化,padding且步长2
with tf.variable_scope('layer4-pool2'):
pool2=tf.nn.max_pool(
relu2,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
#7*7*64
# -------------------------------------------------------------------------------------
#需要把输出的结果拉成向量的形式 因为全链接层的输入为向量
#.get_shape函数可以得到维度而不需要手工计算
#注意虽然7*7*64是三个维度,但是这个函数会给你加一个batch的第一维度
pool_shape=pool2.get_shape().as_list()
#pool_shape[0]即为一个batch中数据的个数
#计算了应该拉成的长度
nodes=pool_shape[1]*pool_shape[2]*pool_shape[3]
#实际拉的动作 拉成一个“有batch的向量”
reshaped=tf.reshape(pool2,[pool_shape[0],nodes])
#1*3136(不算batch的话)
# -------------------------------------------------------------------------------------
#
#输入全连接层的就是reshaped
#声明第五层全连接层的变量并实现前向传播过程
#输入为3136 输出为512(因为FC_SIZE)
#引入dropout防止过拟合
with tf.variable_scope('layer5-fc1'):
fc1_weights=tf.get_variable(
"weight",[nodes,FC_SIZE],
initializer=tf.truncated_normal_initializer(stddev=0.1))
#只有全连接层的权重需要加入正则化
if regularizer != None:
tf.add_to_collection('losses',regularizer(fc1_weights))
fc1_biases=tf.get_variable(
"bias",[FC_SIZE],initializer=tf.constant_initializer(0.0))
fc1=tf.nn.relu(tf.matmul(reshaped,fc1_weights)+fc1_biases)
if train:
fc1=tf.nn.dropout(fc1,0.5)#加入dropout的诡异方式
#1*512
# -------------------------------------------------------------------------------------
##声明第六层全连接层的变量并实现前向传播过程
#这一层的输出通过softmax之后就得到了分类结果
with tf.variable_scope('layer6-fc2'):
fc2_weights = tf.get_variable(
"weight", [FC_SIZE,NUM_LABELS],
initializer=tf.truncated_normal_initializer(stddev=0.1))
# 只有全连接层的权重需要加入正则化
if regularizer != None:
tf.add_to_collection('losses', regularizer(fc2_weights))
fc2_biases = tf.get_variable(
"bias", [NUM_LABELS], initializer=tf.constant_initializer(0.0))
logit=tf.matmul(fc1,fc2_weights)+fc2_biases
return logit
以及
#author MJY
#author MJY
#author MJY
#mnist_train.py的基础上改的lenet_train
#
#所改的内容 只有输入数据的格式
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
#加载mnist_inference.py中定义的常量和前向传播的函数
import lenet_inference
#配置神经网络参数
BATCH_SIZE=100
LEARNING_RATE_BASE=0.8
LEARNING_RATE_DECAY=0.99
REGULARAZTION_RATE=0.0001
TRAINING_STEPS=30000
MOVING_AVERAGE_DECAY=0.99
#模型保存的路径和名称
MODEL_SAVE_PATH="path/"
MODEL_NAME="model.ckpt"
#d定义训练函数
def train(mnist):
#定义输入输出的placeholder这是mnist的输入格式
# x=tf.placeholder(
# tf.float32,[None,mnist_inference.INPUT_NODE],name="x-input")
# y_=tf.placeholder(
# tf.float32, [None, mnist_inference.OUTPUT_NODE], name="y-input")
x=tf.placeholder(tf.float32,[BATCH_SIZE,lenet_inference.IMAGE_SIZE,lenet_inference.IMAGE_SIZE,
lenet_inference.NUM_CHANNELS],name="x-input")
y_ = tf.placeholder(tf.float32, [None, lenet_inference.OUTPUT_NODE], name="y-input")
regularizer=tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE)
#使用mnist_inference.py中定义的前向传播函数
y=lenet_inference.inference(x,train,regularizer)
global_step=tf.Variable(0,trainable=False)#初始化钟表0
#定义损失函数 学习率 滑动平均操作和训练过程
variable_averages=tf.train.ExponentialMovingAverage(
MOVING_AVERAGE_DECAY,global_step)
variable_averages_op=variable_averages.apply(
tf.trainable_variables())#可更新的变量全部更新
cross_entropy=tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=y,labels=tf.argmax(y_,1))
cross_entropy_mean=tf.reduce_mean(cross_entropy)
loss=cross_entropy_mean+tf.add_n(tf.get_collection('losses'))
learning_rate=tf.train.exponential_decay(
LEARNING_RATE_BASE,
global_step,
mnist.train.num_examples / BATCH_SIZE,#存疑这个是怎么来的
LEARNING_RATE_DECAY)
train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)
with tf.control_dependencies([train_step,variable_averages_op]):
train_op=tf.no_op(name='train')#保证train之前参数被刷新
#初始化tensorflow持久化类
saver=tf.train.Saver()
with tf.Session() as sess:
tf.initialize_all_variables().run()
#在训练过程中不再测试模型在验证集上的表现,验证和测试的过程将会有一个独立的程序完成
for i in range(TRAINING_STEPS):
xs,ys = mnist.train.next_batch(BATCH_SIZE)
reshaped_xs=np.reshape(
xs,(BATCH_SIZE,
lenet_inference.IMAGE_SIZE,
lenet_inference.IMAGE_SIZE,
lenet_inference.NUM_CHANNELS))
_,loss_value,step=sess.run([train_op,loss,global_step],feed_dict={x:reshaped_xs,y_:ys})
#每一千轮保存一次模型
if i%1000==0:
#输出当前训练batch上的损失函数大小
print("After %d training steps,loss on training batch is %g" % (step,loss_value))
#保存当前的模型
saver.save(
sess,os.path.join(MODEL_SAVE_PATH,MODEL_NAME),
global_step=global_step)
def main(argv=None):
mnist=input_data.read_data_sets("MNIST_data",one_hot=True)
train(mnist)
if __name__=='__main__':
#tf.app.run()
main()
经长时间检验(巨久) 发现自己的inference没问题
勘误根据https://zhuanlan.zhihu.com/p/31534286
最后发现是
LEARNING_RATE_BASE 设置的太大了
设置为0.8太大了
设置成LEARNING_RATE_BASE = 0.01会好很多
而且一般初始学习率都会很小,书上设置0.8不知道为啥