keras-tensorflow yolo v3 如何實時輸出loss、acc曲線

如果你有以下問題:
1、keras-tensorflow yolo v3 如何實時輸出loss、acc曲線?
3、keras的loss曲線把開頭數據去掉?
4、loss曲線開頭數據太大了,想去掉該如何做?

想加loss曲線,關鍵要使用回調函數。
在訓練函數中找到fit函數或者fit_generator函數,在參數末尾加上回調函數,callbacks=[logs_loss]

我的環境,win10+keras+tensorflow+python3.6+pycharm
爲了不浪費讀者時間,先上張效果圖(圖很多,這個只是loss)
在這裏插入圖片描述

如何加

把這個部分代碼全部加入到train.py函數中去。


class LossHistory(keras.callbacks.Callback):
    # 函數開始時創建盛放loss與acc的容器
    def on_train_begin(self, logs={}):
        self.losses = {'batch': [], 'epoch': []}
        self.accuracy = {'batch': [], 'epoch': []}
        self.val_loss = {'batch': [], 'epoch': []}
        self.val_acc = {'batch': [], 'epoch': []}

    # 按照batch來進行追加數據
    def on_batch_end(self, batch, logs={}):
        # 每一個batch完成後向容器裏面追加loss,acc
        self.losses['batch'].append(logs.get('loss'))
        self.accuracy['batch'].append(logs.get('acc'))
        self.val_loss['batch'].append(logs.get('val_loss'))
        self.val_acc['batch'].append(logs.get('val_acc'))
        # 每五秒按照當前容器裏的值來繪圖
        if int(time.time()) % 5 == 0:
            self.draw_p(self.losses['batch'], 'loss', 'train_batch')
            self.draw_p(self.accuracy['batch'], 'acc', 'train_batch')
            self.draw_p(self.val_loss['batch'], 'loss', 'val_batch')
            self.draw_p(self.val_acc['batch'], 'acc', 'val_batch')

    def on_epoch_end(self, batch, logs={}):
        # 每一個epoch完成後向容器裏面追加loss,acc
        self.losses['epoch'].append(logs.get('loss'))
        self.accuracy['epoch'].append(logs.get('acc'))
        self.val_loss['epoch'].append(logs.get('val_loss'))
        self.val_acc['epoch'].append(logs.get('val_acc'))
        # 每五秒按照當前容器裏的值來繪圖
        if int(time.time()) % 5 == 0:
            self.draw_p(self.losses['epoch'], 'loss', 'train_epoch')
            self.draw_p(self.accuracy['epoch'], 'acc', 'train_epoch')
            self.draw_p(self.val_loss['epoch'], 'loss', 'val_epoch')
            self.draw_p(self.val_acc['epoch'], 'acc', 'val_epoch')

    # 繪圖,這裏把每一種曲線都單獨繪圖,若想把各種曲線繪製在一張圖上的話可修改此方法
    def draw_p(self, lists, label, type):
        plt.figure()
        plt.plot(range(len(lists)), lists, 'r', label=label)
        plt.ylabel(label)
        plt.xlabel(type)
        plt.legend(loc="upper right")
        plt.savefig(type + '_' + label + '.jpg')

    # 由於這裏的繪圖設置的是5s繪製一次,當訓練結束後得到的圖可能不是一個完整的訓練過程(最後一次繪圖結束,有訓練了0-5秒的時間)
    # 所以這裏的方法會在整個訓練結束以後調用
    def end_draw(self):
        self.draw_p(self.losses['batch'], 'loss', 'train_batch')
        self.draw_p(self.accuracy['batch'], 'acc', 'train_batch')
        self.draw_p(self.val_loss['batch'], 'loss', 'val_batch')
        self.draw_p(self.val_acc['batch'], 'acc', 'val_batch')
        self.draw_p(self.losses['epoch'], 'loss', 'train_epoch')
        self.draw_p(self.accuracy['epoch'], 'acc', 'train_epoch')
        self.draw_p(self.val_loss['epoch'], 'loss', 'val_epoch')
        self.draw_p(self.val_acc['epoch'], 'acc', 'val_epoch')


logs_loss = LossHistory()

注意:記得加頭文件,

import keras
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt

