利用Tensorflow訓練自定義數據


很多正在入門或剛入門TensorFlow機器學習的同學希望能夠通過自己指定圖片源對模型進行訓練,然后識別和分類自己指定的圖片。但是,在TensorFlow官方入門教程中,並無明確給出如何把自定義數據輸入訓練模型的方法。現在,我們就參考官方入門課程《Deep MNIST for Experts》一節的內容(傳送門:https://www.tensorflow.org/get_started/mnist/pros),介紹如何將自定義圖片輸入到TensorFlow的訓練模型。

在《Deep MNISTfor Experts》一節的代碼中,程序將TensorFlow自帶的mnist圖片數據集mnist.train.images作為訓練輸入,將mnist.test.images作為驗證輸入。當學習了該節內容后,我們會驚嘆卷積神經網絡的超高識別率,但對於剛開始學習TensorFlow的同學,內心可能會產生一個問號:如何將mnist數據集替換為自己指定的圖片源?譬如,我要將圖片源改為自己C盤里面的圖片,應該怎么調整代碼?

我們先看下該節課程中涉及到mnist圖片調用的代碼:

 

[python]  view plain  copy
 
  1. from tensorflow.examples.tutorials.mnist import input_data  
  2. mnist = input_data.read_data_sets('MNIST_data', one_hot=True)  
  3. batch = mnist.train.next_batch(50)  
  4. train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})  
  5. train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})  
  6. print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))  

對於剛接觸TensorFlow的同學,要修改上述代碼,可能會較為吃力。我也是經過一番摸索,才成功調用自己的圖片集。

要實現輸入自定義圖片,需要自己先准備好一套圖片集。為節省時間,我們把mnist的手寫體數字集一張一張地解析出來,存放到自己的本地硬盤,保存為bmp格式,然后再把本地硬盤的手寫體圖片一張一張地讀取出來,組成集合,再輸入神經網絡。mnist手寫體數字集的提取方式詳見《如何從TensorFlow的mnist數據集導出手寫體數字圖片》。

將mnist手寫體數字集導出圖片到本地后,就可以仿照以下python代碼,實現自定義圖片的訓練:

 

