前提・実現したいこと
参考サイト
このサイトを参考にしてしてYOLOv3で自前のデータを学習させたいと思っています
発生している問題・エラーメッセージ
上記のサイトの「学習の実行」の
(tf114)>python train.py
を実行するとエラーが出ます。
Traceback (most recent call last): File "train.py", line 190, in <module> _main() File "train.py", line 42, in _main with open(annotation_path) as f: FileNotFoundError: [Errno 2] No such file or directory: 'train.txt'
該当のソースコード
python
1""" 2Retrain the YOLO model for your own dataset. 3""" 4 5import numpy as np 6import keras.backend as K 7from keras.layers import Input, Lambda 8from keras.models import Model 9from keras.optimizers import Adam 10from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping 11 12from yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss 13from yolo3.utils import get_random_data 14 15 16def _main(): 17 annotation_path = 'train.txt' 18 log_dir = 'logs/000/' 19 classes_path = 'model_data/voc_classes.txt' 20 anchors_path = 'model_data/yolo_anchors.txt' 21 class_names = get_classes(classes_path) 22 num_classes = len(class_names) 23 anchors = get_anchors(anchors_path) 24 25 input_shape = (416,416) # multiple of 32, hw 26 27 is_tiny_version = len(anchors)==6 # default setting 28 if is_tiny_version: 29 model = create_tiny_model(input_shape, anchors, num_classes, 30 freeze_body=2, weights_path='model_data/tiny_yolo_weights.h5') 31 else: 32 model = create_model(input_shape, anchors, num_classes, 33 freeze_body=2, weights_path='model_data/yolo_weights.h5') # make sure you know what you freeze 34 35 logging = TensorBoard(log_dir=log_dir) 36 checkpoint = ModelCheckpoint(log_dir + 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5', 37 monitor='val_loss', save_weights_only=True, save_best_only=True, period=3) 38 reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1) 39 early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1) 40 41 val_split = 0.1 42 with open(annotation_path) as f: 43 lines = f.readlines() 44 np.random.seed(10101) 45 np.random.shuffle(lines) 46 np.random.seed(None) 47 num_val = int(len(lines)*val_split) 48 num_train = len(lines) - num_val 49 50 # Train with frozen layers first, to get a stable loss. 51 # Adjust num epochs to your dataset. This step is enough to obtain a not bad model. 52 if True: 53 model.compile(optimizer=Adam(lr=1e-3), loss={ 54 # use custom yolo_loss Lambda layer. 55 'yolo_loss': lambda y_true, y_pred: y_pred}) 56 57 batch_size = 32 58 print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size)) 59 model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes), 60 steps_per_epoch=max(1, num_train//batch_size), 61 validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes), 62 validation_steps=max(1, num_val//batch_size), 63 epochs=50, 64 initial_epoch=0, 65 callbacks=[logging, checkpoint]) 66 model.save_weights(log_dir + 'trained_weights_stage_1.h5') 67 68 # Unfreeze and continue training, to fine-tune. 69 # Train longer if the result is not good. 70 if True: 71 for i in range(len(model.layers)): 72 model.layers[i].trainable = True 73 model.compile(optimizer=Adam(lr=1e-4), loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # recompile to apply the change 74 print('Unfreeze all of the layers.') 75 76 batch_size = 32 # note that more GPU memory is required after unfreezing the body 77 print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size)) 78 model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes), 79 steps_per_epoch=max(1, num_train//batch_size), 80 validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes), 81 validation_steps=max(1, num_val//batch_size), 82 epochs=100, 83 initial_epoch=50, 84 callbacks=[logging, checkpoint, reduce_lr, early_stopping]) 85 model.save_weights(log_dir + 'trained_weights_final.h5') 86 87 # Further training if needed. 88 89 90def get_classes(classes_path): 91 '''loads the classes''' 92 with open(classes_path) as f: 93 class_names = f.readlines() 94 class_names = [c.strip() for c in class_names] 95 return class_names 96 97def get_anchors(anchors_path): 98 '''loads the anchors from a file''' 99 with open(anchors_path) as f: 100 anchors = f.readline() 101 anchors = [float(x) for x in anchors.split(',')] 102 return np.array(anchors).reshape(-1, 2) 103 104 105def create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2, 106 weights_path='model_data/yolo_weights.h5'): 107 '''create the training model''' 108 K.clear_session() # get a new session 109 image_input = Input(shape=(None, None, 3)) 110 h, w = input_shape 111 num_anchors = len(anchors) 112 113 y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \ 114 num_anchors//3, num_classes+5)) for l in range(3)] 115 116 model_body = yolo_body(image_input, num_anchors//3, num_classes) 117 print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes)) 118 119 if load_pretrained: 120 model_body.load_weights(weights_path, by_name=True, skip_mismatch=True) 121 print('Load weights {}.'.format(weights_path)) 122 if freeze_body in [1, 2]: 123 # Freeze darknet53 body or freeze all but 3 output layers. 124 num = (185, len(model_body.layers)-3)[freeze_body-1] 125 for i in range(num): model_body.layers[i].trainable = False 126 print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers))) 127 128 model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss', 129 arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})( 130 [*model_body.output, *y_true]) 131 model = Model([model_body.input, *y_true], model_loss) 132 133 return model 134 135def create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2, 136 weights_path='model_data/tiny_yolo_weights.h5'): 137 '''create the training model, for Tiny YOLOv3''' 138 K.clear_session() # get a new session 139 image_input = Input(shape=(None, None, 3)) 140 h, w = input_shape 141 num_anchors = len(anchors) 142 143 y_true = [Input(shape=(h//{0:32, 1:16}[l], w//{0:32, 1:16}[l], \ 144 num_anchors//2, num_classes+5)) for l in range(2)] 145 146 model_body = tiny_yolo_body(image_input, num_anchors//2, num_classes) 147 print('Create Tiny YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes)) 148 149 if load_pretrained: 150 model_body.load_weights(weights_path, by_name=True, skip_mismatch=True) 151 print('Load weights {}.'.format(weights_path)) 152 if freeze_body in [1, 2]: 153 # Freeze the darknet body or freeze all but 2 output layers. 154 num = (20, len(model_body.layers)-2)[freeze_body-1] 155 for i in range(num): model_body.layers[i].trainable = False 156 print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers))) 157 158 model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss', 159 arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.7})( 160 [*model_body.output, *y_true]) 161 model = Model([model_body.input, *y_true], model_loss) 162 163 return model 164 165def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes): 166 '''data generator for fit_generator''' 167 n = len(annotation_lines) 168 i = 0 169 while True: 170 image_data = [] 171 box_data = [] 172 for b in range(batch_size): 173 if i==0: 174 np.random.shuffle(annotation_lines) 175 image, box = get_random_data(annotation_lines[i], input_shape, random=True) 176 image_data.append(image) 177 box_data.append(box) 178 i = (i+1) % n 179 image_data = np.array(image_data) 180 box_data = np.array(box_data) 181 y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes) 182 yield [image_data, *y_true], np.zeros(batch_size) 183 184def data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes): 185 n = len(annotation_lines) 186 if n==0 or batch_size<=0: return None 187 return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes) 188 189if __name__ == '__main__': 190 _main() 191
補足情報(FW/ツールのバージョンなど)
OS:Windows10
anaconda 2019.10
Tensorflow 1.14.0(cpu版)
Keras 2.2.4
回答2件
あなたの回答
tips
プレビュー