Tensorflow實踐 mnist手寫數字識別
minst數據集
tensorflow的文檔中就自帶了mnist手寫數字識別的例子,是一個很經典也比較簡單的入門tensorflow的例子,非常值得自己動手親自實踐一下。由於我用的不是tensorflow中自帶的mnist數據集,而是從kaggle的網站下載下來的,數據集有些不太一樣,所以直接按照tensorflow官方文檔上的參數訓練的話還是踩了一些坑,特此記錄。
首先從kaggle網站下載mnist數據集,一份是train.csv,用於訓練,另一份是test.csv 用於測試提交的。
1 importpandas as pd 2 import numpy as np 3 4 train = pd.read_csv("train.csv") 5 test = pd.read_csv("test.csv")
表中的每一行代表一張圖片,label代表這張圖片的數字,其他列是每個像素點的值,不是0就是1,每張圖有 28 * 28 = 784 個像素點。
由於輸出的時候用的是softmax,所以要先對label進行one-hot encode.
all_x = np.array(train_data.iloc[:,1:],dtype=np.float32) all_y = np.array(train_data.iloc[:,0])from sklearn.preprocessing import OneHotEncoder enc = OneHotEncoder() all_y_onehot = enc.fit_transform(all_y.reshape(-1,1)).toarray()
最後為了不用提交能測試模型的效果,將train_data 拆分成用於訓練和用於測試兩部分。
from sklearn.model_selection import train_test_split train_x,test_x,train_y,test_y = train_test_split(all_x,all_y_onehot,test_size=0.1,random_state=0)
感知機模型
先從最簡單的神經網絡模型出發,設計一個只有兩層的神經網絡,網絡的輸入是 784 維的,輸出是10維的。大致可以分成兩步:1. 設計網絡結構 2. 設置優化方法
import tensorflow as tf sess = tf.InteractiveSession() x = tf.placeholder("float",shape=[None,784]) y_ = tf.placeholder("float",shape=[None,10]) W = tf.Variable(tf.zeros((784,10))) b = tf.Variable(tf.zeros((10,))) y = tf.nn.softmax(tf.matmul(x, W) + b) cross_entropy = -tf.reduce_sum(y_*tf.log(y)) train_step = tf.train.GradientDescentOptimizer(1e-2).minimize(cross_entropy) sess.run(tf.global_variables_initializer())
然後就可以開始訓練了
train_size = train_x.shape[0] for i in range(1000): start = i*50 % train_size end = (i+1)*50 % train_size #print(start,end) #print(b.eval()) if start > end: start = 0 batch_x = train_x[start:end] batch_y = train_y[start:end] print(cross_entropy.eval(feed_dict={x:batch_x,y_:batch_y})) sess.run(train_step,feed_dict={x:batch_x,y_:batch_y})
為了查看模型的收斂情況,我把訓練過程中的cross_entropy也打印出來了,但是發生了不幸的情況。
額,第一次叠代完之後交叉熵就變成nan了,可以同時把 b 和 y 的值也打印出來,發現應該是因為步長太大了,所以將步長調小,我將步長調為了1e-7。
嗯,輸出就變正常啦~ 再看一下這個模型的效果。
在測試集上達到了90%的準確率,嗯,還不錯,但是應該可以更好,畢竟kaggle上面的最高準確率都到100%了==,所以接著嘗試用更復雜一些的卷積神經網絡。
卷積神經網絡
def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.0001) 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‘)
#因為要進行卷積操作,所以要將圖片reshape成28*28*1的形狀。
x_image = tf.reshape(x,[-1,28,28,1])
開始設計網絡
#第一層卷積層 + relu正則函數 + 池化層 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) h_pool1 = max_pool_2x2(h_conv1) #第二層卷積層 + relu正則函數 + 池化層 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) h_pool2 = max_pool_2x2(h_conv2) #第一個全連接層 + relu正則函數 + 隨機失活 W_fc1 = weight_variable([7*7*64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) keep_prob = tf.placeholder("float") h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) #第二個全連接層 + softmax輸出 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)
設置優化方法
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")) sess.run(tf.global_variables_initializer())
然後就可以開始訓練啦
train_size = train_x.shape[0] for i in range(1000): start = i*50 % train_size end = (i+1)*50 % train_size if start > end: start = 0 batch_x = train_x[start:end] batch_y = train_y[start:end] if i%20 == 0: print("iter {} : the accuracy is {:.2f}".format(i,accuracy.eval(feed_dict={x:batch_x,y_:batch_y,keep_prob:1.0})), ", the cross_entropy is {:.2f}".format(cross_entropy.eval(feed_dict={x:batch_x,y_:batch_y,keep_prob:1.0}))) sess.run(train_step,feed_dict={x:batch_x,y_:batch_y,keep_prob:0.5})
看一下輸出的結果
最後準確率停留在0.95左右,但是訓練開始的時候交叉熵變化不大,收斂比較慢,所以可以嘗試將步長設大一些,於是將步長改為1e-3
嗯,準確率提升到了98%,還是不錯的。這樣模型就訓練好了,在測試集上預測一下結果並將結果上傳到kaggle。
test_x = np.array(test_data,dtype=np.float32) test_pred_y = y_conv.eval(feed_dict={x:test_x,keep_prob:1.0}) test_pred = np.argmax(test_pred_y,axis=1)
在測試集上的準確率也是98%左右,排名906,差不多是50%的位置,作為一個開始還是不錯的^^.
總結
一, 用tensorflow的三大步驟:1、設計網絡結構 2、設置優化方法 3、叠代進行訓練
二,訓練過程中觀察損失函數的輸出,如果一下子變成nan,可能是優化時的步長太大了,如果多次叠代沒有變化的話可能是步長太小了。
三,多動手,畢竟就算是文檔中的例子,自己運行的時候也不知道會發生什麽[捂臉]
Tensorflow實踐 mnist手寫數字識別