第三部分:数据处理
3.1 数据集类
# src/data/dataset.py
"""
PyTorch数据集类
负责加载图片、应用数据增强、返回模型输入
"""
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from pathlib import Path
from PIL import Image
import json
from typing import Tuple, Dict, List, Optional
import random
from src.utils.logger import logger
class ProductDataset(Dataset):
"""
商品分类数据集
特性:
1. 支持训练/验证/测试三种模式
2. 训练模式应用数据增强
3. 支持类别权重计算(处理不平衡数据)
4. 支持缓存预处理后的图片
"""
def __init__(
self,
data_dir: Path,
mode: str = 'train',
image_size: int = 224,
use_cache: bool = False,
class_to_idx: Optional[Dict[str, int]] = None
):
"""
初始化数据集
Args:
data_dir: 数据根目录
mode: 模式(train/val/test)
image_size: 目标图片尺寸
use_cache: 是否缓存预处理后的图片
class_to_idx: 类别到索引的映射(测试模式需要)
"""
self.data_dir = Path(data_dir)
self.mode = mode
self.image_size = image_size
self.use_cache = use_cache
self.cache = {} if use_cache else None
# 获取所有图片路径和标签
self.samples = []
if mode == 'test':
# 测试模式:没有标签,需要从文件名推断
self.class_to_idx = class_to_idx
self.idx_to_class = {v: k for k, v in class_to_idx.items()}
for img_path in (data_dir / 'test').glob('*/*.jpg'):
self.samples.append((str(img_path), None))
else:
# 训练/验证模式:有标签
self.class_to_idx = {}
for class_dir in sorted((data_dir / mode).iterdir()):
if class_dir.is_dir():
class_name = class_dir.name
if class_name not in self.class_to_idx:
self.class_to_idx[class_name] = len(self.class_to_idx)
for img_path in class_dir.glob('*.jpg'):
self.samples.append((str(img_path), class_name))
self.idx_to_class = {v: k for k, v in self.class_to_idx.items()}
# 保存类别映射
self.num_classes = len(self.class_to_idx)
# 构建变换
self.transform = self._build_transform()
logger.info(f"Dataset initialized: mode={mode}, size={len(self.samples)}, "
f"classes={self.num_classes}")
def _build_transform(self):
"""构建数据变换"""
if self.mode == 'train':
# 训练模式:更强的数据增强
return transforms.Compose([
transforms.Resize((self.image_size, self.image_size)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomRotation(degrees=15),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
])
else:
# 验证/测试模式:只做基本变换
return transforms.Compose([
transforms.Resize((self.image_size, self.image_size)),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
])
def __len__(self) -> int:
return len(self.samples)
def __getitem__(self, idx: int) -> Tuple[torch.Tensor, Optional[int]]:
"""
获取单个样本
Returns:
image: 预处理后的图片张量 [3, H, W]
label: 类别索引(测试模式可能为None)
"""
img_path, label_name = self.samples[idx]
# 检查缓存
if self.use_cache and img_path in self.cache:
image = self.cache[img_path]
else:
# 加载图片
image = Image.open(img_path).convert('RGB')
# 应用变换
image = self.transform(image)
# 缓存
if self.use_cache:
self.cache[img_path] = image
# 转换标签
if label_name is not None:
label = self.class_to_idx[label_name]
else:
label = -1 # 测试模式无标签
return image, label
def get_class_weights(self) -> torch.Tensor:
"""
计算类别权重(用于处理不平衡数据)
Returns:
每个类别的权重张量
"""
if self.mode != 'train':
raise ValueError("Class weights only available for train mode")
# 统计每个类别的样本数
class_counts = {}
for _, label_name in self.samples:
class_counts[label_name] = class_counts.get(label_name, 0) + 1
# 计算权重:样本数越少的类别权重越大
total = sum(class_counts.values())
weights = []
for class_name in self.class_to_idx.keys():
count = class_counts.get(class_name, 0)
weight = total / (len(self.class_to_idx) * count) if count > 0 else 0
weights.append(weight)
return torch.tensor(weights, dtype=torch.float32)
def save_class_mapping(self, save_path: Path):
"""保存类别映射"""
with open(save_path, 'w') as f:
json.dump(self.class_to_idx, f, indent=2)
logger.info(f"Class mapping saved to {save_path}")
@staticmethod
def load_class_mapping(load_path: Path) -> Dict[str, int]:
"""加载类别映射"""
with open(load_path, 'r') as f:
return json.load(f)
3.2 数据增强
# src/data/augmentations.py
"""
高级数据增强
使用albumentations库实现更丰富的数据增强策略
"""
import albumentations as A
from albumentations.pytorch import ToTensorV2
import cv2
import numpy as np
def get_train_augmentations(image_size: int = 224):
"""
训练数据增强
包含多种增强策略,提高模型泛化能力
"""
return A.Compose([
# 几何变换
A.RandomResizedCrop(image_size, image_size, scale=(0.8, 1.0)),
A.HorizontalFlip(p=0.5),
A.Rotate(limit=30, p=0.5),
# 颜色变换
A.ColorJitter(
brightness=0.2,
contrast=0.2,
saturation=0.2,
hue=0.1,
p=0.5
),
A.RandomBrightnessContrast(p=0.3),
A.HueSaturationValue(p=0.3),
# 模糊和噪声
A.GaussianBlur(blur_limit=(3, 7), p=0.2),
A.GaussNoise(var_limit=(10, 50), p=0.2),
# 其他
A.CLAHE(clip_limit=2.0, tile_grid_size=(8, 8), p=0.2),
A.CoarseDropout(
max_holes=8,
max_height=32,
max_width=32,
fill_value=0,
p=0.3
),
# 归一化
A.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
),
ToTensorV2(),
])
def get_val_augmentations(image_size: int = 224):
"""
验证数据增强
只做必要的变换,不改变原始图片内容
"""
return A.Compose([
A.Resize(image_size, image_size),
A.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
),
ToTensorV2(),
])
class MixupAugmentation:
"""
Mixup数据增强
原理:将两张图片按一定比例混合,标签也按同样比例混合
效果:提高模型鲁棒性,减少过拟合
公式:
x_mix = λ * x_i + (1 - λ) * x_j
y_mix = λ * y_i + (1 - λ) * y_j
"""
def __init__(self, alpha: float = 0.2):
"""
Args:
alpha: Beta分布参数,控制混合比例
"""
self.alpha = alpha
def __call__(self, batch):
"""
对一批数据应用Mixup
Args:
batch: (images, labels) 元组
Returns:
混合后的(images, labels)
"""
images, labels = batch
if self.alpha > 0:
lam = np.random.beta(self.alpha, self.alpha)
else:
lam = 1
batch_size = images.size(0)
index = torch.randperm(batch_size)
mixed_images = lam * images + (1 - lam) * images[index]
mixed_labels = lam * labels + (1 - lam) * labels[index]
return mixed_images, mixed_labels
class CutMixAugmentation:
"""
CutMix数据增强
原理:将一张图片的矩形区域裁剪下来粘贴到另一张图片上
效果:比Mixup更适合图像分类任务
"""
def __init__(self, alpha: float = 1.0):
self.alpha = alpha
def rand_bbox(self, size, lam):
"""生成随机裁剪区域"""
W = size[2]
H = size[3]
cut_rat = np.sqrt(1. - lam)
cut_w = int(W * cut_rat)
cut_h = int(H * cut_rat)
cx = np.random.randint(W)
cy = np.random.randint(H)
bbx1 = np.clip(cx - cut_w // 2, 0, W)
bby1 = np.clip(cy - cut_h // 2, 0, H)
bbx2 = np.clip(cx + cut_w // 2, 0, W)
bby2 = np.clip(cy + cut_h // 2, 0, H)
return bbx1, bby1, bbx2, bby2
def __call__(self, batch):
images, labels = batch
batch_size = images.size(0)
lam = np.random.beta(self.alpha, self.alpha)
rand_index = torch.randperm(batch_size)
bbx1, bby1, bbx2, bby2 = self.rand_bbox(images.size(), lam)
# 替换区域
images[:, :, bbx1:bbx2, bby1:bby2] = images[rand_index, :, bbx1:bbx2, bby1:bby2]
# 调整标签
lam_adjusted = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (images.size(-1) * images.size(-2)))
mixed_labels = lam_adjusted * labels + (1 - lam_adjusted) * labels[rand_index]
return images, mixed_labels
第四部分:模型定义
4.1 模型架构
# src/models/efficientnet.py
"""
EfficientNet模型实现
EfficientNet通过神经网络架构搜索(NAS)找到的最优缩放策略,
在精度和效率之间取得了极好的平衡。
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
from typing import Dict, Optional, Tuple
class EfficientNetClassifier(nn.Module):
"""
EfficientNet分类器
使用ImageNet预训练的EfficientNet-B0作为骨干网络,
添加分类头进行微调。
为什么选择EfficientNet-B0?
- 参数量小(约5M),适合部署
- 精度高(ImageNet Top-1 77.1%)
- 推理速度快
"""
def __init__(
self,
num_classes: int,
model_name: str = 'efficientnet_b0',
pretrained: bool = True,
dropout_rate: float = 0.2
):
super().__init__()
# 加载预训练模型
if model_name == 'efficientnet_b0':
self.backbone = models.efficientnet_b0(pretrained=pretrained)
in_features = self.backbone.classifier[1].in_features
elif model_name == 'efficientnet_b1':
self.backbone = models.efficientnet_b1(pretrained=pretrained)
in_features = self.backbone.classifier[1].in_features
else:
raise ValueError(f"Unsupported model: {model_name}")
# 替换分类头
self.backbone.classifier = nn.Sequential(
nn.Dropout(p=dropout_rate),
nn.Linear(in_features, num_classes)
)
self.num_classes = num_classes
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
前向传播
Args:
x: 输入图片 [B, 3, H, W]
Returns:
logits: 分类分数 [B, num_classes]
"""
return self.backbone(x)
def extract_features(self, x: torch.Tensor) -> torch.Tensor:
"""
提取特征向量(去除分类头)
用于特征提取或迁移学习
"""
# 获取特征图
features = self.backbone.features(x)
# 全局平均池化
features = self.backbone.avgpool(features)
features = torch.flatten(features, 1)
return features
def get_embedding(self, x: torch.Tensor) -> torch.Tensor:
"""获取嵌入向量(用于相似度搜索)"""
return F.normalize(self.extract_features(x), p=2, dim=1)
class MultiHeadEfficientNet(nn.Module):
"""
多任务EfficientNet
同时预测多个任务:
- 主类别(masterCategory)
- 子类别(subCategory)
- 性别(gender)
- 季节(season)
"""
def __init__(
self,
num_master_classes: int,
num_sub_classes: int,
num_gender_classes: int = 3,
num_season_classes: int = 4,
backbone: str = 'efficientnet_b0'
):
super().__init__()
# 共享骨干网络
if backbone == 'efficientnet_b0':
base_model = models.efficientnet_b0(pretrained=True)
in_features = base_model.classifier[1].in_features
else:
raise ValueError(f"Unsupported backbone: {backbone}")
self.features = base_model.features
self.avgpool = base_model.avgpool
# 多个任务头
self.master_head = nn.Linear(in_features, num_master_classes)
self.sub_head = nn.Linear(in_features, num_sub_classes)
self.gender_head = nn.Linear(in_features, num_gender_classes)
self.season_head = nn.Linear(in_features, num_season_classes)
def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]:
"""多任务前向传播"""
# 共享特征提取
features = self.features(x)
features = self.avgpool(features)
features = torch.flatten(features, 1)
# 各任务分支
return {
'master': self.master_head(features),
'sub': self.sub_head(features),
'gender': self.gender_head(features),
'season': self.season_head(features),
}
4.2 模型集成
# src/models/ensemble.py
"""
模型集成
通过组合多个模型的预测结果,提高准确率和鲁棒性。
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import List, Dict, Optional
from collections import OrderedDict
class ModelEnsemble(nn.Module):
"""
模型集成器
支持多种集成策略:
- 投票法(Voting):每个模型投票,得票最多的类别获胜
- 平均法(Averaging):对预测概率取平均
- 加权平均(Weighted Averaging):根据验证准确率加权
- 堆叠法(Stacking):使用元学习器组合
"""
def __init__(
self,
models: List[nn.Module],
weights: Optional[List[float]] = None,
strategy: str = 'averaging'
):
"""
Args:
models: 模型列表
weights: 模型权重(用于weighted_averaging)
strategy: 集成策略(voting/averaging/weighted_averaging/stacking)
"""
super().__init__()
self.models = nn.ModuleList(models)
self.weights = weights
self.strategy = strategy
if strategy == 'stacking':
# 堆叠法需要额外的元学习器
self.meta_learner = nn.Linear(len(models), len(models[0].num_classes))
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""集成预测"""
predictions = []
for model in self.models:
model.eval()
with torch.no_grad():
logits = model(x)
probs = F.softmax(logits, dim=1)
predictions.append(probs)
# 堆叠预测
predictions = torch.stack(predictions, dim=1) # [B, num_models, num_classes]
if self.strategy == 'voting':
# 投票法:取每个样本预测概率最高的类别
pred_classes = predictions.argmax(dim=2) # [B, num_models]
ensemble_pred = torch.mode(pred_classes, dim=1).values
return F.one_hot(ensemble_pred, num_classes=predictions.size(2)).float()
elif self.strategy == 'averaging':
# 平均法:取所有模型概率的平均值
return predictions.mean(dim=1)
elif self.strategy == 'weighted_averaging' and self.weights is not None:
# 加权平均
weights = torch.tensor(self.weights, device=x.device)
weights = weights.view(1, -1, 1) # [1, num_models, 1]
return (predictions * weights).sum(dim=1)
elif self.strategy == 'stacking':
# 堆叠法:使用元学习器
features = predictions.view(predictions.size(0), -1)
return self.meta_learner(features)
else:
raise ValueError(f"Unsupported strategy: {self.strategy}")
class SnapshotEnsemble:
"""
快照集成
在训练过程中保存多个检查点(快照),
最后使用这些快照进行集成预测。
优点:
- 不需要额外训练
- 利用不同收敛状态的模型多样性
"""
def __init__(self, model_class, snapshot_paths: List[str], **model_kwargs):
self.models = []
for path in snapshot_paths:
model = model_class(**model_kwargs)
model.load_state_dict(torch.load(path))
model.eval()
self.models.append(model)
def predict(self, x: torch.Tensor) -> torch.Tensor:
"""集成预测"""
predictions = []
for model in self.models:
with torch.no_grad():
logits = model(x)
probs = F.softmax(logits, dim=1)
predictions.append(probs)
return torch.stack(predictions, dim=1).mean(dim=1)