def use(src): x = tf.placeholder(tf.float32, [ None, train_net.IMAGE_SIZE, train_net.IMAGE_SIZE, train_net.NUM_CHANNELS ], name='x-input') img = Image.open(src) #输入图片路径 img_rgb = img.convert("RGB") img_rgb = img.resize((227, 227)) data = img_rgb.getdata() data = np.matrix(data, dtype='float') xs = tf.reshape(data, [1, 227, 227, 3]) y = inference.alex_net(X=x, output=2, dropout=train_net.DROPOUT, regularizer=None) #tf.argmax()返回向量中最大值位置,tf.equal()返回两个向量对应位置比较结果 返回值为布尔类型 rel = tf.argmax(y, 1) variable_averages = tf.train.ExponentialMovingAverage( train_net.MOVING_AVERAGE_DECAY) #加载变量的滑动平均值 saver = tf.train.Saver(variable_averages.variables_to_restore()) # # saver = tf.train.Saver() cls = 'Male' with tf.Session() as sess: #返回模型变量取值的路径 tf.global_variables_initializer().run() ckpt = tf.train.get_checkpoint_state(train_net.MODEL_SAVE_PATH) if ckpt and ckpt.model_checkpoint_path: #ckpt.model_checkpoint_path返回最新的模型变量取值的路径 saver.restore(sess, ckpt.model_checkpoint_path) global_step = ckpt.model_checkpoint_path.split('/')[-1].split( '-')[-1] xs = sess.run(xs) rel = sess.run(rel, feed_dict={x: xs}) if (rel == 1): cls = 'Female' print('result is %s' % (cls)) plt.imshow(img) # 显示图片 plt.axis('on') # 不显示坐标轴 plt.title('%s' % cls) plt.show() else: print('NO checkpoint file found') return
def evaluate(mnist): # with tf.Graph().as_default() as g: # x = tf.placeholder(tf.float32, [None, mnist_inferenceLeNet.INPUT_NODE], name='x-input') x = tf.placeholder(tf.float32, [ None, train_net.IMAGE_SIZE, train_net.IMAGE_SIZE, train_net.NUM_CHANNELS ], name='x-input') y_ = tf.placeholder(tf.float32, [None, train_net.OUTPUT_NODE], name='y-input') reshape_xs = np.reshape( mnist.validation.images, (mnist.validation.num_examples, train_net.IMAGE_SIZE, train_net.IMAGE_SIZE, train_net.NUM_CHANNELS)) validata_feed = {x: reshape_xs, y_: mnist.validation.labels} y, f = inference.alex_net(X=x, output=10, dropout=train_net.DROPOUT, regularizer=None) #tf.argmax()返回向量中最大值位置,tf.equal()返回两个向量对应位置比较结果 返回值为布尔类型 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) #数据类型转换 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # variable_averages = tf.train.ExponentialMovingAverage(train_net.MOVING_AVERAGE_DECAY) # #加载变量的滑动平均值 # saver = tf.train.Saver(variable_averages.variables_to_restore()) #加载保存模型的变量 saver = tf.train.Saver() while True: with tf.Session() as sess: #返回模型变量取值的路径 ckpt = tf.train.get_checkpoint_state(train_net.MODEL_SAVE_PATH) if ckpt and ckpt.model_checkpoint_path: #ckpt.model_checkpoint_path返回最新的模型变量取值的路径 saver.restore(sess, ckpt.model_checkpoint_path) global_step = ckpt.model_checkpoint_path.split('/')[-1].split( '-')[-1] print('前层特征:') print(sess.run(f, feed_dict=validata_feed)) print( 'After %s traing steps validation accuracy is %g' % (global_step, sess.run(accuracy, feed_dict=validata_feed))) else: print('NO checkpoint file found') return time.sleep(EVAL_INTERVAL_SECS)
def evaluate(mnist, i): x = tf.placeholder(tf.float32, [ 1, train_net.IMAGE_SIZE, train_net.IMAGE_SIZE, train_net.NUM_CHANNELS ], name='x-input') y, f = inference.alex_net(X=x, output=10, dropout=train_net.DROPOUT, regularizer=None) result = tf.argmax(y, 1) variable_averages = tf.train.ExponentialMovingAverage( train_net.MOVING_AVERAGE_DECAY) #加载变量的滑动平均值 saver = tf.train.Saver(variable_averages.variables_to_restore()) #加载保存模型的变量 # saver = tf.train.Saver() with tf.Session() as sess: #返回模型变量取值的路径 ckpt = tf.train.get_checkpoint_state(train_net.MODEL_SAVE_PATH) if ckpt and ckpt.model_checkpoint_path: #ckpt.model_checkpoint_path返回最新的模型变量取值的路径 saver.restore(sess, ckpt.model_checkpoint_path) global_step = ckpt.model_checkpoint_path.split('/')[-1].split( '-')[-1] reshape_xs = np.reshape( mnist.test.images[i], (1, train_net.IMAGE_SIZE, train_net.IMAGE_SIZE, train_net.NUM_CHANNELS)) test_feed = {x: reshape_xs} result = sess.run(result, feed_dict=test_feed) print('After %s traing steps test result is %g' % (global_step, result)) print('truly result is %s' % (sess.run(tf.argmax(mnist.test.labels[i])))) else: print('NO checkpoint file found') return
def test(): reader = tf.TFRecordReader() _, serialized_example = reader.read( filename_queue) # return file_name and file features = tf.parse_single_example(serialized_example, features={ 'label': tf.FixedLenFeature([], tf.int64), 'img': tf.FixedLenFeature([], tf.string), 'width': tf.FixedLenFeature([], tf.int64), 'height': tf.FixedLenFeature([], tf.int64), 'channels': tf.FixedLenFeature([], tf.int64) }) # return image and label label = tf.cast(features['label'], tf.float32) # throw label tensor # height = tf.cast(features['height'],tf.int32) height = features['height'] width = tf.cast(features['width'], tf.int32) channels = tf.cast(features['channels'], tf.int32) img = tf.decode_raw(features['img'], tf.uint8) print(type(height)) img = tf.reshape(img, [227, 227, 3]) img_batch, label_batch = tf.train.shuffle_batch([img, label], batch_size=1000, capacity=5173, min_after_dequeue=5172, num_threads=4) x = tf.placeholder(tf.float32, [ None, train_net.IMAGE_SIZE, train_net.IMAGE_SIZE, train_net.NUM_CHANNELS ], name='x-input') y_ = tf.placeholder(tf.int64, [None], name='y-input') # validata_feed = {x: reshape_xs, y_: mnist.validation.labels} y = inference.alex_net(X=x, output=2, dropout=train_net.DROPOUT, regularizer=None) #tf.argmax()返回向量中最大值位置,tf.equal()返回两个向量对应位置比较结果 返回值为布尔类型 correct_prediction = tf.equal(tf.argmax(y, 1), y_) #数据类型转换 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # variable_averages = tf.train.ExponentialMovingAverage(train_net.MOVING_AVERAGE_DECAY) # #加载变量的滑动平均值 # saver = tf.train.Saver(variable_averages.variables_to_restore()) #加载保存模型的变量 saver = tf.train.Saver() with tf.Session() as sess: #返回模型变量取值的路径 tf.global_variables_initializer().run() coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) xs, ys = sess.run([img_batch, label_batch]) ckpt = tf.train.get_checkpoint_state(train_net.MODEL_SAVE_PATH) if ckpt and ckpt.model_checkpoint_path: #ckpt.model_checkpoint_path返回最新的模型变量取值的路径 saver.restore(sess, ckpt.model_checkpoint_path) global_step = ckpt.model_checkpoint_path.split('/')[-1].split( '-')[-1] print('test accuracy is %g' % (sess.run(accuracy, feed_dict={ x: xs, y_: ys }))) else: print('NO checkpoint file found') return
# Parameters learn_rate = 0.001 decay_rate = 0.1 batch_size = 64 display_step = 20 n_classes = training.num_labels # we got mad kanji dropout = 0.8 # Dropout, probability to keep units imagesize = 227 img_channel = 3 x = tf.placeholder(tf.float32, [None, imagesize, imagesize, img_channel]) y = tf.placeholder(tf.float32, [None, n_classes]) keep_prob = tf.placeholder(tf.float32) # dropout (keep probability) pred = inference.alex_net(x, keep_prob, n_classes, imagesize, img_channel) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) global_step = tf.Variable(0, trainable=False) lr = tf.train.exponential_decay(learn_rate, global_step, 1000, decay_rate, staircase=True) optimizer = tf.train.AdamOptimizer(learning_rate=lr).minimize(cost, global_step=global_step) correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) init = tf.initialize_all_variables() saver = tf.train.Saver() tf.add_to_collection("x", x) tf.add_to_collection("y", y) tf.add_to_collection("keep_prob", keep_prob) tf.add_to_collection("pred", pred)
# Parameters learn_rate = 0.001 decay_rate = 0.1 batch_size = 64 display_step = 20 n_classes = training.num_labels # we got mad kanji dropout = 0.8 # Dropout, probability to keep units imagesize = 227 img_channel = 3 x = tf.placeholder(tf.float32, [None, imagesize, imagesize, img_channel]) y = tf.placeholder(tf.float32, [None, n_classes]) keep_prob = tf.placeholder(tf.float32) # dropout (keep probability) pred = inference.alex_net(x, keep_prob, n_classes, imagesize, img_channel) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) global_step = tf.Variable(0, trainable=False) lr = tf.train.exponential_decay(learn_rate, global_step, 1000, decay_rate, staircase=True) optimizer = tf.train.AdamOptimizer(learning_rate=lr).minimize( cost, global_step=global_step) correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) init = tf.initialize_all_variables()
def train(mnist): #定义预输入 x = tf.placeholder(tf.float32, [None, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS], name='x-input') y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE], name='y-input') #定义正则化 regularizer = tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE) #调用神经网计算输出结果 y, _ = inference.alex_net(X=x, output=OUTPUT_NODE, dropout=DROPOUT, regularizer=None) result = tf.argmax(y, 1, name='out') #定义统计训练轮数的全局变量 global_step = tf.Variable(0, trainable=False) #定义滑动平均 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')) loss = cross_entropy_mean #定义学习率变化 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) # train_step = tf.train.MomentumOptimizer(learning_rate,0.9).minimize(loss,global_step=global_step) #同时更新滑动平均和网络参数 with tf.control_dependencies([train_step, variable_averages_op]): train_op = tf.no_op(name='train') saver = tf.train.Saver() with tf.Session() as sess: tf.global_variables_initializer().run() for i in range(TRAINING_STEPS): xs, ys = mnist.train.next_batch(BATCH_SIZE) reshape_xs = np.reshape( xs, (BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS)) _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={ x: reshape_xs, y_: ys }) if i % 100 == 0: print('After %d training steps,loss on training batch is %g' % (step, loss_value)) #保存checkpoint文件 saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step) #保存pb文件 output_graph_def = graph_util.convert_variables_to_constants( sess, sess.graph_def, ['out']) with tf.gfile.GFile('model_pb/combined_model.pb', 'wb') as f: f.write(output_graph_def.SerializeToString())