Tensorflow:MINIST手寫體識別
阿新 • • 發佈:2018-11-22
1:設計演算法來訓練模型
對於處理這種多分類任務,通常用Softmax Regression。工作原理就是對每一種類別估計一個概率,然後取概率最大的類別作為模型的輸出結果。
2:定義一個loss function來描述模型對問題的分類精度
對多分類問題通常用cross-entropy作為loss function。loss越小,代表與模型的分類結果與真實值的偏差越小,訓練的目的就是不斷減小loss,直到達到一個全域性最優或區域性最優解。
3:定義一個優化演算法即可開始訓練
採用最常見的隨機梯度下降SGD(Stochastic Gradient Descent),定義好後Tensorflow會自動求導並根據反向傳播進行訓練,在每輪迭代時更新引數來減小loss。
4:全域性初始化
5:迭代的執行訓練
隨機選一部分樣本feed給placeholder,稱為隨機梯度下降。大多數情況下,這比全樣本訓練的收斂速度快很多。
6:對準確率進行評測
對比預測概率最大的和真實樣本類別,相同為true,不同為false。然後由bool值轉換為float值再求平均即為準確率。
# -*- coding: utf-8 -*- from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #1定義函式 def weight_variable(shape): initial = tf.truncated_normal(shape,stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1,shape=shape) return tf.Variable(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') #2定義輸入輸出,佔位符 x = tf.placeholder("float", shape=[None, 28*28]) y_ = tf.placeholder("float", shape=[None, 10]) keep_prob = tf.placeholder(tf.float32) x_image = tf.reshape(x,[-1,28,28,1])#重置成28*28*1 #3搭建網路,定義演算法 w_conv1 = weight_variable([5,5,1,32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image,w_conv1)+b_conv1)#28*28*32 h_pool1 = max_pool_2x2(h_conv1)#14*14*32 w_conv2 = weight_variable([5,5,32,64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1,w_conv2)+b_conv2)#14*14*64 h_pool2 = max_pool_2x2(h_conv2) #7*7*64 w_fc1 = weight_variable([7*7*64,1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])#重置成1行 f_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,w_fc1)+b_fc1)#1*1*1024 h_fc1_drop = tf.nn.dropout(f_fc1,keep_prob) w_fc2 = weight_variable([1024,10]) b_fc2 = bias_variable([10]) y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop,w_fc2)+b_fc2)#1*1*10 #4優化:用Adam cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) #5正確率,初始化所有變數 correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) sess = tf.InteractiveSession() sess.run(tf.initialize_all_variables()) #6訓練 for i in range(2000): batch = mnist.train.next_batch(50) if i%100 == 0: train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0}) print ("step %d, training accuracy %g"%(i, train_accuracy) ) train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) print( "test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images[0:500], y_: mnist.test.labels[0:500], keep_prob: 1.0}))