[YOLOv6 は独自のデータ セットを詳細にデプロイおよびトレーニングします (非常に多くの BUG ステッピング レコード)]

序文:

最近、Meituan が公開した YOLOv6 の論文を見て、その速度は 1234FPS に達することができたので、テストをデプロイして独自のデータセットをトレーニングしてみたかったのですが、予想外なことに、公式クローンのソース コードにはバグがたくさんありました。その過程で、他の学者も問題に遭遇しているのを見ましたが、同じバグに悩まされているバグ担当者の中には、明確な解決策を示さなかった人もいました。他の学者の経験と私自身の理解を組み合わせた後、トレーニング、評価、推論を含むモデルの一連の展開を正常に完了しました (フォローアップ TensorRT は高速化され、更新され続けています)。落とし穴の記録。初心者が落とし穴を避けるのに役立つことを期待しています。

モデルのダウンロードと環境の展開

Yolov6 モデル コード: https://github.com/meituan/YOLOv6/tree/0.2.0
Yolov6 論文: https://arxiv.org/abs/2209.02976

環境構成

YOLO シリーズのコードは、必要な機能パッケージの「requirements.txt」ファイルとバージョン情報を提供し、モデルを実行する環境に入り、yolo プロジェクト ディレクトリに移動し、インストール コマンドを実行すると自動的にインストールされます。 「requirements.txt」をインストールする ファイルにリストされている機能パッケージ:

cd YOLOv6
pip install -r requirements.txt

注: 推論に GPU を使用する必要がある場合は、グラフィック カード ドライバー、CUDA、cudnn、およびコンピューターに対応する GPU バージョンの torch を事前にインストールする必要があります。(この部分の操作については別ブログ「GPU版PyTorch詳細インストールチュートリアル」を参照してください)

推理テスト

環境の構成が完了したら、公式の重みを使用して、基本的な環境の展開が正しいかどうかをテストして確認できます。 (公式の重みをダウンロードし、README のパフォーマンス比較表で
目的の重み名をクリックすると、ダウンロードにジャンプします。 )
ここに画像の説明を挿入
テスト手順:

python tools/infer.py --weights yolov6s.pt --source img.jpg / imgdir 

注: カメラを呼び出して検出することはまだサポートされていません。

テストプロセスの落とし穴!

YOLOv6 プロジェクトの構造を観察すると、それが珍しいことがわかります。上記のテスト手順と同様に、作成者は推論、トレーニング、評価のコードをツールの下に置き、その中に yolov6 の別のサブフォルダーがあります。プロジェクトには多くの機能が含まれています。この複雑な構造は、呼び出しプロセスでいくつかのエラーも引き起こします。

1. infer.pyのパスが間違っています

実はこの点はエラーレポートをよく読めば解決できますが、作者はソースコード内のフォルダの構造を考慮しておらず、下図のパスのように一部パラメータの読み込みパスが間違っていました。は tools の下にあるため、上のディレクトリにあるファイルを呼び出すときは、先頭に「.../」を追加します。
ここに画像の説明を挿入

2. エラー: AssertionError: フォント パスが存在しません: ./yolov6/utils/Arial.ttf

このエラーは依然として同じ問題です。公式コードは間違ったパスを記述しています。具体的には、yolov6/core/inferer.py プログラムの 244 行目で、このパスの前に「.」も追加されています。正しいコード以下の図に示されています。
ここに画像の説明を挿入
変更後は、test コマンドを実行するだけです。
ここに画像の説明を挿入

独自のデータセットをトレーニングする

1. データセットの準備

