蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 7 系列分类头核对(含 Swin 勘误)、三策略与两阶段微调实验

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。explore-transfer-learning.py
explore-transfer-learning.py308 行
"""Independent offline PyTorch + TorchVision 0.25 transfer-learning strategies lab."""
import argparse
import hashlib
import json
import platform
from pathlib import Path

import numpy as np
import PIL
from PIL import Image, ImageDraw
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.utils.data import DataLoader, Dataset
import torchvision
from torchvision import models, transforms
from torchvision.models import ResNet50_Weights


class BinaryShapesDataset(Dataset):
    """Offline synthetic binary RGB dataset for two-stage transfer learning verification."""

    def __init__(self, count: int, seed: int, transform=None):
        self.transform = transform
        self.images = []
        self.labels = []
        rng = np.random.default_rng(seed)
        for i in range(count):
            cls = i % 2
            bg = tuple(int(v) for v in rng.integers(20, 50, size=3))
            img = Image.new("RGB", (64, 64), bg)
            draw = ImageDraw.Draw(img)
            dx, dy = int(rng.integers(-6, 7)), int(rng.integers(-6, 7))
            if cls == 0:
                draw.rectangle([14 + dx, 14 + dy, 50 + dx, 50 + dy], fill=(220, 65, 65))
            else:
                draw.ellipse([14 + dx, 14 + dy, 50 + dx, 50 + dy], fill=(55, 165, 225))
            self.images.append(img)
            self.labels.append(cls)

    def __len__(self) -> int:
        return len(self.labels)

    def __getitem__(self, idx: int):
        img = self.images[idx]
        if self.transform is not None:
            img = self.transform(img)
        return img, self.labels[idx]


def build_transfer_model(arch: str, num_classes: int, dropout: float = 0.2) -> nn.Module:
    """Correct classifier-head replacement across ResNet, EfficientNet, MobileNet, DenseNet, ConvNeXt, ViT, Swin."""
    model = getattr(models, arch)(weights=None)
    name = arch.lower()
    if "resnet" in name or "resnext" in name or "regnet" in name:
        model.fc = nn.Sequential(nn.Dropout(dropout), nn.Linear(model.fc.in_features, num_classes))
    elif "efficientnet" in name or "mobilenet" in name or "convnext" in name or "vgg" in name or "alexnet" in name:
        in_f = model.classifier[-1].in_features
        model.classifier[-1] = nn.Linear(in_f, num_classes)
    elif "densenet" in name:
        model.classifier = nn.Linear(model.classifier.in_features, num_classes)
    elif "vit" in name:
        model.heads.head = nn.Linear(model.heads.head.in_features, num_classes)
    elif "swin" in name:
        # Swin Transformer uses model.head (NOT model.heads.head!)
        model.head = nn.Linear(model.head.in_features, num_classes)
    else:
        raise ValueError(f"Unsupported architecture: {arch}")
    return model


