【Deep Learning】Kersa-yolo3の学習自動化
Keras-yolo3における学習リストを用いた学習の自動化を説明します。学習リストをまとめたリストを読み込ませ、1行ずつ学習を行う仕組みです。
前提として学習リストが作成済で、そのまとめリストが以下のようになります。
学習リスト/水増しデータ/調整データ/通常_上下反転_左右反転_90度回転_270度回転_上下反転左右反転/品種/6_桃/train.txt 学習リスト/水増しデータ/調整データ/通常_上下反転_左右反転_90度回転_270度回転_上下反転左右反転/品種/7_さくらんぼ/train.txt
例のパスは水増しデータ、水増しした元データ、水増し内容、種類または品種か、品種、学習リストの順になっています。
パスの構成は学習の構成に依存します。以下のスクリプトでパスを扱っている箇所を編集する必要があります。
import os, glob, shutil import numpy as np import keras.backend as K from keras.layers import Input, Lambda from keras.models import Model from keras.optimizers import Adam from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping from yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss from yolo3.utils import get_random_data import datetime import matplotlib.pyplot as plt train_list_file = 'train_list.txt' train_list = [] with open(train_list_file, 'r', encoding='UTF-8') as f: line = f.readline() while line: train_list.append(line.replace("\n", "")) line = f.readline() log_path = 'logs' classes_path = 'model_data' #クラスパス anchors_path = 'model_data/yolo_anchors.txt' #これはyolo設定なのでとりあえずデフォルト first_weight = 'model_data/darknet53_weights.h5' def get_classes(classes_path): '''loads the classes''' with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names def get_anchors(anchors_path): '''loads the anchors from a file''' with open(anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] return np.array(anchors).reshape(-1, 2) def create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2, weights_path='model_data/yolo_weights.h5'): '''create the training model''' K.clear_session() # get a new session image_input = Input(shape=(None, None, 3)) h, w = input_shape num_anchors = len(anchors) y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \ num_anchors//3, num_classes+5)) for l in range(3)] model_body = yolo_body(image_input, num_anchors//3, num_classes) print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes)) if load_pretrained: model_body.load_weights(weights_path, by_name=True, skip_mismatch=True) print('Load weights {}.'.format(weights_path)) if freeze_body in [1, 2]: # Freeze darknet53 body or freeze all but 3 output layers. num = (185, len(model_body.layers)-3)[freeze_body-1] for i in range(num): model_body.layers[i].trainable = False print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers))) model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss', arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})( [*model_body.output, *y_true]) model = Model([model_body.input, *y_true], model_loss) return model def create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2, weights_path='model_data/tiny_yolo_weights.h5'): '''create the training model, for Tiny YOLOv3''' K.clear_session() # get a new session image_input = Input(shape=(None, None, 3)) h, w = input_shape num_anchors = len(anchors) y_true = [Input(shape=(h//{0:32, 1:16}[l], w//{0:32, 1:16}[l], \ num_anchors//2, num_classes+5)) for l in range(2)] model_body = tiny_yolo_body(image_input, num_anchors//2, num_classes) print('Create Tiny YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes)) if load_pretrained: model_body.load_weights(weights_path, by_name=True, skip_mismatch=True) print('Load weights {}.'.format(weights_path)) if freeze_body in [1, 2]: # Freeze the darknet body or freeze all but 2 output layers. num = (20, len(model_body.layers)-2)[freeze_body-1] for i in range(num): model_body.layers[i].trainable = False print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers))) model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss', arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.7})( [*model_body.output, *y_true]) model = Model([model_body.input, *y_true], model_loss) return model def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes): '''data generator for fit_generator''' n = len(annotation_lines) i = 0 while True: image_data = [] box_data = [] for b in range(batch_size): if i==0: np.random.shuffle(annotation_lines) image, box = get_random_data(annotation_lines[i], input_shape, random=True) image_data.append(image) box_data.append(box) i = (i+1) % n image_data = np.array(image_data) box_data = np.array(box_data) y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes) yield [image_data, *y_true], np.zeros(batch_size) def data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes): n = len(annotation_lines) if n==0 or batch_size<=0: return None return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes) def save_history(history, path): plt.plot(history.history['loss'],"o-",label="loss") plt.plot(history.history['val_loss'],"o-",label="val_loss") plt.title('model loss') plt.xlabel('epoch') plt.ylabel('loss') plt.legend(loc='lower right') #plt.tight_layout() plt.savefig(os.path.join(path, 'history.png')) plt.show() for train in train_list: """ make log folder """ if not os.path.isfile(train): print("train file does not exist:", train) exit(1) target_type = train.split("/")[-2] if target_type == "種類": classes_file = os.path.join(classes_path, target_type, "class.txt") train_type = train.split("/")[-3] train_source = train.split("/")[-4] log_dir = os.path.join(log_path, train_source, train_type, target_type) else: veriety = train.split("/")[-2] target_type = train.split("/")[-3] train_type = train.split("/")[-4] train_source = train.split("/")[-5] addition = train.split("/")[-6] classes_file = os.path.join(classes_path, target_type, veriety, "class.txt") log_dir = os.path.join(log_path, addition, train_source, train_type, target_type, veriety) if not os.path.isdir(log_dir): os.makedirs(log_dir) print("log folder made:", log_dir) shutil.copyfile(train, os.path.join(log_dir, "train.txt")) print("copy", train, "to", os.path.join(log_dir, "train.txt")) shutil.copyfile(classes_file, os.path.join(log_dir, "class.txt")) print("copy", classes_file, "to", os.path.join(log_dir, "class.txt")) """ training preparetion """ class_names = get_classes(classes_file) num_classes = len(class_names) anchors = get_anchors(anchors_path) # 画像のサイズを416x416とする input_shape = (416,416) # multiple of 32, hw # モデルのインスタンス作成 model = create_model(input_shape, anchors, num_classes, freeze_body=2, weights_path=first_weight) # make sure you know what you freeze logging = TensorBoard(log_dir=log_dir) checkpoint = ModelCheckpoint(os.path.join(log_dir, 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5'), monitor='val_loss', save_weights_only=True, save_best_only=True, period=3) reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1) # ある条件で学習をストップさせる設定 early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1) # 訓練データと検証データに分けるとこ(とりあえずランダムで9:1) val_split = 0.1 with open(train) as f: lines = f.readlines() np.random.seed(10101) np.random.shuffle(lines) np.random.seed(None) num_val = int(len(lines)*val_split) num_train = len(lines) - num_val """ training """ # Train with frozen layers first, to get a stable loss. # Adjust num epochs to your dataset. This step is enough to obtain a not bad model. if True: model.compile(optimizer=Adam(lr=1e-3), loss={ # use custom yolo_loss Lambda layer. 'yolo_loss': lambda y_true, y_pred: y_pred}) batch_size = 8 print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size)) model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes), steps_per_epoch=max(1, num_train//batch_size), validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes), validation_steps=max(1, num_val//batch_size), epochs=10, initial_epoch=0, callbacks=[logging, checkpoint]) model.save_weights(os.path.join(log_dir, 'trained_weights_stage_1.h5')) # Unfreeze and continue training, to fine-tune. # Train longer if the result is not good. if True: for i in range(len(model.layers)): model.layers[i].trainable = True model.compile(optimizer=Adam(lr=1e-4), loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # recompile to apply the change print('Unfreeze all of the layers.') batch_size = 8 # note that more GPU memory is required after unfreezing the body print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size)) history = model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes), steps_per_epoch=max(1, num_train//batch_size), validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes), validation_steps=max(1, num_val//batch_size), epochs=100, initial_epoch=10, callbacks=[logging, checkpoint, reduce_lr, early_stopping]) model.save_weights(os.path.join(log_dir, 'trained_weights_final.h5')) save_history(history, log_dir) # Further training if needed. del model K.clear_session()
最近ネタ切れです。今年はAI学習とAWSを突き進むか悩み物です。資格取得もあり、時間が許すなら他の分野にも手を出したいです。