模型建立完成后,便需要對模型進行訓練。模型建立詳見:https://www.cnblogs.com/monologuesmw/p/12793758.html
代碼解析
下載的源碼集中包含兩個訓練相關的文件:train.py和train_bottleneck.py。train.py 和 train_bottleneck.py確實會有不少的區別
- train.py
1 model = create_model(input_shape, anchors, len(class_names) ) train(model, annotation_path, input_shape, anchors, len(class_names), log_dir)
- train_bottleneck.py
1 model, bottleneck_model, last_layer_model = create_model(input_shape, anchors, num_classes, freeze_body=2, weights_path='model_data/yolo.h5')
從兩個.py文件函數的參數以及輸出來看,train_bottleneck.py中包含模型凍結的部分,即預訓練和微調,更符合YOLOv3訓練的過程。
_main()函數中,設置了一些信息后,直接create_model
1 model, bottleneck_model, last_layer_model = create_model(input_shape, anchors, num_classes, 2 freeze_body=2, weights_path='model_data/yolo.h5') # make sure you know what you freeze
其中,可以看出freeze_body會有設置,也就是后續凍結哪一部分進行訓練。返回的參數除了model以外,還有bottleneck_model和last_layer_model。
該create_model中,除了上述設置的參數,還有一個默認參數load_pretrained=True, 是否導入預訓練模型的參數。
1 def create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2, weights_path='model_data/yolo.h5'):
然后,會像網絡結構介紹的一樣,通過yolo_body生成一個model_body。即生成整個模型的框架。
1 model_body = yolo_body(image_input, num_anchors//3, num_classes)
然后,要開始訓練嘍!
據了解,訓練一共分為兩個階段:
- 第一階段,凍結部分網絡,只訓練底層權重。
- 優化器使用常見的Adam;
- 損失函數,直接使用模型的輸出y_pred,忽略真值y_true;
-
第二階段, 使用第1階段已訓練完成的網絡權重,繼續訓練
- 將全部的權重都設置為可訓練,而在第1階段中,則是凍結部分權重;
- 優化器,仍是Adam,只是學習率有所下降,從1e-3減少至1e-4;
- 損失函數,仍是只使用y_pred,忽略y_true。
先知道訓練分兩個階段,第一個階段有一些不參與訓練,第二階段全部都參與訓練就可以了。
准備工作:
1 model, bottleneck_model, last_layer_model = create_model(input_shape, anchors, num_classes, 2 freeze_body=2, weights_path='model_data/yolo.h5')
- 封凍模型
- 建立了三種模型:model, bottleneck_model, last_layer_model
1. 凍結網絡
- 先導入默認的那個模型參數
- 模型的層數-3(輸出的y1,y2,y3),由於freeze_body設置的是2,所以此處的num = 252-3 = 249層,即除了輸出的3層外,共有249層。
- 讓這249層不參與訓練,trainable = Flase.【下述代碼第7行】
1 if load_pretrained: 2 model_body.load_weights(weights_path, by_name=True, skip_mismatch=True) 3 print('Load weights {}.'.format(weights_path)) 4 if freeze_body in [1, 2]: 5 # Freeze darknet53 body or freeze all but 3 output layers.凍結darknet53或者凍結除3個輸出層外的所有輸出層 6 num = (185, len(model_body.layers)-3)[freeze_body-1] # 這里減了3個輸出層 7 for i in range(num): model_body.layers[i].trainable = False # 此時的num為252-3=249,將這些層的權重不參與訓練 8 print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))
2. 取除輸出的y1,y2,y3三層的另外三層。即246、247、248層的輸出。(249,250,251是y1,y2,y3三層)。用這些層建立了一個bottleneck_mode
1 out1=model_body.layers[246].output 2 out2=model_body.layers[247].output 3 out3=model_body.layers[248].output 4 5 bottleneck_model = Model([model_body.input, *y_true], [out1, out2, out3])
揣測一下,其含義就是除y1,y2, y3輸出層以外其余的模型,即凍結部分的模型。
P.S. A. y_true的是三個尺度的輸出層:
1 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)]
單獨將246,247,248層的輸出 和 249,250,251的層的輸出拿出來,一個作為in, 一個作為out
1 in0 = Input(shape=bottleneck_model.output[0].shape[1:].as_list()) 2 in1 = Input(shape=bottleneck_model.output[1].shape[1:].as_list()) 3 in2 = Input(shape=bottleneck_model.output[2].shape[1:].as_list()) 4 5 last_out0=model_body.layers[249](in0) 6 last_out1=model_body.layers[250](in1) 7 last_out2=model_body.layers[251](in2)
構建了一個246,247,248層為輸入,249,250,251層為輸出的Model,它這里稱之為model_last:
1 model_last=Model(inputs=[in0, in1, in2], outputs=[last_out0, last_out1, last_out2])
揣測一下,model_last就是倒數第二層到倒數第一層的模型
自定義Lambda(這個大Lambda 是Keras.layers里的) 模型損失函數層 ,將任意表達式封裝為layers對象
yolo_loss在損失函數loss篇介紹。詳見:https://www.cnblogs.com/monologuesmw/p/12794584.html
1 model_loss_last =Lambda(yolo_loss, output_shape=(1,), name='yolo_loss', 2 arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})( 3 [*model_last.output, *y_true]) # 后面是輸入,前面是輸出
這里的model_loss_last是最后一層之間的損失層
1 last_layer_model = Model([in0,in1,in2, *y_true], model_loss_last)
last_layer_last是帶損失層的最后一層
1 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])
這里是模型整體的損失層
1 model = Model([model_body.input, *y_true], model_loss)
這里是帶損失層的整體模型
該create_model中,返回的參數有 model, bottleneck_model, last_layer_model
其實,建模的過程中,所有的loss層都是為了給模型添加損失函數。也就是說,過程中生成的各種都是為了三模型model, bottleneck_model, last_layer_model服務的。 只不過這里給model 和last_layer_model添加了其對應的損失層而已。
直接將loss的計算作為一個層綁定在模型上。
1 return model, bottleneck_model, last_layer_model
模型保存設置
- 監視驗證的損失
- 只保存權重
- 只保存最好的
- 每迭代三次檢測一次
1 checkpoint = ModelCheckpoint(log_dir + 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5', 2 monitor='val_loss', save_weights_only=True, save_best_only=True, period=3)
模型訓練設置
- 可視化的展示器
- 當檢測值不發生變化時,停止訓練
1 reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1) 2 early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)
划分訓練集和驗證集
1 val_split = 0.1 2 with open(annotation_path) as f: 3 lines = f.readlines() 4 np.random.seed(10101) 5 np.random.shuffle(lines) 6 np.random.seed(None) 7 num_val = int(len(lines)*val_split) 8 num_train = len(lines) - num_val
第一階段1:
第一階段的訓練是只訓練最后一層,最后一層的訓練需要有前面層的輸出,因此,此處使用predict_ generator方法獲取前面各層的輸出。
- 輸入通過data_generator_wrapper函數生成 ---- 詳見真值篇https://www.cnblogs.com/monologuesmw/p/12794278.html
1 batch_size=8 2 bottlenecks=bottleneck_model.predict_generator(data_generator_wrapper(lines, batch_size, input_shape, anchors, num_classes, random=False, verbose=True), 3 steps=(len(lines)//batch_size)+1, max_queue_size=1) 4 np.savez("bottlenecks.npz", bot0=bottlenecks[0], bot1=bottlenecks[1], bot2=bottlenecks[2])
由於后續訓練的過程中,需要有訓練集和驗證集,所以此處也需要對訓練集和測試集兩種進行預測,獲得輸出。
對bottleneck.npz進行保存。
然后再將其導入進來,獲得了訓練集和驗證集。 將預測后的倒數第二層的輸出作為最后一層訓練的輸入。
1 # load bottleneck features from file 2 dict_bot=np.load("bottlenecks.npz") 3 bottlenecks_train=[dict_bot["bot0"][:num_train], dict_bot["bot1"][:num_train], dict_bot["bot2"][:num_train]] 4 bottlenecks_val=[dict_bot["bot0"][num_train:], dict_bot["bot1"][num_train:], dict_bot["bot2"][num_train:]]
******************"Training last layers with bottleneck features"***************************************
有了輸出以后,便可以訓練最后一層。
通過compile配置訓練的過程,通過fit_generator 進行訓練。
1 # train last layers with fixed bottleneck features 訓練最后一層在bottleneck層固定的基礎上 2 batch_size=8 3 print("Training last layers with bottleneck features") 4 print('with {} samples, val on {} samples and batch size {}.'.format(num_train, num_val, batch_size)) 5 last_layer_model.compile(optimizer='adam', loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # 配置學習過程 6 last_layer_model.fit_generator(bottleneck_generator(lines[:num_train], batch_size, input_shape, anchors, num_classes, bottlenecks_train), 7 steps_per_epoch=max(1, num_train//batch_size), 8 validation_data=bottleneck_generator(lines[num_train:], batch_size, input_shape, anchors, num_classes, bottlenecks_val), 9 validation_steps=max(1, num_val//batch_size), 10 epochs=30, 11 initial_epoch=0, max_queue_size=1) 12 model.save_weights(log_dir + 'trained_weights_stage_0.h5')
從這里可以看出去,bottleneck的輸出確實是模型倒數第二層的輸出(即13*13*1024,26*26*512, 52*52*256)。
此部分中bottleneck_generator生成數據(其實是一個生成器),也會進入get_random_data和preprocess_true_boxes中進行數據的生成。不同的是標志位的設置不同。
1.get_random_data
1 _, box = get_random_data(annotation_lines[i], input_shape, random=False, proc_img=False)
random和proc_image都置位False。
- random置位False:不隨機生成圖片,即僅是等比縮放,所做的dx和dy肯定是在416*416的中部。
- proc_image置位False: 在等比縮放后並沒有將其放在標定的灰片上, 也沒有對數據進行歸一化。
因為其並不需要返回圖片的信息,只需要返回邊框,用於后續真值的生成。這個時候box的信息只是將原標定的框縮放到416*416中。
2. preprocess_true_boxes
1 y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)
y_true的生成並不會有什么區別
這部分訓練的是last_layer_model, 輸入是等比縮放下的圖片和框。下面訓練的是model,雖然249層全部凍結。但輸入的是非等比縮放,並通過數據增強的數據。 個人感覺在訓練不同的模型時,各模型權重應該是一個淺拷貝的關系。即互相之間是有影響的。
第一階段2:
1 model.compile(optimizer=Adam(lr=1e-3), loss={ 2 # use custom yolo_loss Lambda layer. 3 'yolo_loss': lambda y_true, y_pred: y_pred}) 4 batch_size = 16 5 print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size)) 6 model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes), 7 steps_per_epoch=max(1, num_train//batch_size), 8 validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes), 9 validation_steps=max(1, num_val//batch_size), 10 epochs=50, 11 initial_epoch=0, 12 callbacks=[logging, checkpoint]) 13 model.save_weights(log_dir + 'trained_weights_stage_1.h5')
第二階段:
此階段將會打開所有層,全部參與訓練過程。
如果訓練結果不夠好,可以訓練的代數長一些。
1 # Unfreeze and continue training, to fine-tune. 這里是第二階段 2 # Train longer if the result is not good. 3 if True: 4 for i in range(len(model.layers)): 5 model.layers[i].trainable = True # 訓練開關都打開了 這里是第二階段的學習參數 6 model.compile(optimizer=Adam(lr=1e-4), loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # recompile to apply the change 7 print('Unfreeze all of the layers.') 8 9 batch_size = 4 # note that more GPU memory is required after unfreezing the body 10 print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size)) 11 model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes), 12 steps_per_epoch=max(1, num_train//batch_size), 13 validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes), 14 validation_steps=max(1, num_val//batch_size), 15 epochs=100, 16 initial_epoch=50, 17 callbacks=[logging, checkpoint, reduce_lr, early_stopping]) 18 model.save_weights(log_dir + 'trained_weights_final.h5')
過程太多,對每一次的設置進行總結,以便區分: