1. 程式人生 > >吳裕雄 python 神經網絡——TensorFlow訓練神經網絡:不使用滑動平均

吳裕雄 python 神經網絡——TensorFlow訓練神經網絡:不使用滑動平均

ace depend tutorials stair mini learn variables 生成 with

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

INPUT_NODE = 784     # 輸入節點
OUTPUT_NODE = 10     # 輸出節點
LAYER1_NODE = 500    # 隱藏層數       
                              
BATCH_SIZE = 100     # 每次batch打包的樣本個數        

# 模型相關的參數
LEARNING_RATE_BASE = 0.8      
LEARNING_RATE_DECAY 
= 0.99 REGULARAZTION_RATE = 0.0001 TRAINING_STEPS = 5000 def inference(input_tensor, avg_class, weights1, biases1, weights2, biases2): # 不使用滑動平均類 if avg_class == None: layer1 = tf.nn.relu(tf.matmul(input_tensor, weights1) + biases1) return tf.matmul(layer1, weights2) + biases2
else: # 使用滑動平均類 layer1 = tf.nn.relu(tf.matmul(input_tensor, avg_class.average(weights1)) + avg_class.average(biases1)) return tf.matmul(layer1, avg_class.average(weights2)) + avg_class.average(biases2) def train(mnist): x = tf.placeholder(tf.float32, [None, INPUT_NODE], name=
x-input) y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE], name=y-input) # 生成隱藏層的參數。 weights1 = tf.Variable(tf.truncated_normal([INPUT_NODE, LAYER1_NODE], stddev=0.1)) biases1 = tf.Variable(tf.constant(0.1, shape=[LAYER1_NODE])) # 生成輸出層的參數。 weights2 = tf.Variable(tf.truncated_normal([LAYER1_NODE, OUTPUT_NODE], stddev=0.1)) biases2 = tf.Variable(tf.constant(0.1, shape=[OUTPUT_NODE])) # 計算不含滑動平均類的前向傳播結果 y = inference(x, None, weights1, biases1, weights2, biases2) # 定義訓練輪數及相關的滑動平均類 global_step = tf.Variable(0, trainable=False) # 計算交叉熵及其平均值 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) # 損失函數的計算 regularizer = tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE) regularaztion = regularizer(weights1) + regularizer(weights2) loss = cross_entropy_mean + regularaztion # 設置指數衰減的學習率。 learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, mnist.train.num_examples / BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) # 優化損失函數 train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step) # 反向傳播更新參數 with tf.control_dependencies([train_step]): train_op = tf.no_op(name=train) # 計算正確率 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # 初始化會話,並開始訓練過程。 with tf.Session() as sess: tf.global_variables_initializer().run() validate_feed = {x: mnist.validation.images, y_: mnist.validation.labels} test_feed = {x: mnist.test.images, y_: mnist.test.labels} # 循環的訓練神經網絡。 for i in range(TRAINING_STEPS): if i % 1000 == 0: validate_acc = sess.run(accuracy, feed_dict=validate_feed) print("After %d training step(s), validation accuracy using average model is %g " % (i, validate_acc)) xs,ys=mnist.train.next_batch(BATCH_SIZE) sess.run(train_op,feed_dict={x:xs,y_:ys}) test_acc=sess.run(accuracy,feed_dict=test_feed) print(("After %d training step(s), test accuracy using average model is %g" %(TRAINING_STEPS, test_acc))) def main(argv=None): mnist = input_data.read_data_sets("E:\\MNIST_data\\", one_hot=True) train(mnist) if __name__==__main__: main()

技術分享圖片

吳裕雄 python 神經網絡——TensorFlow訓練神經網絡:不使用滑動平均