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'))
train_step = tf.train.GradientDescentOptimizer(learningRate).minimize(loss,global_step=global_step) ema = tf.train.ExponentialMovingAverage(MovingDecay,global_step) ema_op = ema.apply(tf.trainable_variables()) with tf.control_dependencies([train_step,ema_op]): train_op = tf.no_op(name='train') saver = tf.train.Saver()
with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) # 断点续训 ckpt = tf.train.get_checkpoint_state(ModelPath) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess,ckpt.model_checkpoint_path)
for i in range(Steps): xs, ys = mnist.train.next_batch(BatchSize) _, loss_value, step = sess.run([train_op,loss,global_step],feed_dict={x: xs,y_:ys}) if i % 1000 == 0: print "%d steps,loss: %g" %(step,loss_value) saver.save(sess,os.path.join(ModelPath,ModelName),global_step=global_step)
#coding=utf-8 import time import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import mnist_forward import mnist_backward TestSecs = 5
# 测试
def test(mnist): with tf.Graph().as_default() as g: # 定义x,y x = tf.placeholder(tf.float32,[None,mnist_forward.InNode]) y_ = tf.placeholder(tf.float32,[None,mnist_forward.OutNode]) y = mnist_forward.forward(x,None)
#coding=utf-8 import tensorflow as tf import numpy as np from PIL import Image import mnist_backward import mnist_forward
def restore_model(testPicArr): with tf.Graph().as_default() as tg: x = tf.placeholder(tf.float32,[None,mnist_forward.InNode]) y = mnist_forward.forward(x,None) preValue = tf.argmax(y,1)