181 lines
6.0 KiB
Python
181 lines
6.0 KiB
Python
"""
|
||
MobileNetV2 模型定义
|
||
支持标准训练和量化训练
|
||
|
||
功能说明:
|
||
1. MobileNetV2Classifier: 标准分类模型,用于训练阶段
|
||
2. QuantizedMobileNetV2: 量化感知训练模型,用于FPGA部署前的训练
|
||
3. create_model: 工厂函数,统一创建模型接口
|
||
|
||
模型架构:
|
||
- 基础网络:MobileNetV2 (轻量级卷积神经网络)
|
||
- 分类头:Dropout(0.2) + Linear(1280 -> num_classes)
|
||
- 输入:3通道RGB图像 (224x224)
|
||
- 输出:10类光瓣数量的概率分布
|
||
"""
|
||
import torch
|
||
import torch.nn as nn
|
||
import torchvision.models as models
|
||
|
||
|
||
class MobileNetV2Classifier(nn.Module):
|
||
"""
|
||
基于MobileNetV2的光图像分类器
|
||
|
||
用途:识别大气湍流影响下的光束传输图像中的光瓣数量
|
||
|
||
架构说明:
|
||
- 使用预训练的MobileNetV2作为特征提取器
|
||
- 替换最后的分类层以适应10类光瓣分类任务
|
||
- 添加Dropout防止过拟合
|
||
|
||
参数:
|
||
num_classes (int): 分类类别数,默认10(对应1-10个光瓣)
|
||
pretrained (bool): 是否使用ImageNet预训练权重,默认True
|
||
"""
|
||
def __init__(self, num_classes=10, pretrained=True):
|
||
super(MobileNetV2Classifier, self).__init__()
|
||
|
||
# 加载预训练的MobileNetV2骨干网络
|
||
# pretrained=True时会下载ImageNet预训练权重,有助于加速收敛
|
||
self.mobilenet = models.mobilenet_v2(pretrained=pretrained)
|
||
|
||
# 获取原始分类层的输入特征维度(MobileNetV2为1280)
|
||
in_features = self.mobilenet.classifier[1].in_features
|
||
|
||
# 替换分类头以适应我们的任务
|
||
# Dropout(0.2): 随机丢弃20%的神经元,防止过拟合
|
||
# Linear: 全连接层,将1280维特征映射到num_classes个类别
|
||
self.mobilenet.classifier = nn.Sequential(
|
||
nn.Dropout(0.2),
|
||
nn.Linear(in_features, num_classes)
|
||
)
|
||
|
||
def forward(self, x):
|
||
"""
|
||
前向传播
|
||
|
||
参数:
|
||
x (Tensor): 输入图像张量,形状为 [batch_size, 3, 224, 224]
|
||
|
||
返回:
|
||
Tensor: 分类logits,形状为 [batch_size, num_classes]
|
||
"""
|
||
return self.mobilenet(x)
|
||
|
||
|
||
class QuantizedMobileNetV2(nn.Module):
|
||
"""
|
||
量化感知训练版本的MobileNetV2
|
||
|
||
用途:在训练过程中模拟量化效果,为FPGA部署做准备
|
||
|
||
量化说明:
|
||
- 使用QAT (Quantization-Aware Training) 方法
|
||
- 在训练时插入伪量化节点,模拟INT8量化的精度损失
|
||
- 训练后可直接转换为真正的INT8量化模型
|
||
|
||
与标准模型的区别:
|
||
- 添加了量化配置 (qconfig)
|
||
- 使用 prepare_qat 准备量化感知训练
|
||
- 支持层融合 (Conv+BN+ReLU) 以提高推理速度
|
||
|
||
参数:
|
||
num_classes (int): 分类类别数,默认10
|
||
pretrained (bool): 是否使用预训练权重,默认True
|
||
"""
|
||
def __init__(self, num_classes=10, pretrained=True):
|
||
super(QuantizedMobileNetV2, self).__init__()
|
||
|
||
# 加载预训练的MobileNetV2骨干网络
|
||
self.model = models.mobilenet_v2(pretrained=pretrained)
|
||
|
||
# 修改分类层以适应光瓣分类任务
|
||
in_features = self.model.classifier[1].in_features
|
||
self.model.classifier = nn.Sequential(
|
||
nn.Dropout(0.2),
|
||
nn.Linear(in_features, num_classes)
|
||
)
|
||
|
||
# 配置量化参数
|
||
# 'fbgemm': 针对x86 CPU优化的量化后端
|
||
# 注意:如果目标是ARM架构(如PYNQ Z2),应使用 'qnnpack'
|
||
self.model.qconfig = torch.quantization.get_default_qat_qconfig('fbgemm')
|
||
|
||
# 准备量化感知训练
|
||
# inplace=True: 直接修改模型,不创建副本
|
||
# 这会在模型中插入伪量化节点(FakeQuantize),模拟量化效果
|
||
torch.quantization.prepare_qat(self.model, inplace=True)
|
||
|
||
def forward(self, x):
|
||
"""
|
||
前向传播
|
||
|
||
参数:
|
||
x (Tensor): 输入图像张量,形状为 [batch_size, 3, 224, 224]
|
||
|
||
返回:
|
||
Tensor: 分类logits,形状为 [batch_size, num_classes]
|
||
"""
|
||
return self.model(x)
|
||
|
||
def fuse_model(self):
|
||
"""
|
||
融合Conv+BN+ReLU层以提高推理速度
|
||
|
||
层融合说明:
|
||
- 将卷积、批归一化、激活函数融合为单个操作
|
||
- 减少内存访问次数,提高推理速度
|
||
- 必须在量化之前调用
|
||
|
||
注意:此方法需要根据具体的模型结构调整
|
||
当前实现是一个示例,可能需要针对MobileNetV2的具体结构进行修改
|
||
"""
|
||
for m in self.model.modules():
|
||
if type(m) == nn.Sequential:
|
||
torch.quantization.fuse_modules(m, [['0', '1', '2']], inplace=True)
|
||
|
||
|
||
def create_model(num_classes=10, pretrained=True, quantized=False):
|
||
"""
|
||
创建模型的工厂函数
|
||
|
||
这是统一的模型创建接口,根据参数返回不同类型的模型
|
||
|
||
参数:
|
||
num_classes (int): 分类类别数,默认10(对应1-10个光瓣)
|
||
pretrained (bool): 是否使用ImageNet预训练权重,默认True
|
||
quantized (bool): 是否创建量化感知训练模型,默认False
|
||
|
||
返回:
|
||
model (nn.Module): 创建的模型实例
|
||
|
||
使用示例:
|
||
# 创建标准训练模型
|
||
model = create_model(num_classes=10, pretrained=True)
|
||
|
||
# 创建量化感知训练模型
|
||
qat_model = create_model(num_classes=10, pretrained=True, quantized=True)
|
||
"""
|
||
if quantized:
|
||
return QuantizedMobileNetV2(num_classes, pretrained)
|
||
else:
|
||
return MobileNetV2Classifier(num_classes, pretrained)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
# 测试模型创建和前向传播
|
||
print("=" * 50)
|
||
print("测试标准MobileNetV2模型")
|
||
print("=" * 50)
|
||
|
||
model = create_model(num_classes=10, pretrained=False)
|
||
x = torch.randn(1, 3, 224, 224) # 模拟一个batch的输入
|
||
y = model(x)
|
||
|
||
print(f"输入形状: {x.shape}")
|
||
print(f"输出形状: {y.shape}")
|
||
print(f"模型参数量: {sum(p.numel() for p in model.parameters()) / 1e6:.2f}M")
|
||
print(f"输出类别数: {y.shape[1]}")
|
||
|