1. 程式人生 > >[TensorFlow深度學習入門]實戰六·用CNN做Kaggle比賽手寫數字識別準確率99%+

[TensorFlow深度學習入門]實戰六·用CNN做Kaggle比賽手寫數字識別準確率99%+

[TensorFlow深度學習入門]實戰六·用CNN做Kaggle比賽手寫數字識別準確率99%+

參考部落格地址
本部落格採用Lenet5實現,也包含TensorFlow模型引數儲存與載入參考我的博文,實用性比較好。在訓練集準確率99.85%,測試訓練集準確率99%+。

  • 訓練與模型引數儲存

train檔案

import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import pandas as pd
import tensorflow as tf  
from tensorflow.examples.tutorials.
mnist import input_data mnist = input_data.read_data_sets('./1CNN/mnistcnn/data', one_hot=True) #sess = tf.InteractiveSession() #訓練資料 x = tf.placeholder("float", shape=[None, 784],name="x") #訓練標籤資料 y_ = tf.placeholder("float", shape=[None, 10],name="y_") #把x更改為4維張量,第1維代表樣本數量,第2維和第3維代表影象長寬, 第4維代表影象通道數, 1表示灰度
x_image = tf.reshape(x, [-1,28,28,1]) #第一層:卷積層 conv1_weights = tf.get_variable("conv1_weights", [5, 5, 1, 32], initializer=tf.truncated_normal_initializer(stddev=0.1)) #過濾器大小為5*5, 當前層深度為1, 過濾器的深度為32 conv1_biases = tf.get_variable("conv1_biases", [32], initializer=tf.constant_initializer(0.0))
conv1 = tf.nn.conv2d(x_image, conv1_weights, strides=[1, 1, 1, 1], padding='SAME') #移動步長為1, 使用全0填充 relu1 = tf.nn.relu( tf.nn.bias_add(conv1, conv1_biases) ) #啟用函式Relu去線性化 #第二層:最大池化層 #池化層過濾器的大小為2*2, 移動步長為2,使用全0填充 pool1 = tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') #第三層:卷積層 conv2_weights = tf.get_variable("conv2_weights", [5, 5, 32, 64], initializer=tf.truncated_normal_initializer(stddev=0.1)) #過濾器大小為5*5, 當前層深度為32, 過濾器的深度為64 conv2_biases = tf.get_variable("conv2_biases", [64], initializer=tf.constant_initializer(0.0)) conv2 = tf.nn.conv2d(pool1, conv2_weights, strides=[1, 1, 1, 1], padding='SAME') #移動步長為1, 使用全0填充 relu2 = tf.nn.relu( tf.nn.bias_add(conv2, conv2_biases) ) #第四層:最大池化層 #池化層過濾器的大小為2*2, 移動步長為2,使用全0填充 pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') #第五層:全連線層 fc1_weights = tf.get_variable("fc1_weights", [7 * 7 * 64, 1024], initializer=tf.truncated_normal_initializer(stddev=0.1)) #7*7*64=3136把前一層的輸出變成特徵向量 fc1_baises = tf.get_variable("fc1_baises", [1024], initializer=tf.constant_initializer(0.1)) pool2_vector = tf.reshape(pool2, [-1, 7 * 7 * 64]) fc1 = tf.nn.relu(tf.matmul(pool2_vector, fc1_weights) + fc1_baises) #為了減少過擬合,加入Dropout層 keep_prob = tf.placeholder(tf.float32,name="keep_prob") fc1_dropout = tf.nn.dropout(fc1, keep_prob) #第六層:全連線層 fc2_weights = tf.get_variable("fc2_weights", [1024, 10], initializer=tf.truncated_normal_initializer(stddev=0.1)) #神經元節點數1024, 分類節點10 fc2_biases = tf.get_variable("fc2_biases", [10], initializer=tf.constant_initializer(0.1)) fc2 = tf.matmul(fc1_dropout, fc2_weights) + fc2_biases #第七層:輸出層 # softmax y_conv = tf.nn.softmax(fc2,name="y_conv") y_conv_labels = tf.argmax(y_conv,1,name='y_conv_labels') #定義交叉熵損失函式 y_conv = tf.clip_by_value(y_conv,1e-4,1.99) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) #選擇優化器,並讓優化器最小化損失函式/收斂, 反向傳播 train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # tf.argmax()返回的是某一維度上其資料最大所在的索引值,在這裡即代表預測值和真實值 # 判斷預測值y和真實值y_中最大數的索引是否一致,y的值為1-10概率 correct_prediction = tf.equal(y_conv_labels, tf.argmax(y_,1)) # 用平均值來統計測試準確率 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32),name="accuracy") def convert2onehot(data): # covert data to onehot representation return pd.get_dummies(data) file_path = "./1CNN/mnistcnn/datas/train.csv" df_data = pd.read_csv(file_path, sep=",", header="infer") np_data = df_data.values trainx = np_data[:, 1:]/255 trainy = convert2onehot(np_data[:, 0]).values with tf.Session() as sess: #開始訓練 srun = sess.run srun(tf.global_variables_initializer()) saver = tf.train.Saver() for i in range(6001): start_step = i*100 % 42000 stop_step = start_step+100 batch_x, batch_y = trainx[start_step:stop_step], trainy[start_step:stop_step] srun(train_step,feed_dict={x: batch_x, y_: batch_y, keep_prob: 0.5}) #訓練階段使用50%的Dropout if i%100 == 0: train_accuracy = srun(accuracy,feed_dict={x:batch_x, y_: batch_y, keep_prob: 1.0}) #評估階段不使用Dropout print("step %d, training accuracy %f" % (i, train_accuracy)) saver_path = saver.save(sess, "./1CNN/mnistcnn/ckpt/my_model.ckpt",global_step=i) # 將模型儲存到save/model.ckpt檔案 #print("W1:", sess.run(conv1_weights)) # 列印v1、v2的值一會讀取之後對比 #print("W2:", sess.run(conv1_biases)) print("Model saved in file:", saver_path) #在測試資料上測試準確率 print("test accuracy %g" % srun(accuracy,feed_dict={x: trainx, y_: trainy, keep_prob: 1.0})) print("test accuracy %g" % srun(accuracy,feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