class TransferWithAttention(nn.Module):
    def __init__(self, num_classes: int = 4, dropout: float = 0.2):
        super().__init__()
        backbone = models.resnet18(weights=None)
        self.backbone = nn.Sequential(*list(backbone.children())[:-1])
        self.feat_dim = 512
        self.attention = nn.Sequential(
            nn.Linear(self.feat_dim, 128), nn.Tanh(), nn.Linear(128, 1), nn.Sigmoid(),
        )
        self.classifier = nn.Sequential(
            nn.Dropout(dropout), nn.Linear(self.feat_dim, 64), nn.ReLU(), nn.Linear(64, num_classes),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        feat = self.backbone(x).flatten(1)
        return self.classifier(feat * self.attention(feat))


def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def run_cases(fig_dir: Path | None):
    torch.manual_seed(2026)
    cases = []
    figures = {}

    # 1. Inspect classifier head attribute names across 7 TorchVision families (catching Swin model.head vs ViT model.heads.head)
    arches = ("resnet18", "mobilenet_v3_small", "efficientnet_b0", "densenet121", "convnext_tiny", "swin_t", "vit_b_16")
    out_shapes = {}
    swin_has_heads = hasattr(models.swin_t(weights=None), "heads")
    swin_has_head = hasattr(models.swin_t(weights=None), "head")
    dummy_224 = torch.randn(1, 3, 224, 224)
    for arch in ("resnet18", "mobilenet_v3_small", "efficientnet_b0", "swin_t"):
        mod = build_transfer_model(arch, num_classes=5).eval()
        with torch.inference_mode():
            out_shapes[arch] = list(mod(dummy_224).shape)
    # Also verify densenet121, convnext_tiny, vit_b_16 head replacement attribute without heavy 224 forward
    d_mod = build_transfer_model("densenet121", num_classes=5)
    c_mod = build_transfer_model("convnext_tiny", num_classes=5)
    v_mod = build_transfer_model("vit_b_16", num_classes=5)
    heads_ok = (d_mod.classifier.out_features == 5 and c_mod.classifier[-1].out_features == 5 and v_mod.heads.head.out_features == 5)
    c1_ok = (not swin_has_heads) and swin_has_head and all(v == [1, 5] for v in out_shapes.values()) and heads_ok
    cases.append(dict(
        name="classifier_head_mapping_and_swin_fix",
        inputs=dict(architectures=list(arches), target_classes=5),
        prerequisites="离线实例化 7 类视觉骨干(weights=None),核对各分类头属性名",
        action="验证 ResNet/MobileNet/EfficientNet/DenseNet/ConvNeXt/ViT/Swin 替换分类头,并确认 Swin 使用 model.head 而非 model.heads.head。",
        expected=dict(swin_lacks_heads=True, swin_has_head=True, all_4_forward_5cls=True, other_3_heads_5cls=True),
        actual=dict(swin_lacks_heads=not swin_has_heads, swin_has_head=swin_has_head, all_4_forward_5cls=all(v == [1, 5] for v in out_shapes.values()), other_3_heads_5cls=heads_ok),
        measurements=dict(verified_forward_shapes=out_shapes),
        passed=c1_ok,
    ))

    # 2. Official weights.transforms() inspection offline + ImageNet normalization pipeline
    official_tf = ResNet50_Weights.IMAGENET1K_V2.transforms()
    sample_im = BinaryShapesDataset(2, seed=1)[0][0]
    official_out = official_tf(sample_im)
    custom_val_tf = transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
    ])
    custom_out = custom_val_tf(sample_im)
    c2_ok = list(official_out.shape) == [3, 224, 224] and list(custom_out.shape) == [3, 224, 224]
    cases.append(dict(
        name="official_weights_transforms_offline",
        inputs=dict(weights_enum="ResNet50_Weights.IMAGENET1K_V2"),
        prerequisites="weights.transforms() 仅读取元数据构建预处理,无需下载权重",
        action="验证官方推荐预处理与手动 ImageNet 均值方差流水线均输出 [3, 224, 224] 张量。",
        expected=dict(official_shape=[3, 224, 224], custom_shape=[3, 224, 224]),
        actual=dict(official_shape=list(official_out.shape), custom_shape=list(custom_out.shape)),
        passed=c2_ok,
    ))

    # 3. Three strategies: freeze all (feature extraction), partial unfreeze (layer4 + fc), differential LR groups
    m_s = models.resnet18(weights=None)
    for p in m_s.parameters():
        p.requires_grad = False
    m_s.fc = nn.Linear(m_s.fc.in_features, 5)
    fe_trainable = sum(p.numel() for p in m_s.parameters() if p.requires_grad)
    for p in m_s.layer4.parameters():
        p.requires_grad = True
    partial_trainable = sum(p.numel() for p in m_s.parameters() if p.requires_grad)
    total_params = sum(p.numel() for p in m_s.parameters())
    diff_opt = optim.Adam([
        {"params": m_s.fc.parameters(), "lr": 1e-3},
        {"params": [p for n, p in m_s.named_parameters() if not n.startswith("fc")], "lr": 1e-5},
    ])
    c3_ok = fe_trainable == 512 * 5 + 5 and fe_trainable < partial_trainable < total_params and len(diff_opt.param_groups) == 2
    cases.append(dict(
        name="three_transfer_strategies_params",
        inputs=dict(backbone="resnet18", num_classes=5),
        prerequisites="依次切换全冻结特征提取、解冻 layer4 部分微调及差异化学习率参数组",
        action="核对三阶段可训练参数量递增与参数组学习率配置。",
        expected=dict(head_only_params=2565, partial_gt_head=True, partial_lt_total=True, diff_groups=2),
        actual=dict(head_only_params=fe_trainable, partial_gt_head=partial_trainable > fe_trainable, partial_lt_total=partial_trainable < total_params, diff_groups=len(diff_opt.param_groups)),
        measurements=dict(total_params=total_params, head_only=fe_trainable, layer4_plus_head=partial_trainable),
        passed=c3_ok,
    ))

    # 4. Two-stage training (Stage 1: head-only frozen backbone; Stage 2: unfreeze layer4 + differential LR)
    torch.manual_seed(42)
    tr_tf = transforms.Compose([
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
    ])
    va_tf = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
    ])
    tr_ds = BinaryShapesDataset(80, seed=10, transform=tr_tf)
    va_ds = BinaryShapesDataset(32, seed=20, transform=va_tf)
    tr_loader = DataLoader(tr_ds, batch_size=16, shuffle=True, generator=torch.Generator().manual_seed(3))
    va_loader = DataLoader(va_ds, batch_size=32, shuffle=False)

    net = models.resnet18(weights=None)
    for p in net.parameters():
        p.requires_grad = False
    net.fc = nn.Linear(net.fc.in_features, 2)
    l4_before_s1 = net.layer4[0].conv1.weight.detach().clone()
    opt = optim.AdamW([
        {"params": net.fc.parameters(), "lr": 5e-3},
        {"params": net.layer4.parameters(), "lr": 5e-4},
    ], weight_decay=1e-4)
    sch = CosineAnnealingLR(opt, T_max=8, eta_min=1e-5)
    crit = nn.CrossEntropyLoss(label_smoothing=0.05)

    stage_losses = []
    l4_changed_s1 = False
    for ep in range(1, 9):
        if ep == 5:
            for p in net.layer4.parameters():
                p.requires_grad = True
        net.train()
        ep_l = 0.0
        for bx, by in tr_loader:
            opt.zero_grad(set_to_none=True)
            loss = crit(net(bx), by)
            loss.backward()
            nn.utils.clip_grad_norm_(net.parameters(), max_norm=1.0)
            opt.step()
            ep_l += float(loss.item()) * bx.size(0)
        sch.step()
        stage_losses.append(round(ep_l / len(tr_ds), 5))
        if ep == 4:
            l4_changed_s1 = float((net.layer4[0].conv1.weight - l4_before_s1).abs().max().item()) > 0.0
    l4_changed_s2 = float((net.layer4[0].conv1.weight - l4_before_s1).abs().max().item()) > 1e-5
    net.eval()
    with torch.inference_mode():
        vx, vy = next(iter(va_loader))
        val_acc = round(float((net(vx).argmax(dim=1) == vy).float().mean().item()), 4)
    c4_ok = (not l4_changed_s1) and l4_changed_s2 and stage_losses[-1] < stage_losses[0] and val_acc >= 0.90
    cases.append(dict(
        name="two_stage_freeze_then_unfreeze",
        inputs=dict(stage1_epochs=4, stage2_epochs=4, train_samples=80, val_samples=32),
        prerequisites="阶段一冻结主干仅训 fc,第 5 轮解冻 layer4 以分层学习率联合微调",
        action="验证阶段一 layer4 权重纹丝不动、阶段二解冻更新且验证准确率达标。",
        expected=dict(stage1_layer4_frozen=True, stage2_layer4_updated=True, loss_dropped=True, val_acc_ge_90=True),
        actual=dict(stage1_layer4_frozen=not l4_changed_s1, stage2_layer4_updated=l4_changed_s2, loss_dropped=stage_losses[-1] < stage_losses[0], val_acc_ge_90=val_acc >= 0.90),
        measurements=dict(ep1_loss=stage_losses[0], ep4_loss=stage_losses[3], ep8_loss=stage_losses[-1], val_acc=val_acc),
        passed=c4_ok,
    ))

    # 5. Custom intermediate feature extractor + attention gate (TransferWithAttention)
    att_net = TransferWithAttention(num_classes=4).eval()
    with torch.inference_mode():
        att_out = att_net(torch.randn(2, 3, 64, 64))
    c5_ok = list(att_out.shape) == [2, 4]
    cases.append(dict(
        name="custom_attention_transfer_head",
        inputs=dict(input_shape=[2, 3, 64, 64], feat_dim=512, num_classes=4),
        prerequisites="移除主干分类头后串联自定义注意力门控与两层分类头",
        action="验证自定义迁移特征提取+注意力加权模块前向输出 [2, 4]。",
        expected=dict(out_shape=[2, 4]),
        actual=dict(out_shape=list(att_out.shape)),
        passed=c5_ok,
    ))

    # 6. Plot two-stage loss curve
    if fig_dir is not None:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        fig_dir.mkdir(parents=True, exist_ok=True)
        fig, ax = plt.subplots(figsize=(6.8, 3.5), dpi=140)
        ep_xs = list(range(1, 9))
        ax.plot(ep_xs, stage_losses, marker="o", color="#174d79", linewidth=2, label="Train Loss")
        ax.axvline(4.5, color="#ae511d", linestyle="--", label="Unfreeze layer4 (Epoch 5)")
        ax.set_title(f"Two-Stage Transfer Learning Loss (Val Acc: {val_acc*100:.1f}%)", fontsize=10)
        ax.set_xlabel("Epoch")
        ax.set_ylabel("Cross-Entropy Loss (Label Smoothing 0.05)")
        ax.grid(True, alpha=0.3)
        ax.legend(fontsize=8)
        fig.tight_layout()
        out_png = fig_dir / "transfer-two-stage-loss.png"
        fig.savefig(out_png)
        plt.close(fig)
        figures["transfer-two-stage-loss.png"] = sha(out_png)
        mpl_ver = matplotlib.__version__
    else:
        mpl_ver = None

    cases.append(dict(
        name="observed_transfer_loss_plot",
        inputs=dict(epochs=8),
        prerequisites="两阶段冻结与解冻训练损失历史",
        action="绘制 8 轮两阶段迁移训练损失曲线 PNG。",
        expected=dict(epochs_plotted=8),
        actual=dict(epochs_plotted=len(stage_losses)),
        measurements=dict(figure_generated="transfer-two-stage-loss.png" in figures),
        passed=len(stage_losses) == 8,
    ))

    payload = dict(
        version=platform.python_version(),
        torch=torch.__version__,
        torchvision=torchvision.__version__,
        pillow=PIL.__version__,
        system=platform.system(),
        cases=cases,
    )
    if mpl_ver:
        payload["matplotlib"] = mpl_ver
        payload["figures"] = figures
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--figures", type=Path, default=None)
    args = parser.parse_args()
    run_cases(args.figures)
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

入口文件:projects/pytorch-transfer-learning-lab/explore-transfer-learning.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-transfer-learning.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a442.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习