然後,在 fit_generator函數,在參數末尾加上回調函數,callbacks=[logs_loss]

    model.fit_generator(data_generator_wrap(lines[:num_train], batch_size, input_shape, anchors, num_classes),
            steps_per_epoch=max(1, num_train//batch_size),
            validation_data=data_generator_wrap(lines[num_train:], batch_size, input_shape, anchors, num_classes),
            validation_steps=max(1, num_val//batch_size),
            epochs=300,
            initial_epoch=0,
            callbacks=[logs_loss])

大功告成,可以在文件夾中看到loss曲線等一系列曲線。
在這裏插入圖片描述

如何把開頭一些太大的loss值不顯示出來?

思路很簡單,只需要設置一下縱座標之範圍,比如我這個只能顯示0-200之間的,如果不知道到底選多大的,可以多寫幾個都輸出。


    def draw_loss_200(self, lists, label, type):
        plt.figure()
        plt.plot(range(len(lists)), lists, 'r', label=label)
        plt.ylim((0, 200))
        plt.ylabel(label)
        plt.xlabel(type)

        plt.legend(loc="upper right")
        plt.savefig(type + '_' + label + '.jpg')

完整代碼見最後一個。

訓練加畫圖完整示例

你可以把這個代碼跑一遍,理解意思。

# import matplotlib.pyplot as plt
#
# history = model.fit(x, y, validation_split=0.25, epochs=50, batch_size=16, verbose=1)
#
# # 繪製訓練 & 驗證的準確率值
# plt.plot(history.history['acc'])
# plt.plot(history.history['val_acc'])
# plt.title('Model accuracy')
# plt.ylabel('Accuracy')
# plt.xlabel('Epoch')
# plt.legend(['Train', 'Test'], loc='upper left')
# plt.show()
#
# # 繪製訓練 & 驗證的損失值
# plt.plot(history.history['loss'])
# plt.plot(history.history['val_loss'])
# plt.title('Model loss')
# plt.ylabel('Loss')
# plt.xlabel('Epoch')
# plt.legend(['Train', 'Test'], loc='upper left')
# plt.show()


# -*- coding: utf-8 -*-
import keras
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt
import time

# 輸入訓練數據 keras接收numpy數組類型的數據
x = np.array([[0, 1, 0],
              [0, 0, 1],
              [1, 3, 2],
              [3, 2, 1]])
y = np.array([0, 0, 1, 1]).T
# 最簡單的序貫模型,序貫模型是多個網絡層的線性堆疊
simple_model = Sequential()
# dense層爲全連接層
# 第一層隱含層爲全連接層 5個神經元 輸入數據的維度爲3
simple_model.add(Dense(5, input_dim=3, activation='relu'))
# 第二個隱含層 4個神經元
simple_model.add(Dense(4, activation='relu'))
# 輸出層爲1個神經元
simple_model.add(Dense(1, activation='sigmoid'))
# 編譯模型,訓練模型之前需要編譯模型
# 編譯模型的三個參數:優化器、損失函數、指標列表
simple_model.compile(optimizer='sgd', loss='mean_squared_error', metrics=['accuracy'])


class LossHistory(keras.callbacks.Callback):
    # 函數開始時創建盛放loss與acc的容器
    def on_train_begin(self, logs={}):
        self.losses = {'batch': [], 'epoch': []}
        self.accuracy = {'batch': [], 'epoch': []}
        self.val_loss = {'batch': [], 'epoch': []}
        self.val_acc = {'batch': [], 'epoch': []}

    # 按照batch來進行追加數據
    def on_batch_end(self, batch, logs={}):
        # 每一個batch完成後向容器裏面追加loss,acc
        self.losses['batch'].append(logs.get('loss'))
        self.accuracy['batch'].append(logs.get('acc'))
        self.val_loss['batch'].append(logs.get('val_loss'))
        self.val_acc['batch'].append(logs.get('val_acc'))
        # 每五秒按照當前容器裏的值來繪圖
        if int(time.time()) % 5 == 0:
            self.draw_p(self.losses['batch'], 'loss', 'train_batch')
            self.draw_p(self.accuracy['batch'], 'acc', 'train_batch')
            self.draw_p(self.val_loss['batch'], 'loss', 'val_batch')
            self.draw_p(self.val_acc['batch'], 'acc', 'val_batch')

    def on_epoch_end(self, batch, logs={}):
        # 每一個epoch完成後向容器裏面追加loss,acc
        self.losses['epoch'].append(logs.get('loss'))
        self.accuracy['epoch'].append(logs.get('acc'))
        self.val_loss['epoch'].append(logs.get('val_loss'))
        self.val_acc['epoch'].append(logs.get('val_acc'))
        # 每五秒按照當前容器裏的值來繪圖
        if int(time.time()) % 5 == 0:
            self.draw_p(self.losses['epoch'], 'loss', 'train_epoch')
            self.draw_p(self.accuracy['epoch'], 'acc', 'train_epoch')
            self.draw_p(self.val_loss['epoch'], 'loss', 'val_epoch')
            self.draw_p(self.val_acc['epoch'], 'acc', 'val_epoch')

    # 繪圖,這裏把每一種曲線都單獨繪圖,若想把各種曲線繪製在一張圖上的話可修改此方法
    def draw_p(self, lists, label, type):
        plt.figure()
        plt.plot(range(len(lists)), lists, 'r', label=label)
        plt.ylabel(label)
        plt.xlabel(type)
        plt.legend(loc="upper right")
        plt.savefig(type + '_' + label + '.jpg')

    # 由於這裏的繪圖設置的是5s繪製一次,當訓練結束後得到的圖可能不是一個完整的訓練過程(最後一次繪圖結束,有訓練了0-5秒的時間)
    # 所以這裏的方法會在整個訓練結束以後調用
    def end_draw(self):
        self.draw_p(self.losses['batch'], 'loss', 'train_batch')
        self.draw_p(self.accuracy['batch'], 'acc', 'train_batch')
        self.draw_p(self.val_loss['batch'], 'loss', 'val_batch')
        self.draw_p(self.val_acc['batch'], 'acc', 'val_batch')
        self.draw_p(self.losses['epoch'], 'loss', 'train_epoch')
        self.draw_p(self.accuracy['epoch'], 'acc', 'train_epoch')
        self.draw_p(self.val_loss['epoch'], 'loss', 'val_epoch')
        self.draw_p(self.val_acc['epoch'], 'acc', 'val_epoch')


logs_loss = LossHistory()

# 訓練網絡 2000次
# Keras以Numpy數組作爲輸入數據和標籤的數據類型。訓練模型一般使用fit函數
simple_model.fit(x, y, epochs=20000, callbacks=[logs_loss])
# 應用模型 進行預測
y_ = simple_model.predict_classes(x[0:1])
print("[0,1,0]的分類結果:" + str(y[0]))

logs_loss.end_draw()

yolo v3的訓練加畫圖完整示例

# coding=gbk
"""
Retrain the YOLO model for your own dataset.
訓練自己模型的程序,運行即可訓練。
"""
import os
import tensorflow as tf
import numpy as np
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping
 
from yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss
from yolo3.utils import get_random_data
import time
#畫loss相關
import keras
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt

# os.environ["CUDA_VISIBLE_DEVICES"] = '0'
# config = tf.ConfigProto()
# config.gpu_options.per_process_gpu_memory_fraction = 0.9
#gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)
class LossHistory(keras.callbacks.Callback):
    # 函數開始時創建盛放loss與acc的容器
    def on_train_begin(self, logs={}):
        self.losses = {'batch': [], 'epoch': []}
        self.accuracy = {'batch': [], 'epoch': []}
        self.val_loss = {'batch': [], 'epoch': []}
        self.val_acc = {'batch': [], 'epoch': []}

    # 按照batch來進行追加數據
    def on_batch_end(self, batch, logs={}):
        # 每一個batch完成後向容器裏面追加loss,acc
        self.losses['batch'].append(logs.get('loss'))
        self.accuracy['batch'].append(logs.get('acc'))
        self.val_loss['batch'].append(logs.get('val_loss'))
        self.val_acc['batch'].append(logs.get('val_acc'))
        # 每五秒按照當前容器裏的值來繪圖
        if int(time.time()) % 5 == 0:
            self.draw_loss(self.losses['batch'], 'loss', 'train_batch')
            self.draw_loss_50(self.losses['batch'], 'loss', 'train_batch_50')
            self.draw_loss_100(self.losses['batch'], 'loss', 'train_batch_100')
            self.draw_loss_200(self.losses['batch'], 'loss', 'train_batch_200')
            self.draw_loss_500(self.losses['batch'], 'loss', 'train_batch_500')
            self.draw_loss_1000(self.losses['batch'], 'loss', 'train_batch_1000')
            self.draw_p(self.accuracy['batch'], 'acc', 'train_batch')
            self.draw_p(self.val_loss['batch'], 'loss', 'val_batch')
            self.draw_p(self.val_acc['batch'], 'acc', 'val_batch')

    def on_epoch_end(self, batch, logs={}):
        # 每一個epoch完成後向容器裏面追加loss,acc
        self.losses['epoch'].append(logs.get('loss'))
        self.accuracy['epoch'].append(logs.get('acc'))
        self.val_loss['epoch'].append(logs.get('val_loss'))
        self.val_acc['epoch'].append(logs.get('val_acc'))
        # 每五秒按照當前容器裏的值來繪圖
        if int(time.time()) % 5 == 0:
            self.draw_loss(self.losses['epoch'], 'loss', 'train_epoch')
            self.draw_loss_50(self.losses['batch'], 'loss', 'train_batch_50')
            self.draw_loss_100(self.losses['batch'], 'loss', 'train_batch_100')
            self.draw_loss_200(self.losses['batch'], 'loss', 'train_batch_200')
            self.draw_loss_500(self.losses['batch'], 'loss', 'train_batch_500')
            self.draw_loss_1000(self.losses['batch'], 'loss', 'train_batch_500')
            self.draw_p(self.accuracy['epoch'], 'acc', 'train_epoch')
            self.draw_p(self.val_loss['epoch'], 'loss', 'val_epoch')
            self.draw_p(self.val_acc['epoch'], 'acc', 'val_epoch')

    # 繪圖,這裏把每一種曲線都單獨繪圖,若想把各種曲線繪製在一張圖上的話可修改此方法
    def draw_p(self, lists, label, type):
        plt.figure()
        plt.plot(range(len(lists)), lists, 'r', label=label)
        #plt.ylim((0, 150))
        plt.ylabel(label)
        plt.xlabel(type)

        plt.legend(loc="upper right")
        plt.savefig(type + '_' + label + '.jpg')

    def draw_loss(self, lists, label, type):
        plt.figure()
        plt.plot(range(len(lists)), lists, 'r', label=label)
        plt.ylim((0, 150))
        plt.ylabel(label)
        plt.xlabel(type)

        plt.legend(loc="upper right")
        plt.savefig(type + '_' + label + '.jpg')

    def draw_loss_50(self, lists, label, type):
        plt.figure()
        plt.plot(range(len(lists)), lists, 'r', label=label)
        plt.ylim((0, 50))
        plt.ylabel(label)
        plt.xlabel(type)

        plt.legend(loc="upper right")
        plt.savefig(type + '_' + label + '.jpg')

    def draw_loss_100(self, lists, label, type):
        plt.figure()
        plt.plot(range(len(lists)), lists, 'r', label=label)
        plt.ylim((0, 100))
        plt.ylabel(label)
        plt.xlabel(type)

        plt.legend(loc="upper right")
        plt.savefig(type + '_' + label + '.jpg')

    # def draw_loss_150(self, lists, label, type):
    #     plt.figure()
    #     plt.plot(range(len(lists)), lists, 'r', label=label)
    #     plt.ylim((0, 150))
    #     plt.ylabel(label)
    #     plt.xlabel(type)
    #
    #     plt.legend(loc="upper right")
    #     plt.savefig(type + '_' + label + '.jpg')

    def draw_loss_200(self, lists, label, type):
        plt.figure()
        plt.plot(range(len(lists)), lists, 'r', label=label)
        plt.ylim((0, 200))
        plt.ylabel(label)
        plt.xlabel(type)

        plt.legend(loc="upper right")
        plt.savefig(type + '_' + label + '.jpg')

    def draw_loss_500(self, lists, label, type):
        plt.figure()
        plt.plot(range(len(lists)), lists, 'r', label=label)
        plt.ylim((0, 500))
        plt.ylabel(label)
        plt.xlabel(type)
        plt.legend(loc="upper right")
        plt.savefig(type + '_' + label + '.jpg')

    def draw_loss_1000(self, lists, label, type):
        plt.figure()
        plt.plot(range(len(lists)), lists, 'r', label=label)
        plt.ylim((0, 1000))
        plt.ylabel(label)
        plt.xlabel(type)
        plt.legend(loc="upper right")
        plt.savefig(type + '_' + label + '.jpg')
    # 由於這裏的繪圖設置的是5s繪製一次,當訓練結束後得到的圖可能不是一個完整的訓練過程(最後一次繪圖結束,有訓練了0-5秒的時間)
    # 所以這裏的方法會在整個訓練結束以後調用
    def end_draw(self):
        self.draw_loss_50(self.losses['batch'], 'loss', 'train_batch_50')
        self.draw_loss_150(self.losses['batch'], 'loss', 'train_batch_50')

        self.draw_loss(self.losses['batch'], 'loss', 'train_batch')
        #self.draw_loss_150(self.losses['batch'], 'loss', 'train_batch_150')
        self.draw_loss_200(self.losses['batch'], 'loss', 'train_batch_200')
        self.draw_loss_500(self.losses['batch'], 'loss', 'train_batch_500')
        self.draw_p(self.accuracy['batch'], 'acc', 'train_batch')
        self.draw_p(self.val_loss['batch'], 'loss', 'val_batch')
        self.draw_p(self.val_acc['batch'], 'acc', 'val_batch')
        self.draw_p(self.losses['epoch'], 'loss', 'train_epoch')
        self.draw_p(self.accuracy['epoch'], 'acc', 'train_epoch')
        self.draw_p(self.val_loss['epoch'], 'loss', 'val_epoch')
        self.draw_p(self.val_acc['epoch'], 'acc', 'val_epoch')


logs_loss = LossHistory()
def _main():
    annotation_path = '2007_train.txt' #訓練數據,txt文件包含了圖片的地址,座標以及類別
    log_dir = 'logs/000/'#模型存放地址。
    classes_path = 'model_data/voc_classes.txt'
    anchors_path = 'model_data/yolo_anchors.txt'
    class_names = get_classes(classes_path)
    anchors = get_anchors(anchors_path)
    input_shape = (416,416) # multiple of 32, hw
    #input_shape = (715, 416)  # multiple of 32, hw
    #input_shape = (128, 128)  # multiple of 32, hw
    model = create_model(input_shape, anchors, len(class_names) )
    train(model, annotation_path, input_shape, anchors, len(class_names), log_dir=log_dir)
 
def train(model, annotation_path, input_shape, anchors, num_classes, log_dir='logs/'):
    model.compile(optimizer='adam', loss={
        'yolo_loss': lambda y_true, y_pred: y_pred})
    logging = TensorBoard(log_dir=log_dir)
    checkpoint = ModelCheckpoint(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=1)
    batch_size = 4
    #batch_size = 4
    val_split = 0.1
    with open(annotation_path) as f:
        lines = f.readlines()
    np.random.shuffle(lines)
    num_val = int(len(lines)*val_split)
    num_train = len(lines) - num_val
    print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))
 
    model.fit_generator(data_generator_wrap(lines[:num_train], batch_size, input_shape, anchors, num_classes),
            steps_per_epoch=max(1, num_train//batch_size),
            validation_data=data_generator_wrap(lines[num_train:], batch_size, input_shape, anchors, num_classes),
            validation_steps=max(1, num_val//batch_size),
            epochs=300,
            initial_epoch=0,
            callbacks=[logs_loss])
    model.save_weights(log_dir + 'trained_weights.h5')
 
def get_classes(classes_path):
    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):
    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=False, freeze_body=False,
            weights_path='model_data/yolo_weights.h5'):
    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:
            # Do not freeze 3 output layers.
            num = len(model_body.layers)-7
            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 data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):
    n = len(annotation_lines)
    np.random.shuffle(annotation_lines)
    i = 0
    while True:
        image_data = []
        box_data = []
        for b in range(batch_size):
            i %= n
            image, box = get_random_data(annotation_lines[i], input_shape, random=True)
            image_data.append(image)
            box_data.append(box)
            i += 1
        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_wrap(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)
 
if __name__ == '__main__':
    _main()
    logs_loss.end_draw()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章