tf.train.MonitoredTrainingSession()的使用案例


2019-03-19 22:07:22

本文主要介紹tf.train.MonitoredTrainingSession():在TensorFlow版本1.2.1中有12個參數,但本例中只用到了兩個參數:

checkpoint_dir:用於指定檢查點保存的路徑和文件名
save_checkpoint_secs:用於指定保存檢查點的時間間隔,以秒為單位

 

# -*- coding:utf-8 -*-
from cifar10_pro import cifar10_input import tensorflow as tf import numpy as np def weight_variable(shape): """According to the parameter 'shape' to generate weight""" initial = tf.truncated_normal(shape=shape, stddev=0.1) return tf.Variable(initial_value=initial) def bias_variable(shape): """According to the parameter 'shpae' to create bias""" initial = tf.constant(value=0.1, shape=shape) return tf.Variable(initial_value=initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def avg_pool_6x6(x): return tf.nn.avg_pool(x, ksize=[1, 6, 6, 1], strides=[1, 6, 6, 1], padding='SAME') tf.reset_default_graph() batch_size = 128 data_dir = '/tmp/cifar10_data/cifar-10-batches-bin' # 讀取訓練集 images_train, labels_train = cifar10_input.inputs(eval_data=False, data_dir=data_dir, batch_size=batch_size) # 讀取測試集 images_test, labels_test = cifar10_input.inputs(eval_data=True, data_dir=data_dir, batch_size=batch_size) x = tf.placeholder(shape=[None, 24, 24, 3], dtype=tf.float32) y = tf.placeholder(shape=[None, 10], dtype=tf.float32) x_image = tf.reshape(x, [-1, 24, 24, 3]) # 64個卷積核,輸出64個通道 W_conv1 = weight_variable([5, 5, 3, 64]) b_conv1 = bias_variable([64]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool_1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 64, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool_1, W_conv2) + b_conv2) h_pool_2 = max_pool_2x2(h_conv2) # 降維 W_conv3 = weight_variable([5, 5, 64, 10]) b_conv3 = bias_variable([10]) h_conv3 = tf.nn.relu(conv2d(h_pool_2, W_conv3) + b_conv3) nt_hpool3 = avg_pool_6x6(h_conv3) nt_hpool3_flat = tf.reshape(nt_hpool3, [-1, 10]) y_conv = tf.nn.softmax(nt_hpool3_flat) cross_entropy = -tf.reduce_sum(y * tf.log(y_conv)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float')) # 使用MonitoredTrainingSession()之前,必須定義global_step變量 global_step = tf.train.get_or_create_global_step() checkpoint_step = tf.assign_add(global_step, 1)
# 2秒保存一次檢查點 save_filename
= 'log/checkpoints' sess = tf.train.MonitoredTrainingSession(checkpoint_dir=save_filename, save_checkpoint_secs=2) # MonitoredTrainingSession() 已經初始化了全局變量,所以不需要再初始化全局變量 # tf.global_variables_initializer().run(session=sess)   tf.train.start_queue_runners(sess=sess) print('Start Training...') max_epochs = 15000 # 讀取上次最后一次訓練的步數,i為當前迭代步數 i = sess.run(global_step) while i < max_epochs: image_batch, label_batch = sess.run([images_train, labels_train]) label_b = np.eye(10, dtype=float)[label_batch] train_step.run(feed_dict={x: image_batch, y: label_b}, session=sess) if i % 200 == 0: train_accuracy = accuracy.eval(feed_dict={x: image_batch, y: label_b}, session=sess) print('step: %d, training accuracy: %g' % (i, train_accuracy)) i = sess.run(checkpoint_step) # 訓練結束,測試模型 image_batch_test, label_batch_test = sess.run([images_test, labels_test]) label_b_test = np.eye(10, dtype=float)[label_batch_test] print('Finished! test accuracy %g' % accuracy.eval(feed_dict={x: image_batch_test, y: label_b_test}, session=sess))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM