1.将数据集分为训练集和验证集
dataset/
├── train/
├── images/
└── labels/
└── val/
├── images/
└── labels/
import os
import shutil
import random
random.seed(0)
def split_data(file_path,xml_path, new_file_path1, new_file_path2, train_rate, val_rate, test_rate):
each_class_image = []
each_class_label = []
for image in os.listdir(file_path):
each_class_image.append(image)
for label in os.listdir(xml_path):
each_class_label.append(label)
data=list(zip(each_class_image,each_class_label))
total = len(each_class_image)
random.shuffle(data)
each_class_image,each_class_label=zip(*data)
train_images = each_class_image[0:int(train_rate * total)]
val_images = each_class_image[int(train_rate * total):int((train_rate + val_rate) * total)]
test_images = each_class_image[int((train_rate + val_rate) * total):]
train_labels = each_class_label[0:int(train_rate * total)]
val_labels = each_class_label[int(train_rate * total):int((train_rate + val_rate) * total)]
test_labels = each_class_label[int((train_rate + val_rate) * total):]
for image in train_images:
print(image)
old_path = file_path + '/' + image
new_path1 = new_file_path1 + '/' + 'train'
if not os.path.exists(new_path1):
os.makedirs(new_path1)
new_path = new_path1 + '/' + image
shutil.copy(old_path, new_path)
for label in train_labels:
print(label)
old_path = xml_path + '/' + label
new_path1 = new_file_path2 + '/' + 'train'
if not os.path.exists(new_path1):
os.makedirs(new_path1)
new_path = new_path1 + '/' + label
shutil.copy(old_path, new_path)
for image in test_images:
old_path = file_path + '/' + image
new_path1 = new_file_path1 + '/' + 'val'
if not os.path.exists(new_path1):
os.makedirs(new_path1)
new_path = new_path1 + '/' + image
shutil.copy(old_path, new_path)
for label in test_labels:
old_path = xml_path + '/' + label
new_path1 = new_file_path2 + '/' + 'val'
if not os.path.exists(new_path1):
os.makedirs(new_path1)
new_path = new_path1 + '/' + label
shutil.copy(old_path, new_path)
if __name__ == '__main__':
file_path = "D:/desktop/picture"
xml_path = 'D:/desktop/label 2'
new_file_path1 = "D:/desktop/datasets/images"
new_file_path2 = "D:/desktop/datasets/labels"
split_data(file_path,xml_path, new_file_path1, new_file_path2, train_rate=0.8, val_rate=0.0, test_rate=0.2)
2.yaml文件
train: #绝对路径
val:
# number of classes
nc: 7
# class names
names: ["comet-T", "comet","steak","w","ww","head","impurity"]
3.先测试一下
yolo predict model=yolov8n.pt source="/share/home/zju_jiangyy/comet/cometv8/bus.jpg" save= True
4. train.py
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8m.pt") # load a pretrained model (recommended for training)
model = YOLO("yolov8m.yaml").load("yolov8m.pt") # build from YAML and transfer weights
# Train the model
results = model.train(data="..../.yaml", epochs=300)
5.练完在照片上试试
yolo detect predict model=/share...runs/detect/train5/weights/best.pt
source=/share.../test1 save=True
6.怎么知道模型是否可以提升或者是训练效果好不好呢?