執行結果:

...
step 5800, training accuracy 1.000000
step 5900, training accuracy 0.990000
step 6000, training accuracy 1.000000
Model saved in file: ./1CNN/mnistcnn/ckpt/my_model.ckpt-6000
test accuracy 0.998571
test accuracy 0.9958
  • 模型載入與複用

app檔案:

import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import tensorflow as tf
import pandas as pd


file_path = "./1CNN/mnistcnn/datas/test.csv"
df_data = pd.read_csv(file_path, sep=",", header="infer")
np_data = df_data.values
testx = np_data[:, :]/255

file_path1 = "./1CNN/mnistcnn/datas/sample_submission.csv"
df_data1 = pd.read_csv(file_path1, sep=",", header="infer")

print(df_data1.head())
df_data1.drop(labels="Label",axis = 1,inplace=True)
print(df_data1.head())

with tf.Session() as sess:    
    #載入運算圖
    saver = tf.train.import_meta_graph('./1CNN/mnistcnn/ckpt/my_model.ckpt-6000.meta')
    #載入引數
    saver.restore(sess,tf.train.latest_checkpoint('./1CNN/mnistcnn/ckpt'))
    graph = tf.get_default_graph()
    #匯入輸入介面
    x = graph.get_tensor_by_name("x:0")
    #匯入輸出介面
    y_ = graph.get_tensor_by_name("y_:0")

    keep_prob = graph.get_tensor_by_name("keep_prob:0")
    y_conv_labels = graph.get_tensor_by_name("y_conv_labels:0")

    y_conv_labels_val = sess.run(y_conv_labels,{x:testx[:],keep_prob:1.0})

    #進行預測
    print("y: ",y_conv_labels_val[:10])

    df_data1["Label"] = y_conv_labels_val
    print(df_data1.head())
    df_data1.to_csv(file_path1,columns=["ImageId","Label"],index=False)
    print("Ok")

執行結果:

 ImageId  Label
0        1      0
1        2      0
2        3      0
3        4      0
4        5      0
   ImageId
0        1
1        2
2        3
3        4
4        5

y:  [2 0 9 9 3 7 0 3 0 3]
   ImageId  Label
0        1      2
1        2      0
2        3      9
3        4      9
4        5      3
Ok
  • 結果分析

Kaagle平臺結果

Your Best Entry 
You advanced 381 places on the leaderboard!

Your submission scored 0.98928, which is an improvement of your previous score of 0.98142. Great job!

通過這個cnn識別手寫數字實戰,加深了對於cnn的理解與運用能力。
使用TensorFlow模型引數儲存與載入參考我的博文也使得程式碼應用更加靈活高效,條理也更加清晰了,推薦大家使用。