import glob import os.path import numpy as np import tensorflow as tf from tensorflow.python.platform import gfile # 原始輸入數據的目錄,這個目錄下有5個子目錄,每一個子目錄底下保存這屬於該 # 類別的全部圖片。 INPUT_DATA = 'F:\\TensorFlowGoogle\\201806-github\\datasets\\flower_photos\\' # 輸出文件地址。咱們將整理後的圖片數據經過numpy的格式保存。 OUTPUT_FILE = 'F:\\shuju\\flower_processed_data.npy' # 測試數據和驗證數據比例。 VALIDATION_PERCENTAGE = 10 TEST_PERCENTAGE = 10 # 讀取數據並將數據分割成訓練數據、驗證數據和測試數據。 def create_image_lists(sess, testing_percentage, validation_percentage): sub_dirs = [x[0] for x in os.walk(INPUT_DATA)] is_root_dir = True # 初始化各個數據集。 training_images = [] training_labels = [] testing_images = [] testing_labels = [] validation_images = [] validation_labels = [] current_label = 0 # 讀取全部的子目錄。 for sub_dir in sub_dirs: if is_root_dir: is_root_dir = False continue # 獲取一個子目錄中全部的圖片文件。 extensions = ['jpg', 'jpeg', 'JPG', 'JPEG'] file_list = [] dir_name = os.path.basename(sub_dir) for extension in extensions: file_glob = os.path.join(INPUT_DATA, dir_name, '*.' + extension) file_list.extend(glob.glob(file_glob)) if not file_list: continue print("processing:", dir_name) i = 0 # 處理圖片數據。 for file_name in file_list: i += 1 # 讀取並解析圖片,將圖片轉化爲299*299以方便inception-v3模型來處理。 image_raw_data = gfile.FastGFile(file_name, 'rb').read() image = tf.image.decode_jpeg(image_raw_data) if image.dtype != tf.float32: image = tf.image.convert_image_dtype(image, dtype=tf.float32) image = tf.image.resize_images(image, [299, 299]) image_value = sess.run(image) # 隨機劃分數據聚。 chance = np.random.randint(100) if chance < validation_percentage: validation_images.append(image_value) validation_labels.append(current_label) elif chance < (testing_percentage + validation_percentage): testing_images.append(image_value) testing_labels.append(current_label) else: training_images.append(image_value) training_labels.append(current_label) if i % 200 == 0: print(i, "images processed.") current_label += 1 # 將訓練數據隨機打亂以得到更好的訓練效果。 state = np.random.get_state() np.random.shuffle(training_images) np.random.set_state(state) np.random.shuffle(training_labels) return np.asarray([training_images, training_labels,validation_images, validation_labels,testing_images, testing_labels]) with tf.Session() as sess: processed_data = create_image_lists(sess, TEST_PERCENTAGE, VALIDATION_PERCENTAGE) # 經過numpy格式保存處理後的數據。 np.save(OUTPUT_FILE, processed_data) import glob import os.path import numpy as np import tensorflow as tf from tensorflow.python.platform import gfile import tensorflow.contrib.slim as slim # 加載經過TensorFlow-Slim定義好的inception_v3模型。 import tensorflow.contrib.slim.python.slim.nets.inception_v3 as inception_v3 # 處理好以後的數據文件。 INPUT_DATA = 'F:\\shuju\\flower_processed_data.npy' # 保存訓練好的模型的路徑。 TRAIN_FILE = 'E:\\train_dir\\model' # 谷歌提供的訓練好的模型文件地址。由於GitHub沒法保存大於100M的文件,因此 # 在運行時須要先自行從Google下載inception_v3.ckpt文件。 CKPT_FILE = 'E:\\inception_v3\\inception_v3.ckpt' # 定義訓練中使用的參數。 LEARNING_RATE = 0.0001 STEPS = 300 BATCH = 32 N_CLASSES = 5 # 不須要從谷歌訓練好的模型中加載的參數。 CHECKPOINT_EXCLUDE_SCOPES = 'InceptionV3/Logits,InceptionV3/AuxLogits' # 須要訓練的網絡層參數明層,在fine-tuning的過程當中就是最後的全聯接層。 TRAINABLE_SCOPES='InceptionV3/Logits,InceptionV3/AuxLogit' def get_tuned_variables(): exclusions = [scope.strip() for scope in CHECKPOINT_EXCLUDE_SCOPES.split(',')] variables_to_restore = [] # 枚舉inception-v3模型中全部的參數,而後判斷是否須要從加載列表中移除。 for var in slim.get_model_variables(): excluded = False for exclusion in exclusions: if var.op.name.startswith(exclusion): excluded = True break if not excluded: variables_to_restore.append(var) return variables_to_restore def get_trainable_variables(): scopes = [scope.strip() for scope in TRAINABLE_SCOPES.split(',')] variables_to_train = [] # 枚舉全部須要訓練的參數前綴,並經過這些前綴找到全部須要訓練的參數。 for scope in scopes: variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope) variables_to_train.extend(variables) return variables_to_train def main(): # 加載預處理好的數據。 processed_data = np.load(INPUT_DATA) training_images = processed_data[0] n_training_example = len(training_images) training_labels = processed_data[1] validation_images = processed_data[2] validation_labels = processed_data[3] testing_images = processed_data[4] testing_labels = processed_data[5] print("%d training examples, %d validation examples and %d testing examples." % (n_training_example, len(validation_labels), len(testing_labels))) # 定義inception-v3的輸入,images爲輸入圖片,labels爲每一張圖片對應的標籤。 images = tf.placeholder(tf.float32, [None, 299, 299, 3], name='input_images') labels = tf.placeholder(tf.int64, [None], name='labels') # 定義inception-v3模型。由於谷歌給出的只有模型參數取值,因此這裏 # 須要在這個代碼中定義inception-v3的模型結構。雖然理論上須要區分訓練和 # 測試中使用到的模型,也就是說在測試時應該使用is_training=False,可是 # 由於預先訓練好的inception-v3模型中使用的batch normalization參數與 # 新的數據會有出入,因此這裏直接使用同一個模型來作測試。 with slim.arg_scope(inception_v3.inception_v3_arg_scope()): logits, _ = inception_v3.inception_v3(images, num_classes=N_CLASSES, is_training=True) trainable_variables = get_trainable_variables() # 定義損失函數和訓練過程。 tf.losses.softmax_cross_entropy(tf.one_hot(labels, N_CLASSES), logits, weights=1.0) total_loss = tf.losses.get_total_loss() train_step = tf.train.RMSPropOptimizer(LEARNING_RATE).minimize(total_loss) # 計算正確率。 with tf.name_scope('evaluation'): correct_prediction = tf.equal(tf.argmax(logits, 1), labels) evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # 定義加載Google訓練好的Inception-v3模型的Saver。 load_fn = slim.assign_from_checkpoint_fn( CKPT_FILE, get_tuned_variables(), ignore_missing_vars=True) # 定義保存新模型的Saver。 saver = tf.train.Saver() with tf.Session() as sess: # 初始化沒有加載進來的變量。 init = tf.global_variables_initializer() sess.run(init) # 加載谷歌已經訓練好的模型。 print('Loading tuned variables from %s' % CKPT_FILE) load_fn(sess) start = 0 end = BATCH for i in range(STEPS): _, loss = sess.run([train_step, total_loss], feed_dict={ images: training_images[start:end], labels: training_labels[start:end]}) if i % 30 == 0 or i + 1 == STEPS: saver.save(sess, TRAIN_FILE, global_step=i) validation_accuracy = sess.run(evaluation_step, feed_dict={images: validation_images, labels: validation_labels}) print('Step %d: Training loss is %.1f Validation accuracy = %.1f%%' % (i, loss, validation_accuracy * 100.0)) start = end if start == n_training_example: start = 0 end = start + BATCH if end > n_training_example: end = n_training_example # 在最後的測試數據上測試正確率。 test_accuracy = sess.run(evaluation_step, feed_dict={ images: testing_images, labels: testing_labels}) print('Final test accuracy = %.1f%%' % (test_accuracy * 100)) if __name__ == '__main__': main()