使用tensorflow训练自己的数据集—定义反向传播
上一篇使用tensorflow训练自己的数据集(二)中制作已经介绍了定义神经网络、接下来就是定义反向传播过程进行训练神经网络了。反向传播过程中使用了滑动平均类和学习率指数下降来优化神经网络。
ps.没有GPU加速训练过程无比慢(五代i7,A卡,DDR3 8G内存)
import tensorflow as tf
import forward
import os
import genertateds
# 定义神经网络相关参数
BACTH_SIZE = 100
LEARNING_RATE_BASE = 0.01
LEARNING_RATE_DECAY = 0.99
REGULARAZTION_RATE = 0.0001
TRAINING_STEPS = 10000
MOVING_AVERAGE_DECAY = 0.99
train_num_examples = 17500
# 模型保存的路径和文件名
MODEL_SAVE_PATH = "LeNet5_model_of_catvsdog/"
MODEL_NAME = "LeNet5_model_of_catvsdog"
# 定义训练过程
def train():
# 定义输入输出的placeholder
x = tf.placeholder(tf.float32, [
BACTH_SIZE,
forward.IMAGE_SIZE,
forward.IMAGE_SIZE,
forward.NUM_CHANNELS])
y_ = tf.placeholder(tf.int32, [None], name='y-input') # label为int类型
y = forward.inference(x,True,REGULARAZTION_RATE) # 训练过程需要使用正则化
global_step = tf.Variable(0, trainable=False) # 记录step、不可训练的变量
# 定义滑动平均类
variable_average = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
variable_average_op = variable_average.apply(tf.trainable_variables())
# 定义损失函数
# cross_entropy_mean = tf.reduce_mean(tf.square(y - y_)) # 使用softmax层时的loss函数
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=y_)
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,
train_num_examples/BACTH_SIZE,
LEARNING_RATE_DECAY,
staircase=True)
# 使用AdamOptimizer优化器、记录step
train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss,global_step=global_step)
# 控制计算流程(自己这么理解的...)
with tf.control_dependencies([train_step, variable_average_op]):
train_op = tf.no_op(name='train')
# 初始化TensorFlow持久化类
saver = tf.train.Saver()
# 读取训练集
image_batch,label_batch = genertateds.get_batch_record(genertateds.train_record_path,100)
with tf.Session() as sess:
# 初始化所有变量
init_op = tf.global_variables_initializer()
sess.run(init_op)
# 断点检查
ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH)
# 有checkpoint的话继续上一次的训练
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess,ckpt.model_checkpoint_path)
# 创建线程
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess,coord)
# 开始训练
for i in range(TRAINING_STEPS):
xs, ys = sess.run([image_batch,label_batch])
_, loss_value, step = sess.run([train_op, loss, global_step],
feed_dict={x:xs,y_:ys})
# 每100轮保存一次模型
if i % 100 == 0:
# 输出当前的训练情况
print("After %d training step(s),loss on training batch is %g." % (step, loss_value))
# 保存当前模型
saver.save(
sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step)
# 关闭线程
coord.request_stop()
coord.join(threads)
def main():
train()
if __name__ == '__main__':
main()
下一篇将介绍计算准确率
如有错误望多多指教~~