[python]  view plain  copy
 
  1. #!/usr/bin/python3.5  
  2. # -*- coding: utf-8 -*-    
  3.   
  4. import os  
  5.   
  6. import numpy as np  
  7. import tensorflow as tf  
  8.   
  9. from PIL import Image  
  10.   
  11.   
  12. # 第一次遍歷圖片目錄是為了獲取圖片總數  
  13. input_count = 0  
  14. for i in range(0,10):  
  15.     dir = './custom_images/%s/' % i                 # 這里可以改成你自己的圖片目錄,i為分類標簽  
  16.     for rt, dirs, files in os.walk(dir):  
  17.         for filename in files:  
  18.             input_count += 1  
  19.   
  20. # 定義對應維數和各維長度的數組  
  21. input_images = np.array([[0]*784 for i in range(input_count)])  
  22. input_labels = np.array([[0]*10 for i in range(input_count)])  
  23.   
  24. # 第二次遍歷圖片目錄是為了生成圖片數據和標簽  
  25. index = 0  
  26. for i in range(0,10):  
  27.     dir = './custom_images/%s/' % i                 # 這里可以改成你自己的圖片目錄,i為分類標簽  
  28.     for rt, dirs, files in os.walk(dir):  
  29.         for filename in files:  
  30.             filename = dir + filename  
  31.             img = Image.open(filename)  
  32.             width = img.size[0]  
  33.             height = img.size[1]  
  34.             for h in range(0, height):  
  35.                 for w in range(0, width):  
  36.                     # 通過這樣的處理,使數字的線條變細,有利於提高識別准確率  
  37.                     if img.getpixel((w, h)) > 230:  
  38.                         input_images[index][w+h*width] = 0  
  39.                     else:  
  40.                         input_images[index][w+h*width] = 1  
  41.             input_labels[index][i] = 1  
  42.             index += 1  
  43.   
  44.   
  45. # 定義輸入節點,對應於圖片像素值矩陣集合和圖片標簽(即所代表的數字)  
  46. x = tf.placeholder(tf.float32, shape=[None, 784])  
  47. y_ = tf.placeholder(tf.float32, shape=[None, 10])  
  48.   
  49. x_image = tf.reshape(x, [-1, 28, 28, 1])  
  50.   
  51. # 定義第一個卷積層的variables和ops  
  52. W_conv1 = tf.Variable(tf.truncated_normal([7, 7, 1, 32], stddev=0.1))  
  53. b_conv1 = tf.Variable(tf.constant(0.1, shape=[32]))  
  54.   
  55. L1_conv = tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], padding='SAME')  
  56. L1_relu = tf.nn.relu(L1_conv + b_conv1)  
  57. L1_pool = tf.nn.max_pool(L1_relu, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')  
  58.   
  59. # 定義第二個卷積層的variables和ops  
  60. W_conv2 = tf.Variable(tf.truncated_normal([3, 3, 32, 64], stddev=0.1))  
  61. b_conv2 = tf.Variable(tf.constant(0.1, shape=[64]))  
  62.   
  63. L2_conv = tf.nn.conv2d(L1_pool, W_conv2, strides=[1, 1, 1, 1], padding='SAME')  
  64. L2_relu = tf.nn.relu(L2_conv + b_conv2)  
  65. L2_pool = tf.nn.max_pool(L2_relu, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')  
  66.   
  67.   
  68. # 全連接層  
  69. W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1024], stddev=0.1))  
  70. b_fc1 = tf.Variable(tf.constant(0.1, shape=[1024]))  
  71.   
  72. h_pool2_flat = tf.reshape(L2_pool, [-1, 7*7*64])  
  73. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)  
  74.   
  75.   
  76. # dropout  
  77. keep_prob = tf.placeholder(tf.float32)  
  78. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)  
  79.   
  80.   
  81. # readout層  
  82. W_fc2 = tf.Variable(tf.truncated_normal([1024, 10], stddev=0.1))  
  83. b_fc2 = tf.Variable(tf.constant(0.1, shape=[10]))  
  84.   
  85. y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2  
  86.   
  87. # 定義優化器和訓練op  
  88. cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))  
  89. train_step = tf.train.AdamOptimizer((1e-4)).minimize(cross_entropy)  
  90. correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))  
  91. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
  92.   
  93.   
  94. with tf.Session() as sess:  
  95.     sess.run(tf.global_variables_initializer())  
  96.   
  97.     print ("一共讀取了 %s 個輸入圖像, %s 個標簽" % (input_count, input_count))  
  98.   
  99.     # 設置每次訓練op的輸入個數和迭代次數,這里為了支持任意圖片總數,定義了一個余數remainder,譬如,如果每次訓練op的輸入個數為60,圖片總數為150張,則前面兩次各輸入60張,最后一次輸入30張(余數30)  
  100.     batch_size = 60  
  101.     iterations = 100  
  102.     batches_count = int(input_count / batch_size)  
  103.     remainder = input_count % batch_size  
  104.     print ("數據集分成 %s 批, 前面每批 %s 個數據,最后一批 %s 個數據" % (batches_count+1, batch_size, remainder))  
  105.   
  106.     # 執行訓練迭代  
  107.     for it in range(iterations):  
  108.         # 這里的關鍵是要把輸入數組轉為np.array  
  109.         for n in range(batches_count):  
  110.             train_step.run(feed_dict={x: input_images[n*batch_size:(n+1)*batch_size], y_: input_labels[n*batch_size:(n+1)*batch_size], keep_prob: 0.5})  
  111.         if remainder > 0:  
  112.             start_index = batches_count * batch_size;  
  113.             train_step.run(feed_dict={x: input_images[start_index:input_count-1], y_: input_labels[start_index:input_count-1], keep_prob: 0.5})  
  114.   
  115.         # 每完成五次迭代,判斷准確度是否已達到100%,達到則退出迭代循環  
  116.         iterate_accuracy = 0  
  117.         if it%5 == 0:  
  118.             iterate_accuracy = accuracy.eval(feed_dict={x: input_images, y_: input_labels, keep_prob: 1.0})  
  119.             print ('iteration %d: accuracy %s' % (it, iterate_accuracy))  
  120.             if iterate_accuracy >= 1:  
  121.                 break;  
  122.   
  123.     print ('完成訓練!')  

上述python代碼的執行結果截圖如下:

 

對於上述代碼中與模型構建相關的代碼,請查閱官方《Deep MNIST for Experts》一節的內容進行理解。在本文中,需要重點掌握的是如何將本地圖片源整合成為feed_dict可接受的格式。其中最關鍵的是這兩行:

 

[python]  view plain  copy
 
  1. # 定義對應維數和各維長度的數組  
  2. input_images = np.array([[0]*784 for i in range(input_count)])  
  3. input_labels = np.array([[0]*10 for i in range(input_count)])  

它們對應於feed_dict的兩個placeholder:

 

[python]  view plain  copy
 
  1. x = tf.placeholder(tf.float32, shape=[None, 784])  
  2. y_ = tf.placeholder(tf.float32, shape=[None, 10])  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM