BiSeNetV2实战:从零构建实时语义分割模型,在Camvid数据集上实现工业级部署
如果你正在寻找一个能在移动端或边缘设备上流畅运行的语义分割方案,同时又不希望牺牲太多精度,那么BiSeNetV2绝对值得你投入时间深入研究。我在几个实际的道路场景理解项目中都采用了这个架构,它那种双分支设计的巧妙思路,让我在处理需要兼顾实时性与准确性的任务时,总能游刃有余。不同于那些动辄数百兆的庞然大物,BiSeNetV2在保持轻量化的同时,通过Detail Branch捕捉丰富的空间细节,再通过Semantic Branch获取高层语义上下文,最后用一个精心设计的Aggregation Layer将两者融合,这套组合拳打下来,效果往往出人意料的好。
今天这篇文章,我会带你从零开始,用PyTorch完整地实现BiSeNetV2,并基于经典的Camvid数据集进行训练、调优和可视化。整个过程我会穿插大量我在实践中踩过的坑和总结的技巧,目标是让你不仅能跑通代码,更能理解模型设计的精髓,并具备将其应用到你自己项目中的能力。无论你是刚接触语义分割的开发者,还是希望优化现有模型性能的工程师,相信都能从中获得实用的收获。
1. 环境准备与数据工程
在开始构建模型之前,一个稳定、可复现的环境是高效开发的基础。我强烈建议使用Conda来管理你的Python环境,它能有效避免不同项目间的依赖冲突。
1.1 创建并配置Python环境
首先,我们创建一个独立的Python 3.8环境,并安装核心的深度学习框架。
conda create -n bisenetv2 python=3.8 -y
conda activate bisenetv2
pip install torch==1.12.1+cu113 torchvision==0.13.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113
注意:这里指定了CUDA 11.3版本的PyTorch,请根据你本地的CUDA版本进行调整。使用
nvcc --version或nvidia-smi可以查看CUDA版本。
接下来,安装数据处理和可视化相关的库。Albumentations是一个功能强大且速度极快的图像增强库,在语义分割任务中尤其好用。
pip install albumentations==1.3.0 opencv-python pillow pandas matplotlib tqdm
pip install scikit-learn scikit-image
1.2 Camvid数据集解析与预处理
Camvid(Cambridge-driving Labeled Video Database)是一个用于自动驾驶场景理解的经典数据集。它包含700多张像素级标注的图像,涵盖32个语义类别(实际常用33类,包含一个“void”类)。数据集的标注质量很高,但类别不平衡问题比较明显,例如“道路”和“天空”的像素远多于“行人”或“自行车”,这在训练时需要特别注意。
数据集结构通常如下所示:
camvid/
├── train_images/
│ ├── 0001TP_006690.png
│ └── ...
├── train_labels/
│ ├── 0001TP_006690.png
│ └── ...
├── val_images/
│ └── ...
└── val_labels/
└── ...
我们需要编写一个Dataset类来加载图像和对应的标签。标签图像是RGB格式的,每个颜色对应一个特定的类别。因此,我们需要一个将RGB标签映射到类别索引(0-32)的函数。
import os
from PIL import Image
import numpy as np
import torch
from torch.utils.data import Dataset
import albumentations as A
from albumentations.pytorch import ToTensorV2
# Camvid的官方颜色到类别索引的映射
CAMVID_COLORS = [
(64, 128, 64), # Animal -> 0
(192, 0, 128), # Archway -> 1
(0, 128, 192), # Bicyclist -> 2
(0, 128, 64), # Bridge -> 3
(128, 0, 0), # Building -> 4
(64, 0, 128), # Car -> 5
(64, 0, 192), # CartLuggagePram -> 6
(192, 128, 64), # Child -> 7
(192, 192, 128), # Column_Pole -> 8
(64, 64, 128), # Fence -> 9
(128, 0, 192), # LaneMkgsDriv -> 10
(192, 0, 64), # LaneMkgsNonDriv -> 11
(128, 128, 64), # Misc_Text -> 12
(192, 0, 192), # MotorcycleScooter -> 13
(128, 64, 64), # OtherMoving -> 14
(64, 192, 128), # ParkingBlock -> 15
(64, 64, 0), # Pedestrian -> 16
(128, 64, 128), # Road -> 17
(128, 128, 192), # RoadShoulder -> 18
(0, 0, 192), # Sidewalk -> 19
(192, 128, 128), # SignSymbol -> 20
(128, 128, 128), # Sky -> 21
(64, 128, 192), # SUVPickupTruck -> 22
(0, 0, 64), # TrafficCone -> 23
(0, 64, 64), # TrafficLight -> 24
(192, 64, 128), # Train -> 25
(128, 128, 0), # Tree -> 26
(192, 128, 192), # Truck_Bus -> 27
(64, 0, 64), # Tunnel -> 28
(192, 192, 0), # VegetationMisc -> 29
(0, 0, 0), # Void -> 30 (通常忽略)
(64, 192, 0), # Wall -> 31
(128, 64, 192), # Bridge -> 32 (有时单独列出)
]
def rgb_to_mask(img_rgb, color_map=CAMVID_COLORS):
"""将RGB标签图像转换为类别索引掩码"""
h, w = img_rgb.shape[:2]
mask = np.zeros((h, w), dtype=np.uint8) + 30 # 默认填充为Void类别
img_rgb = img_rgb.astype(np.int32)
for class_idx, color in enumerate(color_map):
# 计算每个像素与当前颜色的欧氏距离,找到精确匹配的像素
color_arr = np.array(color).reshape(1, 1, 3)
diff = np.sum(np.abs(img_rgb - color_arr), axis=2)
match_pixels = diff == 0
mask[match_pixels] = class_idx
return mask
class CamvidDataset(Dataset):
def __init__(self, images_dir, masks_dir, transform=None, img_size=(448, 448)):
self.images_dir = images_dir
self.masks_dir = masks_dir
self.transform = transform
self.img_size = img_size
self.image_files = sorted([f for f in os.listdir(images_dir) if f.endswith('.png')])
self.mask_files = sorted([f for f in os.listdir(masks_dir) if f.endswith('.png')])
# 确保图像和掩码文件一一对应
assert len(self.image_files) == len(self.mask_files)
for img, msk in zip(self.image_files, self.mask_files):
assert img == msk, f"Mismatch: {img} vs {msk}"
def __len__(self):
return len(self.image_files)
def __getitem__(self, idx):
img_path = os.path.join(self.images_dir, self.image_files[idx])
mask_path = os.path.join(self.masks_dir, self.mask_files[idx])
image = np.array(Image.open(img_path).convert('RGB'))
mask_rgb = np.array(Image.open(mask_path).convert('RGB'))
mask = rgb_to_mask(mask_rgb) # 转换为单通道类别索引图
if self.transform:
augmented = self.transform(image=image, mask=mask)
image = augmented['image']
mask = augmented['mask']
else:
# 基础转换:调整大小并转为Tensor
transform = A.Compose([
A.Resize(height=self.img_size[0], width=self.img_size[1]),
A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
ToTensorV2(),
])
augmented = transform(image=image, mask=mask)
image = augmented['image']
mask = augmented['mask'].long() # 确保mask是Long类型
return image, mask
数据增强策略对于语义分割模型的泛化能力至关重要。对于Camvid这类街景数据,我常用的增强组合如下:
def get_train_transform(img_size=(448, 448)):
return A.Compose([
A.Resize(height=img_size[0], width=img_size[1]),
A.HorizontalFlip(p=0.5),
A.VerticalFlip(p=0.1), # 街景中垂直翻转较少,概率设低
A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.5),
A.HueSaturationValue(hue_shift_limit=10, sat_shift_limit=20, val_shift_limit=10, p=0.5),
A.ShiftScaleRotate(shift_limit=0.1, scale_limit=0.1, rotate_limit=15, p=0.5, border_mode=0),
A.CoarseDropout(max_holes=8, max_height=img_size[0]//20, max_width=img_size[1]//20,
fill_value=0, mask_fill_value=30, p=0.3), # 模拟遮挡
A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
ToTensorV2(),
])
def get_val_transform(img_size=(448, 448)):
return A.Compose([
A.Resize(height=img_size[0], width=img_size[1]),
A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
ToTensorV2(),
])
提示:
A.CoarseDropout中的mask_fill_value=30对应的是Camvid中的“Void”类别索引,这样在随机遮挡区域,模型学习到的是忽略该区域,而不是错误地预测为其他类别。
2. BiSeNetV2模型架构深度解析与实现
BiSeNetV2的核心思想在于解耦空间细节与语义信息,并通过高效的聚合模块将它们融合。下面我们分模块拆解,并给出我优化后的实现版本。
2.1 Detail Branch:捕捉高频空间细节
Detail Branch的设计目标是快速下采样并保留丰富的边缘、纹理信息。它采用了类似VGG的简单堆叠结构,没有使用残差连接或注意力机制,以保持其轻量和快速的特点。
import torch
import torch.nn as nn
import torch.nn.functional as F
class DetailBranch(nn.Module):
"""
细节分支:使用浅层、宽通道的网络快速提取空间细节特征。
输入:3通道RGB图像
输出:高维特征图,空间分辨率逐步降低(通常为输入的1/8)
"""
def __init__(self, in_channels=3, stage_channels=(64, 64, 128)):
super().__init__()
self.stages = nn.ModuleList()
# 第一阶段:快速下采样
self.stages.append(
nn.Sequential(
nn.Conv2d(in_channels, stage_channels[0], kernel_size=3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(stage_channels[0]),
nn.ReLU(inplace=True),
nn.Conv2d(stage_channels[0], stage_channels[0], kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(stage_channels[0]),
nn.ReLU(inplace=True),
)
)
# 中间阶段:继续下采样并增加通道数
for i in range(1, len(stage_channels)):
self.stages.append(
nn.Sequential(
nn.Conv2d(stage_channels[i-1], stage_channels[i], kernel_size=3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(stage_channels[i]),
nn.ReLU(inplace=True),
nn.Conv2d(stage_channels[i], stage_channels[i], kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(stage_channels[i]),
nn.ReLU(inplace=True),
nn.Conv2d(stage_channels[i], stage_channels[i], kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(stage_channels[i]),
nn.ReLU(inplace=True),
)
)
def forward(self, x):
for stage in self.stages:
x = stage(x)
return x
这个分支有几个设计要点:
- 不使用最大池化:全部使用步长为2的卷积进行下采样,能更好地保留位置信息。
- 通道数适中:相比语义分支,细节分支的通道数更多,因为空间细节信息需要更高的容量来编码。
- 激活函数:使用ReLU而非更复杂的Swish或Mish,权衡了速度与效果。
2.2 Semantic Branch:提取高层语义上下文
语义分支的目标是快速扩大感受野,理解图像的全局上下文。它采用了更深的网络和精心设计的模块。
Stem Block是语义分支的入口,负责快速进行4倍下采样:
class StemBlock(nn.Module):
def __init__(self, in_channels=3, out_channels=16):
super().__init__()
# 主路径:3x3卷积,步长2
self.conv_main = nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
# 分支路径:1x1卷积降维 -> 3x3卷积下采样
self.conv_branch = nn.Sequential(
nn.Conv2d(out_channels, out_channels//2, 1, bias=False),
nn.BatchNorm2d(out_channels//2),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels//2, out_channels, 3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
# 池化路径:最大池化
self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
# 特征融合层
self.fusion = nn.Sequential(
nn.Conv2d(out_channels*2, out_channels, 3, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
def forward(self, x):
x = self.conv_main(x) # [B, C, H/2, W/2]
x_branch = self.conv_branch(x) # [B, C, H/4, W/4]
x_pool = self.pool(x) # [B, C, H/4, W/4]
# 拼接两个分支的特征
x_concat = torch.cat([x_branch, x_pool], dim=1) # [B, 2C, H/4, W/4]
out = self.fusion(x_concat) # [B, C, H/4, W/4]
return out
Gather-and-Expansion Layer (GE Layer) 是语义分支的核心模块,借鉴了MobileNetV2的倒残差结构,在保持轻量的同时增强特征表达能力:
class DepthwiseSeparableConv(nn.Module):
"""深度可分离卷积:大幅减少参数量和计算量"""
def __init__(self, in_channels, out_channels, stride=1):
super().__init__()
self.depthwise = nn.Conv2d(
in_channels, in_channels, kernel_size=3,
stride=stride, padding=1, groups=in_channels, bias=False
)
self.pointwise = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(in_channels)
self.bn2 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
x = self.depthwise(x)
x = self.bn1(x)
x = self.relu(x)
x = self.pointwise(x)
x = self.bn2(x)
return x
class GELayer(nn.Module):
"""收集与扩展层:包含下采样和非下采样两种变体"""
def __init__(self, in_channels, out_channels, expansion_ratio=6, stride=1):
super().__init__()
hidden_dim = in_channels * expansion_ratio
# 第一个1x1卷积,不改变通道数
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels, in_channels, 3, padding=1, bias=False),
nn.BatchNorm2d(in_channels),
nn.ReLU(inplace=True)
)
# 深度可分离卷积块
if stride == 1:
# 非下采样版本
self.dwconv = nn.Sequential(
nn.Conv2d(in_channels, hidden_dim, 3, padding=1, groups=in_channels, bias=False),
nn.BatchNorm2d(hidden_dim),
nn.ReLU(inplace=True),
DepthwiseSeparableConv(hidden_dim, hidden_dim, stride=1),
nn.BatchNorm2d(hidden_dim),
)
self.shortcut = None
else:
# 下采样版本
self.dwconv = nn.Sequential(
nn.Conv2d(in_channels, hidden_dim, 3, padding=1, groups=in_channels, bias=False),
nn.BatchNorm2d(hidden_dim),
nn.ReLU(inplace=True),
DepthwiseSeparableConv(hidden_dim, hidden_dim, stride=stride),
nn.BatchNorm2d(hidden_dim),
DepthwiseSeparableConv(hidden_dim, hidden_dim, stride=1),
nn.BatchNorm2d(hidden_dim),
)
# 下采样时需要shortcut匹配维度
self.shortcut = nn.Sequential(
DepthwiseSeparableConv(in_channels, out_channels, stride=stride),
nn.BatchNorm2d(out_channels),
nn.Conv2d(out_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_channels),
)
# 最后的1x1卷积,降回目标通道数
self.conv2 = nn.Sequential(
nn.Conv2d(hidden_dim, out_channels, 1, bias=False),
nn.BatchNorm2d(out_channels)
)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
identity = x
x = self.conv1(x)
x = self.dwconv(x)
x = self.conv2(x)
if self.shortcut is not None:
identity = self.shortcut(identity)
x += identity
x = self.relu(x)
return x
Context Embedding Block (CE Block) 在语义分支的末端,通过全局平均池化捕获图像级的上下文信息:
class CEBlock(nn.Module):
"""上下文嵌入块:使用全局平均池化获取全局上下文"""
def __init__(self, in_channels, out_channels):
super().__init__()
self.gap = nn.AdaptiveAvgPool2d((1, 1))
self.conv_gap = nn.Sequential(
nn.Conv2d(in_channels, out_channels, 1, bias=False),
nn.ReLU(inplace=True)
)
# 论文中这里是一个普通的3x3卷积,没有BN和ReLU
self.conv_last = nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False)
def forward(self, x):
identity = x
# 全局平均池化 + 1x1卷积
x_gap = self.gap(x)
x_gap = self.conv_gap(x_gap)
# 将全局特征广播到每个空间位置并与原始特征相加
x = identity + x_gap
x = self.conv_last(x)
return x
现在我们可以组装完整的语义分支:
class SemanticBranch(nn.Module):
def __init__(self, in_channels=3, stage_channels=(16, 32, 64, 128), expansion_ratio=6):
super().__init__()
self.stages = nn.ModuleList()
# Stage 1: Stem Block (4倍下采样)
self.stages.append(StemBlock(in_channels, stage_channels[0]))
# Stage 2-4: GE Layers
for i in range(1, len(stage_channels)):
if i == len(stage_channels) - 1:
# 最后一个阶段:1个下采样GE + 3个非下采样GE
stage_layers = [
GELayer(stage_channels[i-1], stage_channels[i], expansion_ratio, stride=2),
GELayer(stage_channels[i], stage_channels[i], expansion_ratio, stride=1),
GELayer(stage_channels[i], stage_channels[i], expansion_ratio, stride=1),
GELayer(stage_channels[i], stage_channels[i], expansion_ratio, stride=1),
]
else:
# 中间阶段:1个下采样GE + 1个非下采样GE
stage_layers = [
GELayer(stage_channels[i-1], stage_channels[i], expansion_ratio, stride=2),
GELayer(stage_channels[i], stage_channels[i], expansion_ratio, stride=1),
]
self.stages.append(nn.Sequential(*stage_layers))
# Stage 5: Context Embedding Block
self.stages.append(CEBlock(stage_channels[-1], stage_channels[-1]))
def forward(self, x):
features = []
for stage in self.stages:
x = stage(x)
features.append(x)
return features # 返回所有阶段的特征,用于辅助损失
2.3 Aggregation Layer:特征融合的艺术
这是BiSeNetV2最精妙的部分,它负责将细节分支的高分辨率特征与语义分支的丰富上下文特征进行有效融合。
class AggregationLayer(nn.Module):
def __init__(self, detail_channels, semantic_channels, out_channels):
super().__init__()
# 细节分支处理路径1:保持空间分辨率
self.detail_branch_1 = nn.Sequential(
DepthwiseSeparableConv(detail_channels, out_channels, stride=1),
nn.BatchNorm2d(out_channels),
nn.Conv2d(out_channels, out_channels, 1, bias=False)
)
# 细节分支处理路径2:下采样路径
self.detail_branch_2 = nn.Sequential(
nn.Conv2d(detail_channels, out_channels, 3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.AvgPool2d(kernel_size=3, stride=2, padding=1)
)
# 语义分支处理路径1:生成注意力权重
self.semantic_branch_1 = nn.Sequential(
nn.Conv2d(semantic_channels, out_channels, 3, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.Upsample(scale_factor=4, mode='bilinear', align_corners=True),
nn.Sigmoid() # 输出0-1的注意力权重
)
# 语义分支处理路径2:生成另一组注意力权重
self.semantic_branch_2 = nn.Sequential(
DepthwiseSeparableConv(semantic_channels, out_channels, stride=1),
nn.BatchNorm2d(out_channels),
nn.Conv2d(out_channels, out_channels, 1, bias=False),
nn.Sigmoid()
)
# 最终融合卷积
self.fusion_conv = nn.Sequential(
nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False),
nn.BatchNorm2d(out_channels)
)
def forward(self, detail_feat, semantic_feat):
# 处理细节特征
d1 = self.detail_branch_1(detail_feat) # [B, C, H, W]
d2 = self.detail_branch_2(detail_feat) # [B, C, H/4, W/4]
# 处理语义特征,生成注意力图
s1 = self.semantic_branch_1(semantic_feat) # [B, C, H, W]
s2 = self.semantic_branch_2(semantic_feat) # [B, C, H/4, W/4]
# 使用矩阵乘法进行特征调制(实际上是逐元素相乘)
# 这里论文中的"matmul"在实现上通常是逐元素相乘
out1 = d1 * s1 # 高分辨率特征加权
out2 = d2 * s2 # 低分辨率特征加权
# 将低分辨率特征上采样到原始尺寸
out2 = F.interpolate(out2, scale_factor=4, mode='bilinear', align_corners=True)
# 融合两个尺度的特征
out = out1 + out2 # 论文中是matmul,但实际实现多为相加
out = self.fusion_conv(out)
return out
这个聚合层的设计有几个关键点:
- 双路径注意力机制:语义分支生成两套注意力图,分别作用于细节分支的不同分辨率特征。
- 矩阵乘法实现特征选择:通过逐元素相乘,让语义信息指导细节特征的选择性保留。
- 多尺度融合:结合了高分辨率的细节和低分辨率的上下文信息。
2.4 分割头与辅助损失
分割头相对简单,但辅助损失的设计对训练稳定性有很大影响。
class SegmentationHead(nn.Module):
"""分割头:将特征图转换为类别预测"""
def __init__(self, in_channels, num_classes):
super().__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_channels, in_channels, 3, padding=1, bias=False),
nn.BatchNorm2d(in_channels),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels, num_classes, 1)
)
def forward(self, x):
return self.conv(x)
class BiSeNetV2(nn.Module):
"""完整的BiSeNetV2模型"""
def __init__(self, num_classes=33, detail_channels=(64, 64, 128),
semantic_channels=(16, 32, 64, 128), aggregation_channels=128):
super().__init__()
self.num_classes = num_classes
# 双分支主干
self.detail_branch = DetailBranch(in_channels=3, stage_channels=detail_channels)
self.semantic_branch = SemanticBranch(in_channels=3, stage_channels=semantic_channels)
# 聚合层
self.aggregation = AggregationLayer(
detail_channels=detail_channels[-1], # 细节分支最后阶段的通道数
semantic_channels=semantic_channels[-1], # 语义分支最后阶段的通道数
out_channels=aggregation_channels
)
# 主分割头(作用于聚合后的特征)
self.seg_head_main = SegmentationHead(aggregation_channels, num_classes)
# 辅助分割头(作用于语义分支的中间特征)
self.aux_heads = nn.ModuleList()
for i, channels in enumerate(semantic_channels):
self.aux_heads.append(SegmentationHead(channels, num_classes))
# 初始化权重
self._init_weights()
def _init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, x):
# 获取输入尺寸,用于后续上采样
_, _, H, W = x.shape
# 双分支特征提取
detail_feat = self.detail_branch(x) # [B, 128, H/8, W/8]
semantic_feats = self.semantic_branch(x) # 5个特征图列表
# 特征聚合(使用语义分支的最后一个特征)
aggregated = self.aggregation(detail_feat, semantic_feats[-1]) # [B, 128, H/8, W/8]
# 主分割输出
main_out = self.seg_head_main(aggregated)
main_out = F.interpolate(main_out, size=(H, W), mode='bilinear', align_corners=True)
# 辅助分割输出
aux_outs = []
for i, feat in enumerate(semantic_feats[:-1]): # 前4个特征图用于辅助损失
aux_out = self.aux_heads[i](feat)
aux_out = F.interpolate(aux_out, size=(H, W), mode='bilinear', align_corners=True)
aux_outs.append(aux_out)
return [main_out] + aux_outs
注意:辅助损失只在训练时使用,推理时可以只使用主输出。这种设计借鉴了深度监督的思想,有助于梯度回传,改善深层网络的训练。
3. 训练策略与调参技巧
有了模型和数据,接下来就是最关键的训练环节。我在多个项目中使用BiSeNetV2后,总结出了一套比较有效的训练策略。
3.1 损失函数设计
对于多类别语义分割,交叉熵损失是标准选择。但Camvid数据集存在严重的类别不平衡问题,需要特别处理。
import torch.nn as nn
import torch.nn.functional as F
class WeightedCrossEntropyLoss(nn.Module):
"""带类别权重的交叉熵损失"""
def __init__(self, weight=None, ignore_index=255):
super().__init__()
self.weight = weight
self.ignore_index = ignore_index
def forward(self, pred, target):
if self.weight is not None:
self.weight = self.weight.to(pred.device)
loss = F.cross_entropy(pred, target, weight=self.weight,
ignore_index=self.ignore_index, reduction='mean')
return loss
def calculate_class_weights(dataset, num_classes=33):
"""计算类别权重以处理不平衡"""
class_pixels = torch.zeros(num_classes)
total_pixels = 0
for _, mask in dataset:
unique, counts = torch.unique(mask, return_counts=True)
for cls, cnt in zip(unique, counts):
if cls < num_classes: # 忽略void类别
class_pixels[cls] += cnt
total_pixels += cnt
# 使用中位数频率平衡
class_freq = class_pixels / total_pixels
median_freq = torch.median(class_freq[class_freq > 0])
weights = median_freq / class_freq
weights[torch.isinf(weights)] = 0 # 处理除零情况
weights = weights / weights.sum() * num_classes # 归一化
return weights
# 计算Camvid的类别权重(示例值,实际应从训练集计算)
camvid_weights = torch.tensor([
2.5, # Animal
10.0, # Archway
8.0, # Bicyclist
6.0, # Bridge
0.8, # Building
1.0, # Car
15.0, # CartLuggagePram
12.0, # Child
7.0, # Column_Pole
5.0, # Fence
1.5, # LaneMkgsDriv
3.0, # LaneMkgsNonDriv
9.0, # Misc_Text
14.0, # MotorcycleScooter
11.0, # OtherMoving
4.0, # ParkingBlock
13.0, # Pedestrian
0.6, # Road
2.0, # RoadShoulder
1.2, # Sidewalk
8.5, # SignSymbol
0.7, # Sky
1.1, # SUVPickupTruck
16.0, # TrafficCone
9.5, # TrafficLight
17.0, # Train
0.9, # Tree
1.3, # Truck_Bus
5.5, # Tunnel
0.8, # VegetationMisc
0.0, # Void (忽略)
4.5, # Wall
6.5, # Bridge (重复)
])
对于BiSeNetV2,我们需要结合主损失和辅助损失:
class BiSeNetV2Loss(nn.Module):
def __init__(self, main_weight=1.0, aux_weights=(0.2, 0.2, 0.2, 0.2),
class_weights=None, ignore_index=255):
super().__init__()
self.main_weight = main_weight
self.aux_weights = aux_weights
self.criterion = WeightedCrossEntropyLoss(weight=class_weights,
ignore_index=ignore_index)
def forward(self, preds, target):
"""
preds: 列表,[main_output, aux1, aux2, aux3, aux4]
target: 真实标签
"""
main_pred = preds[0]
aux_preds = preds[1:]
# 主损失
main_loss = self.criterion(main_pred, target)
# 辅助损失
aux_losses = []
for i, aux_pred in enumerate(aux_preds):
loss = self.criterion(aux_pred, target)
aux_losses.append(loss * self.aux_weights[i])
total_aux_loss = sum(aux_losses)
# 总损失
total_loss = main_loss * self.main_weight + total_aux_loss
return total_loss, main_loss, total_aux_loss
3.2 优化器与学习率调度
BiSeNetV2对学习率比较敏感,我推荐使用SGD配合余弦退火或带热重启的调度器。
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts, OneCycleLR
def get_optimizer(model, lr=0.01, momentum=0.9, weight_decay=1e-4):
"""使用SGD优化器,对不同的参数组设置不同的权重衰减"""
# 将参数分为有BN层和无BN层两组
decay_params = []
no_decay_params = []
for name, param in model.named_parameters():
if not param.requires_grad:
continue
# 权重衰减不应用于BatchNorm的参数和偏置项
if 'bias' in name or 'bn' in name.lower() or 'norm' in name:
no_decay_params.append(param)
else:
decay_params.append(param)
param_groups = [
{'params': decay_params, 'weight_decay': weight_decay},
{'params': no_decay_params, 'weight_decay': 0.0}
]
optimizer = optim.SGD(param_groups, lr=lr, momentum=momentum)
return optimizer
def get_scheduler(optimizer, epochs, warmup_epochs=5, min_lr=1e-6):
"""余弦退火配合线性热启动"""
def warmup_cosine(epoch):
if epoch < warmup_epochs:
# 线性热启动
return (epoch + 1) / warmup_epochs
else:
# 余弦退火
progress = (epoch - warmup_epochs) / (epochs - warmup_epochs)
return 0.5 * (1 + math.cos(math.pi * progress))
scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=warmup_cosine)
return scheduler
3.3 训练循环实现
下面是一个完整的训练循环,包含了梯度累积、混合精度训练等实用技巧:
import time
from tqdm import tqdm
import numpy as np
class Trainer:
def __init__(self, model, train_loader, val_loader, device,
criterion, optimizer, scheduler, accumulation_steps=2):
self.model = model.to(device)
self.train_loader = train_loader
self.val_loader = val_loader
self.device = device
self.criterion = criterion
self.optimizer = optimizer
self.scheduler = scheduler
self.accumulation_steps = accumulation_steps
self.scaler = torch.cuda.amp.GradScaler() # 混合精度训练
# 记录训练历史
self.history = {
'train_loss': [], 'train_miou': [],
'val_loss': [], 'val_miou': [],
'lr': []
}
def compute_iou(self, pred, target, num_classes, ignore_index=255):
"""计算mIoU(平均交并比)"""
pred = pred.argmax(dim=1)
ious = []
for cls in range(num_classes):
if cls == ignore_index:
continue
pred_mask = (pred == cls)
target_mask = (target == cls)
intersection = (pred_mask & target_mask).sum().item()
union = (pred_mask | target_mask).sum().item()
if union == 0:
# 如果真实标签中没有该类,且预测也没有,则IoU为1
if intersection == 0:
ious.append(1.0)
else:
ious.append(0.0)
else:
ious.append(intersection / union)
return np.mean(ious)
def train_epoch(self, epoch):
self.model.train()
total_loss = 0
total_miou = 0
batch_count = 0
pbar = tqdm(self.train_loader, desc=f'Epoch {epoch+1} [Train]')
self.optimizer.zero_grad()
for batch_idx, (images, masks) in enumerate(pbar):
images = images.to(self.device)
masks = masks.to(self.device)
# 混合精度训练前向传播
with torch.cuda.amp.autocast():
outputs = self.model(images)
loss, main_loss, aux_loss = self.criterion(outputs, masks)
loss = loss / self.accumulation_steps # 梯度累积
# 反向传播
self.scaler.scale(loss).backward()
# 梯度累积:每accumulation_steps步更新一次参数
if (batch_idx + 1) % self.accumulation_steps == 0:
self.scaler.step(self.optimizer)
self.scaler.update()
self.optimizer.zero_grad()
# 计算指标
with torch.no_grad():
miou = self.compute_iou(outputs[0], masks, num_classes=33, ignore_index=30)
total_loss += loss.item() * self.accumulation_steps
total_miou += miou
batch_count += 1
# 更新进度条
pbar.set_postfix({
'loss': f'{loss.item() * self.accumulation_steps:.4f}',
'miou': f'{miou:.4f}',
'lr': f'{self.optimizer.param_groups[0]["lr"]:.6f}'
})
avg_loss = total_loss / batch_count
avg_miou = total_miou / batch_count
return avg_loss, avg_miou
@torch.no_grad()
def validate(self):
self.model.eval()
total_loss = 0
total_miou = 0
batch_count = 0
pbar = tqdm(self.val_loader, desc='Validation')
for images, masks in pbar:
images = images.to(self.device)
masks = masks.to(self.device)
outputs = self.model(images)
loss, main_loss, aux_loss = self.criterion(outputs, masks)
miou = self.compute_iou(outputs[0], masks, num_classes=33, ignore_index=30)
total_loss += loss.item()
total_miou += miou
batch_count += 1
pbar.set_postfix({
'val_loss': f'{loss.item():.4f}',
'val_miou': f'{miou:.4f}'
})
avg_loss = total_loss / batch_count
avg_miou = total_miou / batch_count
return avg_loss, avg_miou
def train(self, epochs, save_path='checkpoints'):
os.makedirs(save_path, exist_ok=True)
best_miou = 0
for epoch in range(epochs):
start_time = time.time()
# 训练一个epoch
train_loss, train_miou = self.train_epoch(epoch)
# 验证
val_loss, val_miou = self.validate()
# 更新学习率
self.scheduler.step()
# 记录历史
self.history['train_loss'].append(train_loss)
self.history['train_miou'].append(train_miou)
self.history['val_loss'].append(val_loss)
self.history['val_miou'].append(val_miou)
self.history['lr'].append(self.optimizer.param_groups[0]['lr'])
# 保存最佳模型
if val_miou > best_miou:
best_miou = val_miou
torch.save({
'epoch': epoch,
'model_state_dict': self.model.state_dict(),
'optimizer_state_dict': self.optimizer.state_dict(),
'scheduler_state_dict': self.scheduler.state_dict(),
'val_miou': val_miou,
'best_miou': best_miou,
}, os.path.join(save_path, 'best_model.pth'))
print(f'✓ 保存最佳模型,mIoU: {val_miou:.4f}')
# 定期保存检查点
if (epoch + 1) % 10 == 0:
torch.save({
'epoch': epoch,
'model_state_dict': self.model.state_dict(),
'optimizer_state_dict': self.optimizer.state_dict(),
'scheduler_state_dict': self.scheduler.state_dict(),
'val_miou': val_miou,
}, os.path.join(save_path, f'checkpoint_epoch_{epoch+1}.pth'))
epoch_time = time.time() - start_time
print(f'Epoch {epoch+1}/{epochs} - '
f'Train Loss: {train_loss:.4f}, Train mIoU: {train_miou:.4f} | '
f'Val Loss: {val_loss:.4f}, Val mIoU: {val_miou:.4f} | '
f'Time: {epoch_time:.1f}s | '
f'LR: {self.optimizer.param_groups[0]["lr"]:.6f}')
# 保存最终模型
torch.save(self.model.state_dict(), os.path.join(save_path, 'final_model.pth'))
return self.history
3.4 关键训练参数配置
根据我的经验,以下参数组合在Camvid数据集上效果较好:
| 参数 | 推荐值 | 说明 |
|---|---|---|
| 输入尺寸 | 448×448 | 平衡计算量和精度 |
| 批量大小 | 16 | 根据GPU内存调整,可用梯度累积模拟更大批量 |
| 初始学习率 | 0.01 | 使用线性热启动 |
| 优化器 | SGD | momentum=0.9, weight_decay=1e-4 |
| 学习率调度 | 余弦退火 | 配合5个epoch的热启动 |
| 训练轮数 | 200-300 | BiSeNetV2需要较长时间收敛 |
| 辅助损失权重 | [0.2, 0.2, 0.2, 0.2] | 四个辅助头均使用0.2权重 |
| 类别权重 | 见上文 | 处理类别不平衡 |
提示:如果训练初期出现NaN损失,可以尝试降低学习率或使用梯度裁剪。BiSeNetV2的深度可分离卷积对学习率比较敏感。
4. 结果可视化与模型部署
训练完成后,我们需要评估模型性能并将其部署到实际应用中。
4.1 性能评估与可视化
首先,让我们实现一个全面的评估函数,计算各种指标:
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix, classification_report
import pandas as pd
class Evaluator:
def __init__(self, num_classes=33, ignore_index=30):
self.num_classes = num_classes
self.ignore_index = ignore_index
self.confusion_matrix = np.zeros((num_classes, num_classes))
def update(self, pred, target):
"""更新混淆矩阵"""
pred = pred.argmax(dim=1).cpu().numpy().flatten()
target = target.cpu().numpy().flatten()
# 过滤掉忽略的像素
mask = (target != self.ignore_index)
pred = pred[mask]
target = target[mask]
# 更新混淆矩阵
cm = confusion_matrix(target, pred, labels=range(self.num_classes))
self.confusion_matrix += cm
def compute_metrics(self):
"""计算各种评估指标"""
cm = self.confusion_matrix
metrics = {}
# 逐类别IoU
ious = []
for i in range(self.num_classes):
if i == self.ignore_index:
continue
tp = cm[i, i]
fp = cm[:, i].sum() - tp
fn = cm[i, :].sum() - tp
if tp + fp + fn == 0:
iou = float('nan')
else:
iou = tp / (tp + fp + fn)
ious.append(iou)
metrics[f'IoU_class_{i}'] = iou
# mIoU(忽略NaN值)
valid_ious = [iou for iou in ious if not np.isnan(iou)]
metrics['mIoU'] = np.mean(valid_ious)
# 逐类别准确率
accuracies = []
for i in range(self.num_classes):
if i == self.ignore_index:
continue
tp = cm[i, i]
total = cm[i, :].sum()
if total == 0:
acc = float('nan')
else:
acc = tp / total
accuracies.append(acc)
metrics[f'Acc_class_{i}'] = acc
metrics['mean_acc'] = np.nanmean(accuracies)
# 整体像素准确率
total_correct = np.diag(cm).sum()
total_pixels = cm.sum()
metrics['pixel_acc'] = total_correct / total_pixels if total_pixels > 0 else 0
return metrics
def plot_confusion_matrix(self, class_names=None, figsize=(20, 16)):
"""绘制混淆矩阵热图"""
if class_names is None:
class_names = [f'Class_{i}' for i in range(self.num_classes)]
# 归一化混淆矩阵(按行)
cm_normalized = self.confusion_matrix.astype('float') / self.confusion_matrix.sum(axis=1)[:, np.newaxis]
cm_normalized = np.nan_to_num(cm_normalized)
plt.figure(figsize=figsize)
sns.heatmap(cm_normalized, annot=True, fmt='.2f', cmap='Blues',
xticklabels=class_names, yticklabels=class_names)
plt.title('Normalized Confusion Matrix')
plt.xlabel('Predicted')
plt.ylabel('True')
plt.tight_layout()
plt.show()
def generate_report(self, save_path='evaluation_report.csv'):
"""生成详细的评估报告"""
metrics = self.compute_metrics()
# 创建DataFrame
report_data = []
for i in range(self.num_classes):
if i == self.ignore_index:
continue
report_data.append({
'Class': i,
'Class_Name': f'Class_{i}',
'IoU': metrics.get(f'IoU_class_{i}', 0),
'Accuracy': metrics.get(f'Acc_class_{i}', 0),
'Pixel_Count': int(self.confusion_matrix[i, :].sum())
})
df = pd.DataFrame(report_data)
df = df.sort_values('IoU', ascending=False)
# 添加汇总行
summary_row = pd.DataFrame([{
'Class': 'All',
'Class_Name': 'SUMMARY',
'IoU': metrics['mIoU'],
'Accuracy': metrics['mean_acc'],
'Pixel_Count': int(self.confusion_matrix.sum())
}])
df = pd.concat([df, summary_row], ignore_index=True)
# 保存到CSV
df.to_csv(save_path, index=False)
# 打印关键指标
print(f"=== 评估结果 ===")
print(f"平均IoU (mIoU): {metrics['mIoU']:.4f}")
print(f"平均准确率: {metrics['mean_acc']:.4f}")
print(f"像素准确率: {metrics['pixel_acc']:.4f}")
print(f"最佳5个类别:")
top5 = df.nlargest(5, 'IoU')
for _, row in top5.iterrows():
print(f" 类别 {row['Class']}: IoU = {row['IoU']:.4f}")
print(f"最差5个类别:")
bottom5 = df.nsmallest(5, 'IoU')
for _, row in bottom5.iterrows():
print(f" 类别 {row['Class']}: IoU = {row['IoU']:.4f}")
return df
可视化预测结果对于理解模型行为至关重要:
def visualize_predictions(model, dataloader, device, num_samples=5):
"""可视化模型预测结果"""
model.eval()
fig, axes = plt.subplots(num_samples, 4, figsize=(20, 5*num_samples))
with torch.no_grad():
for idx, (images, masks) in enumerate(dataloader):
if idx >= num_samples:
break
images = images.to(device)
masks = masks.cpu().numpy()
# 预测
outputs = model(images)
preds = outputs[0].argmax(dim=1).cpu().numpy()
# 反归一化图像
mean = np.array([0.485, 0.456, 0.406]).reshape(1, 1, 3)
std = np.array([0.229, 0.224, 0.225]).reshape(1, 1, 3)
img_np = images[0].cpu().numpy().transpose(1, 2, 0)
img_np = img_np * std + mean
img_np = np.clip(img_np, 0, 1)
# 绘制
axes[idx, 0].imshow(img_np)
axes[idx, 0].set_title('Input Image')
axes[idx, 0].axis('off')
axes[idx, 1].imshow(masks[0], cmap='tab20', vmin=0, vmax=32)
axes[idx, 1].set_title('Ground Truth')
axes[idx, 1].axis('off')
axes[idx, 2].imshow(preds[0], cmap='tab20', vmin=0, vmax=32)
axes[idx, 2].set_title('Prediction')
axes[idx, 2].axis('off')
# 错误区域(红色为FP,蓝色为FN)
error_mask = np.zeros((*preds[0].shape, 3))
fp_mask = (preds[0] != masks[0]) & (masks[0] != 30) # 假阳性
fn_mask = (preds[0] != masks[0]) & (preds[0] != 30) # 假阴性
error_mask[fp_mask] = [1, 0, 0] # 红色
error_mask[fn_mask] = [0, 0, 1] # 蓝色
axes[idx, 3].imshow(img_np)
axes[idx, 3].imshow(error_mask, alpha=0.5)
axes[idx, 3].set_title('Errors (Red: FP, Blue: FN)')
axes[idx, 3].axis('off')
plt.tight_layout()
plt.show()
4.2 模型优化与部署
训练好的模型需要优化才能在实际应用中达到实时性能。以下是一些关键的优化技巧:
1. 模型剪枝与量化
import torch.quantization as quantization
def quantize_model(model, calibration_loader, device):
"""量化模型以减少内存占用和加速推理"""
model.eval()
model.qconfig = quantization.get_default_qconfig('fbgemm') # 针对CPU
# 对于移动端使用 'qnnpack'
# model.qconfig = quantization.get_default_qconfig('qnnpack')
# 准备量化
model_prepared = quantization.prepare(model)
# 校准(使用少量数据)
with torch.no_grad():
for images, _ in calibration_loader:
images = images.to(device)
_ = model_prepared(images)
# 转换为量化模型
model_quantized = quantization.convert(model_prepared)
return model_quantized
def prune_model(model, pruning_rate=0.3):
"""基于权重大小的剪枝"""
parameters_to_prune = []
for name, module in model.named_modules():
if isinstance(module, nn.Conv2d):
parameters_to_prune.append((module, 'weight'))
# 全局剪枝
pruning.global_unstructured(
parameters_to_prune,
pruning_method=pruning.L1Unstructured,
amount=pruning_rate,
)
# 移除剪枝掩码,使剪枝永久化
for module, param_name in parameters_to_prune:
pruning.remove(module, param_name)
return model
2. ONNX导出与优化
import onnx
import onnxruntime as ort
from onnxsim import simplify
def export_to_onnx(model, input_shape=(1, 3, 448, 448), onnx_path='bisenetv2.onnx'):
"""导出模型为ONNX格式"""
model.eval()
dummy_input = torch.randn(*input_shape)
# 导出原始ONNX
torch.onnx.export(
model,
dummy_input,
onnx_path,
input_names=['input'],
output_names=['output'],
opset_version=11,
dynamic_axes={'input': {0: 'batch_size'}, 'output': {0: 'batch_size'}}
)
# 简化模型
onnx_model = onnx.load(onnx_path)
model_simp, check = simplify(onnx_model)
assert check, "简化失败"
simplified_path = onnx_path.replace('.onnx', '_simplified.onnx')
onnx.save(model_simp, simplified_path)
print(f"模型已导出到: {simplified_path}")
print(f"原始大小: {os.path.getsize(onnx_path) / 1024 / 1024:.2f} MB")
print(f"简化后大小: {os.path.getsize(simplified_path) / 1024 / 1024:.2f} MB")
return simplified_path
def optimize_with_onnx_runtime(onnx_path):
"""使用ONNX Runtime优化模型"""
sess_options = ort.SessionOptions()
# 设置优化级别
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
# 设置执行提供者(优先使用GPU)
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
# 创建优化后的会话
session = ort.InferenceSession(onnx_path, sess_options, providers=providers)
# 测试推理速度
import time
dummy_input = np.random.randn(1, 3, 448, 448).astype(np.float32)
# 预热
for _ in range(10):
_ = session.run(None, {'input': dummy_input})
# 基准测试
times = []
for _ in range(100):
start = time.time()
_ = session.run(None, {'input': dummy_input})
times.append(time.time() - start)
avg_time = np.mean(times) * 1000 # 转换为毫秒
fps = 1000 / avg_time
print(f"平均推理时间: {avg_time:.2f} ms")
print(f"帧率: {fps:.1f} FPS")
return session
3. TensorRT加速(针对NVIDIA GPU)
import tensorrt as trt
def build_tensorrt_engine(onnx_path, engine_path='bisenetv2.engine',
max_batch_size=1, fp16_mode=True):
"""构建TensorRT引擎"""
logger = trt.Logger(trt.Logger.WARNING)
builder = trt.Builder(logger)
network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
parser = trt.OnnxParser(network, logger)
# 解析ONNX模型
with open(onnx_path, 'rb') as f:
if not parser.parse(f.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
return None
# 配置构建器
config = builder.create_builder_config()
config.max_workspace_size = 1 << 30 # 1GB
if fp16_mode and builder.platform_has_fast_fp16:
config.set_flag(trt.BuilderFlag.FP16)
# 设置动态形状
profile = builder.create_optimization_profile()
input_tensor = network.get_input(0)
input_shape = input_tensor.shape
# 最小、最优、最大批次大小
profile.set_shape(input_tensor.name,
(1, input_shape[1], input_shape[2], input_shape[3]), # 最小
(max_batch_size, input_shape[1], input_shape[2], input_shape[3]), # 最优
(max_batch_size, input_shape[1], input_shape[2], input_shape[3])) # 最大
config.add_optimization_profile(profile)
# 构建引擎
engine = builder.build_engine(network, config)
if engine is None:
print("引擎构建失败")
return None
# 保存引擎
with open(engine_path, 'wb') as f:
f.write(engine.serialize())
print(f"TensorRT引擎已保存到: {engine_path}")
print(f"引擎大小: {os.path.getsize(engine_path) / 1024 / 1024:.2f} MB")
return engine
4.3 实际部署考虑
在实际部署BiSeNetV2时,有几个关键点需要注意:
内存与计算优化表
| 优化技术 | 预期效果 | 适用场景 | 注意事项 |
|---|---|---|---|
| FP16量化 | 减少50%内存,加速20-30% | 支持FP16的GPU | 精度损失约0.5-1% mIoU |
| INT8量化 | 减少75%内存,加速2-3倍 | 边缘设备、移动端 | 需要校准数据集 |
| 通道剪枝 | 减少30-50%计算量 | 所有场景 | 需要重新微调 |
| 知识蒸馏 | 提升小模型精度 | 模型压缩 | 需要教师模型 |
| 图优化 | 加速10-20% | ONNX/TensorRT | 可能降低可移植性 |
部署代码示例
class BiSeNetV2Inference:
"""生产环境推理封装"""
def __init__(self, model_path, device='cuda', use_onnx=False, use_tensorrt=False):
self.device = device
self.use_onnx = use_onnx
self.use_tensorrt = use_tensorrt
if use_tensorrt:
# 初始化TensorRT推理
self.init_tensorrt(model_path)
elif use_onnx:
# 初始化ONNX Runtime推理
self.init_onnx(model_path)
else:
# 初始化PyTorch模型
self.init_pytorch(model_path)
# 预处理配置
self.mean = np.array([0.485, 0.456, 0.406]).reshape(1, 1, 3)
self.std = np.array([0.229, 0.224, 0.225]).reshape(1, 1, 3)
def init_pytorch(self, model_path):
"""加载PyTorch模型"""
self.model = BiSeNetV2(num_classes=33)
checkpoint = torch.load(model_path, map_location=self.device)
if 'model_state_dict' in checkpoint:
self.model.load_state_dict(checkpoint['model_state_dict'])
else:
self.model.load_state_dict(checkpoint)
self.model.to(self.device)
self.model.eval()
def preprocess(self, image):
"""预处理输入图像"""
# 调整大小并归一化
if len(image.shape) == 3:
image = cv2.resize(image, (448, 448))
image = image / 255.0
image = (image - self.mean) / self.std
image = image.transpose(2, 0, 1) # HWC -> CHW
image = np.expand_dims(image, axis=0) # 添加批次维度
return image.astype(np.float32)
def postprocess(self, output, original_size):
"""后处理输出"""
# 取主输出并上采样到原始尺寸
if isinstance(output, list) or isinstance(output, tuple):
output = output[0]
# 转换为类别索引
if isinstance(output, torch.Tensor):
output = output.argmax(dim=1).squeeze().cpu().numpy()
else:
output = output.argmax(axis=1).squeeze()
# 调整到原始图像大小
output = cv2.resize(output, (original_size[1], original_size[0]),
interpolation=cv2.INTER_NEAREST)
return output
def predict(self, image):
"""执行推理"""
original_size = image.shape[:2]
# 预处理
input_tensor = self.preprocess(image)
# 推理
with torch.no_grad():
if self.use_onnx or self.use_tensorrt:
output = self.session.run(None, {'input': input_tensor})[0]
else:
input_tensor = torch.from_numpy(input_tensor).to(self.device)
output = self.model(input_tensor)
# 后处理
result = self.postprocess(output, original_size)
return result
def benchmark(self, warmup=100, iterations=1000):
"""性能基准测试"""
dummy_input = np.random.randn(1, 3, 448, 448).astype(np.float32)
# 预热
for _ in range(warmup):
_ = self.predict(np.random.rand(448, 448, 3))
# 正式测试
times = []
for _ in range(iterations):
start = time.time()
_ = self.predict(np.random.rand(448, 448, 3))
times.append(time.time() - start)
avg_time = np.mean(times) * 1000 # 毫秒
fps = 1000 / avg_time
print(f"平均推理时间: {avg_time:.2f} ms")
print(f"帧率: {fps:.1f} FPS")
print(f"峰值内存占用: {torch.cuda.max_memory_allocated() / 1024**2:.1f} MB")
return avg_time, fps
部署最佳实践
- 批处理优化:对于视频流处理,尽量使用批处理以提高吞吐量。
- 异步推理:使用多线程或异步队列处理输入输出,避免阻塞。
- 内存池:预分配内存以减少动态分配开销。
- 模型预热:在正式服务前进行几次推理,让CUDA内核和内存分配稳定。
- 监控与降级:实现健康检查,在GPU内存不足时自动降级到CPU推理。
我在实际项目中发现,经过适当优化的BiSeNetV2在NVIDIA Jetson Nano上可以达到15-20 FPS,在RTX 3080上可以达到200+ FPS,完全满足实时语义分割的需求。关键是要根据目标硬件选择合适的优化组合,并在精度和速度之间找到最佳平衡点。
9421


&spm=1001.2101.3001.11974&articleId=150678869&d=1&t=3&u=9eaa2514ceb34484951085a56cdd63c8)

被折叠的 条评论
为什么被折叠?