公式の README では coco 形式のデータセットが推奨されていますが、トレーニングでは VOC データセットを使用しました (YOLOv5 と同様のデータセットのアノテーションについてはここでは説明しません)。エクスポートされたタグは XML 形式でエクスポートできます。変換スクリプトを使用して、XML タグを yolo で必要な txt タグに変換し、voc データ セットの形式を自動的に調整します。変換スクリプトは以下で共有されます: (このスクリプトは yolov5 をデプロイするときに使用され、最終的に生成されるファイルには yolov5 にちなんだ名前が付けられます。これはバグではなく、使用には影響しません。

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
import random
from shutil import copyfile

classes=["A""B"]   #标签标注时的name

TRAIN_RATIO = 80       #数据集划分比:训练80%     

def clear_hidden_files(path):
    dir_list = os.listdir(path)
    for i in dir_list:
        abspath = os.path.join(os.path.abspath(path), i)
        if os.path.isfile(abspath):
            if i.startswith("._"):
                os.remove(abspath)
        else:
            clear_hidden_files(abspath)

def convert(size, box):
    dw = 1./size[0]
    dh = 1./size[1]
    x = (box[0] + box[1])/2.0
    y = (box[2] + box[3])/2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x*dw
    w = w*dw
    y = y*dh
    h = h*dh
    return (x,y,w,h)

def convert_annotation(image_id):
    in_file = open('VOCdevkit/VOC2007/Annotations/%s.xml' %image_id)        #只用修改这里加载的XML标签地址即可,执行脚本后会自动生成标准的VOC格式数据集
    out_file = open('VOCdevkit/VOC2007/YOLOLabels/%s.txt' %image_id, 'w')
    tree=ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)

    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        if cls not in classes or int(difficult) == 1:
            continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
        bb = convert((w,h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
    in_file.close()
    out_file.close()

wd = os.getcwd()
wd = os.getcwd()
data_base_dir = os.path.join(wd, "VOCdevkit/")
if not os.path.isdir(data_base_dir):
    os.mkdir(data_base_dir)
work_sapce_dir = os.path.join(data_base_dir, "VOC2007/")
if not os.path.isdir(work_sapce_dir):
    os.mkdir(work_sapce_dir)
annotation_dir = os.path.join(work_sapce_dir, "Annotations/")
if not os.path.isdir(annotation_dir):
        os.mkdir(annotation_dir)
clear_hidden_files(annotation_dir)
image_dir = os.path.join(work_sapce_dir, "JPEGImages/")
if not os.path.isdir(image_dir):
        os.mkdir(image_dir)
clear_hidden_files(image_dir)
yolo_labels_dir = os.path.join(work_sapce_dir, "YOLOLabels/")
if not os.path.isdir(yolo_labels_dir):
        os.mkdir(yolo_labels_dir)
clear_hidden_files(yolo_labels_dir)
yolov5_images_dir = os.path.join(data_base_dir, "images/")
if not os.path.isdir(yolov5_images_dir):
        os.mkdir(yolov5_images_dir)
clear_hidden_files(yolov5_images_dir)
yolov5_labels_dir = os.path.join(data_base_dir, "labels/")
if not os.path.isdir(yolov5_labels_dir):
        os.mkdir(yolov5_labels_dir)
clear_hidden_files(yolov5_labels_dir)
yolov5_images_train_dir = os.path.join(yolov5_images_dir, "train/")
if not os.path.isdir(yolov5_images_train_dir):
        os.mkdir(yolov5_images_train_dir)
clear_hidden_files(yolov5_images_train_dir)
yolov5_images_test_dir = os.path.join(yolov5_images_dir, "val/")
if not os.path.isdir(yolov5_images_test_dir):
        os.mkdir(yolov5_images_test_dir)
clear_hidden_files(yolov5_images_test_dir)
yolov5_labels_train_dir = os.path.join(yolov5_labels_dir, "train/")
if not os.path.isdir(yolov5_labels_train_dir):
        os.mkdir(yolov5_labels_train_dir)
clear_hidden_files(yolov5_labels_train_dir)
yolov5_labels_test_dir = os.path.join(yolov5_labels_dir, "val/")
if not os.path.isdir(yolov5_labels_test_dir):
        os.mkdir(yolov5_labels_test_dir)
clear_hidden_files(yolov5_labels_test_dir)

train_file = open(os.path.join(wd, "yolov5_train.txt"), 'w')
test_file = open(os.path.join(wd, "yolov5_val.txt"), 'w')
train_file.close()
test_file.close()
train_file = open(os.path.join(wd, "yolov5_train.txt"), 'a')
test_file = open(os.path.join(wd, "yolov5_val.txt"), 'a')
list_imgs = os.listdir(image_dir) # list image files
prob = random.randint(1, 100)
print("Probability: %d" % prob)
for i in range(0,len(list_imgs)):
    path = os.path.join(image_dir,list_imgs[i])
    if os.path.isfile(path):
        image_path = image_dir + list_imgs[i]
        voc_path = list_imgs[i]
        (nameWithoutExtention, extention) = os.path.splitext(os.path.basename(image_path))
        (voc_nameWithoutExtention, voc_extention) = os.path.splitext(os.path.basename(voc_path))
        annotation_name = nameWithoutExtention + '.xml'
        annotation_path = os.path.join(annotation_dir, annotation_name)
        label_name = nameWithoutExtention + '.txt'
        label_path = os.path.join(yolo_labels_dir, label_name)
    prob = random.randint(1, 100)
    print("Probability: %d" % prob)
    if(prob < TRAIN_RATIO): # train dataset
        if os.path.exists(annotation_path):
            train_file.write(image_path + '\n')
            convert_annotation(nameWithoutExtention) # convert label
            copyfile(image_path, yolov5_images_train_dir + voc_path)
            copyfile(label_path, yolov5_labels_train_dir + label_name)
    else: # test dataset
        if os.path.exists(annotation_path):
            test_file.write(image_path + '\n')
            convert_annotation(nameWithoutExtention) # convert label
            copyfile(image_path, yolov5_images_test_dir + voc_path)
            copyfile(label_path, yolov5_labels_test_dir + label_name)
train_file.close()
test_file.close()

データセットの作成については多くは言いませんが、VOC データセットの作成に関するチュートリアルも多数あります。

2. voc.yaml を変更する

data/voc.yaml 内のトレーニング データ セットのパスを変更します。
ここに画像の説明を挿入

3. tools/train.py にロードされたパラメータを変更し、トレーニングを開始します

ここでのパスと、コンピューターのパフォーマンスに応じた「--batch-size」および「--workers」に関するトレーニング ウェイトの読み込みに注意してください。たとえば、次のようになります。

結果:RuntimeError: CUDA のメモリが不足しています。200.00 MiB (GPU 0; 合計容量 4.00 GiB; すでに割り当てられている 2.88 GiB; 空き 0 バイト; PyTorch によって合計 2.89 GiB 予約) を割り当てようとしました)

エラーが報告された場合: ページが小さすぎるため操作を完了できません。
「--workers」を減らすだけです

トレーニングの途中に落とし穴が!

1、报错:AttributeError: 'Trainer' オブジェクトには属性 'epoch' がありません

ここに画像の説明を挿入
分析と解決策:
エラー メッセージによると、「Trainer」クラスに「epoch」クラスまたはパラメータが存在しないことを意味します。これは、yolov6/core/engine.py プログラムの「Trainer」クラスまで遡ることができます: 261 行目、プログラムは
次のように "self.epoch " を呼び出します。
ここに画像の説明を挿入
問題の原因を上方向に追跡し続けると、属性 "epoch" がこのクラスに定義されていないことに驚きました。そのため、呼び出すことができない非常に低レベルのエラーが発生しました。解決方法も非常に簡単で、クラスの初期化時にこの属性を定義するだけです。実はepochというのは見慣れないものではなく、「args」に定義されているパラメータです。そのため、下図のように「」からパラメータを取得します。 args" を取得し、それをエポック属性に渡します。:
ここに画像の説明を挿入

成功したトレーニング:

上記の落とし穴に対処した後、次のトレーニングを行うことができます。
ここに画像の説明を挿入

TensorRT による推論の高速化

最近、yolov6 の tensorRT アクセラレーションがデプロイされており、この部分の内容は整理が完了した後に更新されます。

おすすめ

転載: blog.csdn.net/uuhhy/article/details/127622432