YOLOv4-tiny Darknet 目标检测训练实战:轻量模型配置、训练与推理
YOLOv4-tiny Darknet 目标检测训练实战:轻量模型配置、训练与推理
这篇教程根据我复现 YOLOv4-tiny Darknet 训练流程时整理,重点演示 cuDNN 环境、Darknet 编译、YOLO 数据整理、配置生成和测试集推理。
本文整理自我的学习和项目复现过程,尽量按实操顺序保留 notebook 的关键步骤,同时把数据集获取方式调整为适合中文教程发布的写法。
本文会重点跑通以下流程:
- 配置 Colab CUDA/cuDNN 环境
- 安装并编译 Darknet
- 从数据集后台获取 YOLO Darknet 格式数据
- 动态生成 YOLOv4-tiny 自定义配置
- 训练模型并随机选择测试图推理
如果你正在系统学习目标检测、实例分割、OCR、多目标跟踪或视觉大模型,建议收藏本文;配套 notebook、示例图片和运行环境说明后续会继续整理。如果环境配置卡住,可以在评论区说明具体报错。
📚 文章目录
- YOLOv4-tiny Darknet 目标检测训练实战:轻量模型配置、训练与推理
- ⚙️ 配置 CUDA/cuDNN
- 🧩 安装 Darknet
- 📦 从数据集后台获取 Darknet 数据
- 📁 整理训练文件
- 🔧 生成训练配置
- 🏋️ 训练 YOLOv4-tiny
- 🧪 推理工具函数
- 📌 小结
- 📚 同系列教程汇总
⚙️ 配置 CUDA/cuDNN
YOLOv4-tiny Darknet 对 CUDA/cuDNN 配置敏感,先检查运行环境。
# 检查 CUDA 是否已安装以及当前版本。!/usr/local/cuda/bin/nvcc--version# We need to install the correct cuDNN according to this output# 查看当前 GPU 型号!nvidia-smi# This cell ensures you have the correct architecture for your respective GPU# If you command is not found, look through these GPUs, find the respective# GPU and add them to the archTypes dictionary# Tesla V100# ARCH= -gencode arch=compute_70,code=[sm_70,compute_70]# Tesla K80# ARCH= -gencode arch=compute_37,code=sm_37# GeForce RTX 2080 Ti, RTX 2080, RTX 2070, Quadro RTX 8000, Quadro RTX 6000, Quadro RTX 5000, Tesla T4, XNOR Tensor Cores# ARCH= -gencode arch=compute_75,code=[sm_75,compute_75]# Jetson XAVIER# ARCH= -gencode arch=compute_72,code=[sm_72,compute_72]# GTX 1080, GTX 1070, GTX 1060, GTX 1050, GTX 1030, Titan Xp, Tesla P40, Tesla P4# ARCH= -gencode arch=compute_61,code=sm_61# GP100/Tesla P100 - DGX-1# ARCH= -gencode arch=compute_60,code=sm_60# For Jetson TX1, Tegra X1, DRIVE CX, DRIVE PX - uncomment:# ARCH= -gencode arch=compute_53,code=[sm_53,compute_53]# For Jetson Tx2 or Drive-PX2 uncomment:# ARCH= -gencode arch=compute_62,code=[sm_62,compute_62]importos os.environ['GPU_TYPE']=str(os.popen('nvidia-smi --query-gpu=name --format=csv,noheader').read())defgetGPUArch(argument):try:argument=argument.strip()# All Colab GPUsarchTypes={"Tesla V100-SXM2-16GB":"-gencode arch=compute_70,code=[sm_70,compute_70]","Tesla K80":"-gencode arch=compute_37,code=sm_37","Tesla T4":"-gencode arch=compute_75,code=[sm_75,compute_75]","Tesla P40":"-gencode arch=compute_61,code=sm_61","Tesla P4":"-gencode arch=compute_61,code=sm_61","Tesla P100-PCIE-16GB":"-gencode arch=compute_60,code=sm_60"}returnarchTypes[argument]exceptKeyError:return"GPU must be added to GPU Commands"os.environ['ARCH_VALUE']=getGPUArch(os.environ['GPU_TYPE'])print("GPU Type: "+os.environ['GPU_TYPE'])print("ARCH Value: "+os.environ['ARCH_VALUE'])🧩 安装 Darknet
克隆并编译 Darknet,开启 GPU、cuDNN 和 OpenCV 支持。
%cd/content/%rm-rf darknet# 克隆 Darknet 仓库,用于 YOLOv4-tiny 训练!git clone https://github.com/AlexeyAB/darknet.git#install environment from the Makefile%cd/content/darknet/# compute_37, sm_37 for Tesla K80# compute_75, sm_75 for Tesla T4# !sed -i 's/ARCH= -gencode arch=compute_60,code=sm_60/ARCH= -gencode arch=compute_75,code=sm_75/g' Makefile#install environment from the Makefile#note if you are on Colab Pro this works on a P100 GPU#if you are on Colab free, you may need to change the Makefile for the K80 GPU#this goes for any GPU, you need to change the Makefile to inform darknet which GPU you are running on.!sed-i's/OPENCV=0/OPENCV=1/g'Makefile !sed-i's/GPU=0/GPU=1/g'Makefile !sed-i's/CUDNN=0/CUDNN=1/g'Makefile !sed-i"s/ARCH= -gencode arch=compute_60,code=sm_60/ARCH= ${ARCH_VALUE}/g"Makefile !make#download the newly released yolov4-tiny weights%cd/content/darknet !wget https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v4_pre/yolov4-tiny.weights !wget https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v4_pre/yolov4-tiny.conv.29fromtypesimportSimpleNamespace# 从数据集后台下载 YOLO Darknet 格式数据集后,修改 DATASET_DIR 指向解压目录。DATASET_DIR="/content/dataset"# 修改为数据集后台导出的数据集目录dataset=SimpleNamespace(location=DATASET_DIR,version="1",name="custom-dataset")📦 从数据集后台获取 Darknet 数据
从数据集后台导出 YOLO Darknet 格式数据,并接入训练目录。
fromtypesimportSimpleNamespace# 从数据集后台下载 YOLO Darknet 检测 格式数据集后,修改 DATASET_DIR 指向解压目录。DATASET_DIR="/content/dataset"# 修改为数据集后台导出的数据集目录dataset=SimpleNamespace(location=DATASET_DIR,version="1",name="custom-dataset")# 数据集已在上一单元配置,如需更换数据,请修改 DATASET_DIR。print(dataset.location)📁 整理训练文件
复制图片、标签和类别文件,生成 Darknet 训练所需的 obj.data。
# 根据类别数量动态生成配置#we build iteratively from base config files. This is the same file shape as cfg/yolo-obj.cfgdeffile_len(fname):withopen(fname)asf:fori,linenumerate(f):passreturni+1num_classes=file_len(dataset.location+'/train/_darknet.labels')max_batches=num_classes*2000steps1=.8*max_batches steps2=.9*max_batches steps_str=str(steps1)+','+str(steps2)num_filters=(num_classes+5)*3print("writing config for a custom YOLOv4 detector detecting number of classes: "+str(num_classes))#Instructions from the darknet repo#change line max_batches to (classes*2000 but not less than number of training images, and not less than 6000), f.e. max_batches=6000 if you train for 3 classes#change line steps to 80% and 90% of max_batches, f.e. steps=4800,5400ifos.path.exists('./cfg/custom-yolov4-tiny-detector.cfg'):os.remove('./cfg/custom-yolov4-tiny-detector.cfg')#customize iPython writefile so we can write variablesfromIPython.core.magicimportregister_line_cell_magic@register_line_cell_magicdefwritetemplate(line,cell):withopen(line,'w')asf:f.write(cell.format(**globals()))🔧 生成训练配置
根据类别数动态修改 filters、classes、max_batches 等配置。
%%writetemplate./cfg/custom-yolov4-tiny-detector.cfg[net]# Testing#batch=1#subdivisions=1# Trainingbatch=64subdivisions=24width=416height=416channels=3momentum=0.9decay=0.0005angle=0saturation=1.5exposure=1.5hue=.1learning_rate=0.00261burn_in=1000max_batches={max_batches}policy=steps steps={steps_str}scales=.1,.1[convolutional]batch_normalize=1filters=32size=3stride=2pad=1activation=leaky[convolutional]batch_normalize=1filters=64size=3stride=2pad=1activation=leaky[convolutional]batch_normalize=1filters=64size=3stride=1pad=1activation=leaky[route]layers=-1groups=2group_id=1[convolutional]batch_normalize=1filters=32size=3stride=1pad=1activation=leaky[convolutional]batch_normalize=1filters=32size=3stride=1pad=1activation=leaky[route]layers=-1,-2[convolutional]batch_normalize=1filters=64size=1stride=1pad=1activation=leaky[route]layers=-6,-1[maxpool]size=2stride=2[convolutional]batch_normalize=1filters=128size=3stride=1pad=1activation=leaky[route]layers=-1groups=2group_id=1[convolutional]batch_normalize=1filters=64size=3stride=1pad=1activation=leaky[convolutional]batch_normalize=1filters=64size=3stride=1pad=1activation=leaky[route]layers=-1,-2[convolutional]batch_normalize=1filters=128size=1stride=1pad=1activation=leaky[route]layers=-6,-1[maxpool]size=2stride=2[convolutional]batch_normalize=1filters=256size=3stride=1pad=1activation=leaky[route]layers=-1groups=2group_id=1[convolutional]batch_normalize=1filters=128size=3stride=1pad=1activation=leaky[convolutional]batch_normalize=1filters=128size=3stride=1pad=1activation=leaky[route]layers=-1,-2[convolutional]batch_normalize=1filters=256size=1stride=1pad=1activation=leaky[route]layers=-6,-1[maxpool]size=2stride=2[convolutional]batch_normalize=1filters=512size=3stride=1pad=1activation=leaky##################################[convolutional]batch_normalize=1filters=256size=1stride=1pad=1activation=leaky[convolutional]batch_normalize=1filters=512size=3stride=1pad=1activation=leaky[convolutional]size=1stride=1pad=1filters={num_filters}activation=linear[yolo]mask=3,4,5anchors=10,14,23,27,37,58,81,82,135,169,344,319classes={num_classes}num=6jitter=.3scale_x_y=1.05cls_normalizer=1.0iou_normalizer=0.07iou_loss=ciou ignore_thresh=.7truth_thresh=1random=0nms_kind=greedynms beta_nms=0.6[route]layers=-4[convolutional]batch_normalize=1filters=128size=1stride=1pad=1activation=leaky[upsample]stride=2[route]layers=-1,23[convolutional]batch_normalize=1filters=256size=3stride=1pad=1activation=leaky[convolutional]size=1stride=1pad=1filters={num_filters}activation=linear[yolo]mask=1,2,3anchors=10,14,23,27,37,58,81,82,135,169,344,319classes={num_classes}num=6jitter=.3scale_x_y=1.05cls_normalizer=1.0iou_normalizer=0.07iou_loss=ciou ignore_thresh=.7truth_thresh=1random=0nms_kind=greedynms beta_nms=0.6# 查看刚写入的配置文件。#you may consider adjusting certain things#like the number of subdivisions 64 runs faster but Colab GPU may not be big enough#if Colab GPU memory is too small, you will need to adjust subdivisions to 16%cat cfg/custom-yolov4-tiny-detector.cfg!./darknet detector train data/obj.data cfg/custom-yolov4-tiny-detector.cfg yolov4-tiny.conv.29-dont_show-map#If you get CUDA out of memory adjust subdivisions above!#adjust max batches down for shorter training above# 定义图片显示工具函数defimShow(path):importcv2importmatplotlib.pyplotasplt%matplotlib inline image=cv2.imread(path)height,width=image.shape[:2]resized_image=cv2.resize(image,(3*width,3*height),interpolation=cv2.INTER_CUBIC)fig=plt.gcf()fig.set_size_inches(18,10)plt.axis("off")#plt.rcParams['figure.figsize'] = [10, 5]plt.imshow(cv2.cvtColor(resized_image,cv2.COLOR_BGR2RGB))plt.show()🏋️ 训练 YOLOv4-tiny
启动 Darknet 训练。如果显存不足,优先调整 subdivisions。
# 检查权重是否已保存#backup houses the last weights for our detector#(file yolo-obj_last.weights will be saved to the build\darknet\x64\backup\ for each 100 iterations)#(file yolo-obj_xxxx.weights will be saved to the build\darknet\x64\backup\ for each 1000 iterations)#After training is complete - get result yolo-obj_final.weights from path build\darknet\x64\bac!ls backup#if it is empty you haven't trained for long enough yet, you need to train for at least 100 iterations🧪 推理工具函数
定义图片显示工具,方便查看 Darknet 推理结果。
#coco.names is hardcoded somewhere in the detector%cp data/obj.names data/coco.names# test 目录中包含可用于测试的图片test_images=[fforfinos.listdir('test')iff.endswith('.jpg')]importrandom img_path="test/"+random.choice(test_images);#test out our detector!!./darknet detect cfg/custom-yolov4-tiny-detector.cfg backup/custom-yolov4-tiny-detector_best.weights{img_path}-dont-show imShow('/content/darknet/predictions.jpg')📌 小结
这篇教程完整整理了YOLOv4-tiny Darknet 目标检测训练的核心复现流程。实际操作时,建议先确认 GPU、依赖版本、数据集路径和模型权重路径,再逐段运行 notebook。
后续我会继续按源项目顺序整理同系列中的目标检测、实例分割、OCR、多目标跟踪和视觉大模型教程。
📚 同系列教程汇总
Google Gemini 3.5 Flash 零样本目标检测教程:从提示词到可视化结果
GLM-OCR 文档识别实战教程:从验证码、公式到车牌 OCR
RF-DETR + ByteTrack 多目标跟踪实战教程:从命令行到 Python 视频轨迹可视化
SAM 3 图像分割实战教程:文本、框和点提示的多种分割方式
SAM 3 视频分割实战教程:用文本提示分割并跟踪视频中的目标
YOLOv4-tiny Darknet 目标检测训练实战:轻量模型配置、训练与推理-本文