手把手教你使用yolov11训练自己的数据集和推理
时间: 2025-05-04 22:58:03 浏览: 140
### 使用YOLOv11训练自定义数据集并实现推理
#### 一、YOLOv11简介
YOLOv11作为Ultralytics YOLO系列的目标检测算法之一,在性能和易用性方面都有显著提升[^4]。其核心优势在于快速的推理速度和高精度,适用于多种实际场景。
---
#### 二、环境配置
为了顺利运行YOLOv11,需完成以下准备工作:
##### 1. 安装PyTorch
YOLOv11基于PyTorch框架开发,因此需要先安装合适的PyTorch版本。具体命令如下:
```bash
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
```
##### 2. 克隆YOLOv11仓库
通过Git克隆官方GitHub仓库以获取源码:
```bash
git clone https://github.com/ultralytics/yolov11.git
cd yolov11
```
##### 3. 安装依赖项
执行以下命令来安装所需的Python库:
```bash
pip install -r requirements.txt
```
---
#### 三、数据集准备
以下是针对自定义数据集的具体操作流程:
##### 1. 数据收集与标注
使用工具(如LabelImg)对图像进行标注,并保存为Pascal VOC格式或COCO格式[^2]。
##### 2. 转换至YOLO格式
如果原始标注不是YOLO格式,则需要将其转换。假设已有的标注文件为VOC格式,可以利用脚本批量处理:
```python
from xml.etree import ElementTree as ET
import os
def convert_voc_to_yolo(xml_file, output_dir):
tree = ET.parse(xml_file)
root = tree.getroot()
image_width = int(root.find('size').find('width').text)
image_height = int(root.find('size').find('height').text)
with open(os.path.join(output_dir, f"{os.path.splitext(os.path.basename(xml_file))[0]}.txt"), 'w') as out_file:
for obj in root.findall('object'):
class_name = obj.find('name').text
bbox = obj.find('bndbox')
x_min = float(bbox.find('xmin').text)
y_min = float(bbox.find('ymin').text)
x_max = float(bbox.find('xmax').text)
y_max = float(bbox.find('ymax').text)
x_center = (x_min + x_max) / (2 * image_width)
y_center = (y_min + y_max) / (2 * image_height)
width = abs(x_max - x_min) / image_width
height = abs(y_max - y_min) / image_height
out_file.write(f"0 {x_center} {y_center} {width} {height}\n")
# 遍历XML文件夹并调用函数
xml_folder = './annotations'
output_txt_folder = './labels'
if not os.path.exists(output_txt_folder):
os.makedirs(output_txt_folder)
for file in os.listdir(xml_folder):
if file.endswith('.xml'):
convert_voc_to_yolo(os.path.join(xml_folder, file), output_txt_folder)
```
##### 3. 划分数据集
将数据分为训练集、验证集和测试集。通常比例为7:2:1。创建`train.txt`和`val.txt`文件记录对应的图片路径列表。
##### 4. 修改配置文件
编辑`data/custom.yaml`文件指定类别名称及数据分布:
```yaml
train: ./images/train/
val: ./images/val/
nc: 1 # 类别数量
names: ['custom_class'] # 自定义类名
```
---
#### 四、模型训练
启动训练过程前,确保GPU驱动正常工作。运行以下命令即可开始训练:
```bash
python train.py --img 640 --batch 16 --epochs 50 --data custom.yaml --weights yolov11.pt
```
其中参数解释如下:
- `--img`: 输入图像尺寸,默认为640×640。
- `--batch`: 批量大小。
- `--epochs`: 总轮次。
- `--data`: 数据配置文件路径。
- `--weights`: 初始化权重文件位置。
---
#### 五、模型推理
当训练完成后,可加载最佳权重文件用于推断新样本的结果。示例代码如下所示:
```python
from ultralytics import YOLO
model = YOLO('./runs/detect/train/weights/best.pt')
results = model.predict(source='test.jpg', save=True, conf=0.5)
```
上述脚本会读取一张名为`test.jpg`的图片,并输出带有边界框标记后的结果存储于本地磁盘中。
---
#### 六、常见问题解答
1. **中断恢复**: 如果因意外原因导致训练中途停止,可通过设置`resume`选项续训:
```bash
python train.py --resume
```
2. **显存不足错误**: 减少批次规模或将分辨率调整得更低一些尝试缓解此状况。
---
阅读全文
相关推荐
















