學習筆記TF016:CNN實現、數據集、TFRecord、載入圖像、模型、訓練、調試
AlexNet(Alex Krizhevsky,ILSVRC2012冠軍)適合做圖像分類。層自左向右、自上向下讀取,關聯層分為一組,高度、寬度減小,深度增加。深度增加減少網路計算量。
訓練模型數據集 Stanford計算機視覺站點Stanford Dogs http://vision.stanford.edu/aditya86/ImageNetDogs/ 。數據下載解壓到模型代碼同一路徑imagenet-dogs目錄下。包含的120種狗圖像。80%訓練,20%測試。產品模型需要預留原始數據交叉驗證。每幅圖像JPEG格式(RGB),尺寸不一。
圖像轉TFRecord文件,有助加速訓練,簡化圖像標籤匹配,圖像分離利用檢查點文件對模型進行不間斷測試。轉換圖像格式把顏色空間轉灰度,圖像修改統一尺寸,標籤除上每幅圖像。訓練前只進行一次預處理,時間較長。
glob.glob 枚舉指定路徑目錄,顯示數據集文件結構。「*」通配符可以實現模糊查找。文件名中8個數字對應ImageNet類別WordNetID。ImageNet網站可用WordNetID查圖像細節: ImageNet Tree View 。
文件名分解為品種和相應的文件名,品種對應文件夾名稱。依據品種對圖像分組。枚舉每個品種圖像,20%圖像劃入測試集。檢查每個品種測試圖像是否至少有全部圖像的18%。目錄和圖像組織到兩個與每個品種相關的字典,包含各品種所有圖像。分類圖像組織到字典中,簡化選擇分類圖像及歸類過程。
預處理階段,依次遍歷所有分類圖像,打開列表中文件。用dataset圖像填充TFRecord文件,把類別包含進去。dataset鍵值對應文件列表標籤。record_location 存儲TFRecord輸出路徑。枚舉dataset,當前索引用於文件劃分,每隔100m幅圖像,訓練樣本信息寫入新的TFRecord文件,加快寫操作進程。無法被TensorFlow識別為JPEG圖像,用try/catch忽略。轉為灰度圖減少計算量和內存佔用。tf.cast把RGB值轉換到[0,1)區間內。標籤按字元串存儲較高效,最好轉換為整數索引或獨熱編碼秩1張量。
打開每幅圖像,轉換為灰度圖,調整尺寸,添加到TFRecord文件。tf.image.resize_images函數把所有圖像調整為相同尺寸,不考慮長寬比,有扭曲。裁剪、邊界填充能保持圖像長寬比。
按照TFRecord文件讀取圖像,每次載入少量圖像及標籤。修改圖像形狀有助訓練和輸出可視化。匹配所有在訓練集目錄下TFRecord文件載入訓練圖像。每個TFRecord文件包含多幅圖像。tf.parse_single_example只從文件提取單個樣本。批運算可同時訓練多幅圖像或單幅圖像,需要足夠系統內存。
圖像轉灰度值為[0,1)浮點類型,匹配convolution2d期望輸入。卷積輸出第1維和最後一維不改變,中間兩維發生變化。tf.contrib.layers.convolution2d創建模型第1層。weights_initializer設置正態隨機值,第一組濾波器填充正態分布隨機數。濾波器設置trainable,信息輸入網路,權值調整,提高模型準確率。
max_pool把輸出降採樣。ksize、strides ([1,2,2,1]),卷積輸出形狀減半。輸出形狀減小,不改變濾波器數量(輸出通道)或圖像批數據尺寸。減少分量,與圖像(濾波器)高度、寬度有關。更多輸出通道,濾波器數量增加,2倍於第一層。多個卷積和池化層減少輸入高度、寬度,增加深度。很多架構,卷積層和池化層超過5層。訓練調試時間更長,能匹配更多更複雜模式。
圖像每個點與輸出神經元建立全連接。softmax,全連接層需要二階張量。第1維區分圖像,第2維輸入張量秩1張量。tf.reshape 指示和使用其餘所有維,-1把最後池化層調整為巨大秩1張量。
池化層展開,網路當前狀態與預測全連接層整合。weights_initializer接收可調用參數,lambda表達式返回截斷正態分布,指定分布標準差。dropout 削減模型中神經元重要性。tf.contrib.layers.fully_connected 輸出前面所有層與訓練中分類的全連接。每個像素與分類關聯。網路每一步將輸入圖像轉化為濾波減小尺寸。濾波器與標籤匹配。減少訓練、測試網路計算量,輸出更具一般性。
訓練數據真實標籤和模型預測結果,輸入到訓練優化器(優化每層權值)計算模型損失。數次迭代,每次提升模型準確率。大部分分類函數(tf.nn.softmax)要求數值類型標籤。每個標籤轉換代表包含所有分類列表索引整數。tf.map_fn 匹配每個標籤並返回類別列表索引。map依據目錄列表創建包含分類列表。tf.map_fn 可用指定函數對數據流圖張量映射,生成僅包含每個標籤在所有類標籤列表索引秩1張量。tf.nn.softmax用索引預測。
調試CNN,觀察濾波器(卷積核)每輪迭代變化。設計良好CNN,第一個卷積層工作,輸入權值被隨機初始化。權值通過圖像激活,激活函數輸出(特徵圖)隨機。特徵圖可視化,輸出外觀與原始圖相似,被施加靜力(static)。靜力由所有權值的隨機激發。經過多輪迭代,權值被調整擬合訓練反饋,濾波器趨於一致。網路收斂,濾波器與圖像不同細小模式類似。tf.image_summary得到訓練後的濾波器和特徵圖簡單視圖。數據流圖圖像概要輸出(image summary output)從整體了解所使用的濾波器和輸入圖像特徵圖。TensorDebugger,迭代中以GIF動畫查看濾波器變化。
文本輸入存儲在SparseTensor,大部分分量為0。CNN使用稠密輸入,每個值都重要,輸入大部分分量非0。
import tensorflow as tfnn import globnn from itertools import groupbynn from collections import defaultdictnn sess = tf.InteractiveSession()nn image_filenames = glob.glob("./imagenet-dogs/n02*/*.jpg")nn image_filenames[0:2]nn training_dataset = defaultdict(list)nn testing_dataset = defaultdict(list)nn image_filename_with_breed = map(lambda filename: (filename.split("/")[2], filename), image_filenames)nn for dog_breed, breed_images in groupby(image_filename_with_breed, lambda x: x[0]):nn for i, breed_image in enumerate(breed_images):nn if i % 5 == 0:nn testing_dataset[dog_breed].append(breed_image[1])nn else:nn training_dataset[dog_breed].append(breed_image[1])nn breed_training_count = len(training_dataset[dog_breed])nn breed_testing_count = len(testing_dataset[dog_breed])nn breed_training_count_float = float(breed_training_count)nn breed_testing_count_float = float(breed_testing_count)nn assert round(breed_testing_count_float / (breed_training_count_float + breed_testing_count_float), 2) > 0.18, "Not enough testing images."nn print "training_dataset testing_dataset END ------------------------------------------------------"nn def write_records_file(dataset, record_location):nn writer = Nonenn current_index = 0nn for breed, images_filenames in dataset.items():nn for image_filename in images_filenames:nn if current_index % 100 == 0:nn if writer:nn writer.close()nn record_filename = "{record_location}-{current_index}.tfrecords".format(nn record_location=record_location,nn current_index=current_index)nn writer = tf.python_io.TFRecordWriter(record_filename)nn print record_filename + "------------------------------------------------------" nn current_index += 1nn image_file = tf.read_file(image_filename)nn try:nn image = tf.image.decode_jpeg(image_file)nn except:nn print(image_filename)nn continuenn grayscale_image = tf.image.rgb_to_grayscale(image)nn resized_image = tf.image.resize_images(grayscale_image, [250, 151])nn image_bytes = sess.run(tf.cast(resized_image, tf.uint8)).tobytes()nn image_label = breed.encode("utf-8")nn example = tf.train.Example(features=tf.train.Features(feature={nn label: tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_label])),nn image: tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_bytes]))nn }))nn writer.write(example.SerializeToString())nn writer.close()nn write_records_file(testing_dataset, "./output/testing-images/testing-image")nn write_records_file(training_dataset, "./output/training-images/training-image")nn print "write_records_file testing_dataset training_dataset END------------------------------------------------------"nn filename_queue = tf.train.string_input_producer(nn tf.train.match_filenames_once("./output/training-images/*.tfrecords"))nn reader = tf.TFRecordReader()nn _, serialized = reader.read(filename_queue)nn features = tf.parse_single_example(nn serialized,nn features={nn label: tf.FixedLenFeature([], tf.string),nn image: tf.FixedLenFeature([], tf.string),nn })nn record_image = tf.decode_raw(features[image], tf.uint8)nn image = tf.reshape(record_image, [250, 151, 1])nn label = tf.cast(features[label], tf.string)nn min_after_dequeue = 10nn batch_size = 3nn capacity = min_after_dequeue + 3 * batch_sizenn image_batch, label_batch = tf.train.shuffle_batch(nn [image, label], batch_size=batch_size, capacity=capacity, min_after_dequeue=min_after_dequeue)nn print "load image from TFRecord END------------------------------------------------------"nn float_image_batch = tf.image.convert_image_dtype(image_batch, tf.float32)nn conv2d_layer_one = tf.contrib.layers.convolution2d(nn float_image_batch,nn num_outputs=32,nn kernel_size=(5,5),nn activation_fn=tf.nn.relu,nn weights_initializer=tf.random_normal,nn stride=(2, 2),nn trainable=True)nn pool_layer_one = tf.nn.max_pool(conv2d_layer_one,nn ksize=[1, 2, 2, 1],nn strides=[1, 2, 2, 1],nn padding=SAME)nn conv2d_layer_one.get_shape(), pool_layer_one.get_shape()nn print "conv2d_layer_one pool_layer_one END------------------------------------------------------"nn conv2d_layer_two = tf.contrib.layers.convolution2d(nn pool_layer_one,nn num_outputs=64,nn kernel_size=(5,5),nn activation_fn=tf.nn.relu,nn weights_initializer=tf.random_normal,nn stride=(1, 1),nn trainable=True)nn pool_layer_two = tf.nn.max_pool(conv2d_layer_two,nn ksize=[1, 2, 2, 1],nn strides=[1, 2, 2, 1],nn padding=SAME)nn conv2d_layer_two.get_shape(), pool_layer_two.get_shape()nn print "conv2d_layer_two pool_layer_two END------------------------------------------------------"nn flattened_layer_two = tf.reshape(nn pool_layer_two,nn [nn batch_size,nn -1nn ])nn flattened_layer_two.get_shape()nn print "flattened_layer_two END------------------------------------------------------"nn hidden_layer_three = tf.contrib.layers.fully_connected(nn flattened_layer_two,nn 512,nn weights_initializer=lambda i, dtype: tf.truncated_normal([38912, 512], stddev=0.1),nn activation_fn=tf.nn.relunn )nn hidden_layer_three = tf.nn.dropout(hidden_layer_three, 0.1)nn final_fully_connected = tf.contrib.layers.fully_connected(nn hidden_layer_three,nn 120,nn weights_initializer=lambda i, dtype: tf.truncated_normal([512, 120], stddev=0.1)nn )nn print "final_fully_connected END------------------------------------------------------"nn labels = list(map(lambda c: c.split("/")[-1], glob.glob("./imagenet-dogs/*")))nn train_labels = tf.map_fn(lambda l: tf.where(tf.equal(labels, l))[0,0:1][0], label_batch, dtype=tf.int64)nn loss = tf.reduce_mean(nn tf.nn.sparse_softmax_cross_entropy_with_logits(nn final_fully_connected, train_labels))nn batch = tf.Variable(0)nn learning_rate = tf.train.exponential_decay(nn 0.01,nn batch * 3,nn 120,nn 0.95,nn staircase=True)nn optimizer = tf.train.AdamOptimizer(nn learning_rate, 0.9).minimize(nn loss, global_step=batch)nn train_prediction = tf.nn.softmax(final_fully_connected)nn print "train_prediction END------------------------------------------------------"nn filename_queue.close(cancel_pending_enqueues=True)nn coord.request_stop()nn coord.join(threads)nn print "END------------------------------------------------------"n
參考資料:
《面向機器智能的TensorFlow實踐》
歡迎加我微信交流:qingxingfengzi
我的微信公眾號:qingxingfengzigz
我老婆張幸清的微信公眾號:qingqingfeifangz
推薦閱讀:
※生成式對抗網路 NIPS 2016 課程 第 0~1 節
※譯文:機器學習的首要條件不是數學而是數據分析
※人工智慧發展簡史
TAG:TensorFlow | 机器学习 | 深度学习DeepLearning |