1. 程式人生 > >Tensorflow Practice 3-2

Tensorflow Practice 3-2

Tensorflow practice lesson 3-2

 1 import tensorflow as tf
 2 from tensorflow.examples.tutorials.mnist import input_data
 3 
 4 # 載入資料集
 5 mnist = input_data.read_data_sets("MNIST_data", one_hot=True, source_url='http://yann.lecun.com/exdb/mnist/')
 6 
 7 # 定義兩個變數,表示每個批次的大小,在進行演算法訓練的過程中,將會載入一個批次的檔案進行訓練
8 batch_size = 100 9 # 計算批次的數量 10 n_batch = mnist.train.num_examples // batch_size 11 12 # 定義兩個placeholder 13 x = tf.placeholder(tf.float32, [None, 784]) 14 y = tf.placeholder(tf.float32, [None, 10]) 15 16 # 建立一個簡單的神經元網路 17 W = tf.Variable(tf.zeros([784, 10])) 18 b = tf.Variable(tf.zeros([10])) 19 prediction = tf.nn.softmax(tf.matmul(x, W) + b)
20 21 # 二次代價函式 22 loss = tf.reduce_mean(tf.square(y - prediction)) 23 # 使用梯度下降法最小化loss的值 24 train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss) 25 26 # 初始化變數 27 init = tf.global_variables_initializer() 28 29 # 結果存放在一個布林型的列表中 30 # arg_max 返回一維張量中最大值所在的位置 31 correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(prediction, 1))
32 33 # 求準確率 34 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 35 36 # 進行訓練 37 with tf.Session() as sess: 38 sess.run(init) 39 for epoch in range(21): 40 for batch in range(n_batch): 41 batch_xs, batch_ys = mnist.train.next_batch(batch_size) 42 sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys}) 43 acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}) 44 print("Iter " + str(epoch) + ", Test Accuracy " + str(acc))