AI4M
AI for Materials Science 材料人工智能实战课程 · 研究生课程门户

07b · 卷积神经网络与材料显微图像(SEM/金相)智能分析

课件文件:07b_cnn_microstructure.ipynb(628.9 KB)

Open In Colab

07b · 卷积神经网络与材料显微图像(SEM/金相)智能分析

在 07a 中我们看到,当输入是预先算好的 17 个分子描述符时,多层感知机(MLP)受限于手工特征的信息瓶颈,表现与随机森林相差无几。然而在材料科学实验室中,大量核心表征数据并非表格数字,而是二维高维空间场——例如扫描电镜(SEM)、透射电镜(TEM)、光学金相显微镜以及原子力显微镜(AFM)拍摄的显微组织图像。

材料的“工艺—微结构—性能”关系决定了显微组织形貌(如球状碳化物析出、层片状珠光体、凝固树枝晶或晶界网络)直接控制着合金的屈服强度、断裂韧性与耐蚀性。传统金相分析依赖人工截线法或手工设计纹理统计量,不仅耗时费力,而且极易受光照不均与成像噪声干扰。

本节我们将引入专为网格拓扑数据设计的卷积神经网络(Convolutional Neural Networks, CNN),展示它如何利用局部连接、权重共享与空间池化三大机制,直接从原始像素矩阵中自动学习多尺度微结构特征,完成金相组织分类与析出相定量分析。

本节大纲

  1. 为什么普通 MLP 不适合处理材料显微图像?(参数爆炸与平移敏感性)
  2. 二维卷积运算的物理直觉:平滑滤波与 Sobel 相界边缘检测
  3. PyTorch CNN 核心组件:nn.Conv2d、填充、步幅、池化与特征图尺寸推导
  4. 四类典型材料显微组织分类实战:CNN vs. 展平 MLP 与旋转不变性增强
  5. 打开 CNN 黑箱:中间层特征图可视化与析出相面积分数(Area Fraction)定量统计
  6. 小样本电镜迁移学习实战:冻结预训练卷积主干与两阶段微调(2-Stage Fine-Tuning)
In [1] · Python
import os
import copy
import warnings
warnings.filterwarnings("ignore")

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.model_selection import train_test_split

import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset

%matplotlib inline
plt.rcParams["figure.dpi"] = 110

def set_seed(seed=42):
    torch.manual_seed(seed)
    np.random.seed(seed)
    torch.use_deterministic_algorithms(True)

set_seed(42)
print("PyTorch version:", torch.__version__)
Out:
PyTorch version: 2.8.0+cpu

📘 课程统一绘图风格:下面这格加载课程自带的 ai4m.mplstyle(配色与课程网站同源,无上右边框,仅横向浅网格,保存默认 300 dpi)。C 是课程配色,手动指定颜色时写 color=C.crimson。

In [2] · Python
# ai4m-style:课程统一绘图风格(本地与 Colab 通用)
import pathlib, sys

sys.path.insert(0, str(pathlib.Path.cwd().parent))   # course/ 根目录
import ai4m_style as ai4m

C = ai4m.use()        # 应用 ai4m.mplstyle,返回课程配色

1. 为什么普通 MLP 不适合处理材料显微图像?

一张单通道灰度电镜图像在计算机中表示为一个二维矩阵 \(\mathbf{I} \in \mathbb{R}^{H \times W}\),每个元素对应像素点的背散射或二次电子强度(通常归一化到 \([0, 1]\))。

如果照搬 07a 的多层感知机,必须先把二维图像按行展平(Flatten)为一维长向量:

  1. 参数量灾难:即便是一张中等分辨率的 \(256 \times 256\) 电镜图,展平后也有 \(65,536\) 维。若第一个隐藏层有 512 个神经元,仅第一层权重矩阵就有 \(65,536 \times 512 \approx 3.35 \times 10^7\)(三千三百多万)个参数,在几百张电镜照片的小样本上瞬间过拟合。
  2. 破坏二维空间拓扑与平移不变性(Translation Invariance):在展平向量中,原本上下相邻的像素被拆散到相距 \(W\) 个元素的位置。更重要的是,金相视场中同一颗析出相颗粒无论出现在左上角还是右下角,其物相属性完全相同;但对全连接层而言,平移几个像素就意味着激活了完全不同的一组输入权重,模型不得不为每个位置重新学习一遍识别规则。

为了解决这两个根本缺陷,我们需要一种只在局部邻域内提取模式,并将同一套检测算子在整个视场平面上滑动复用的运算——这就是二维卷积。


2. 二维卷积运算:从经典滤波到相界边缘提取

给定输入图像 \(I(i, j)\) 与一个尺寸为 \(k_h \times k_w\) 的小矩阵 \(K\)(称为卷积核 Kernel 或滤波器 Filter),二维离散互相关(深度学习中通称二维卷积)定义为卷积核在图像上逐像素滑动时的局部内积:

\[(I * K)(i, j) = \sum_{u=0}^{k_h-1} \sum_{v=0}^{k_w-1} I(i + u, j + v) \cdot K(u, v)\]

不同的卷积核权重对应着截然不同的物理特征提取器:

  • 平滑均值核(Box Blur):邻域权重全部为 \(1/9\),抑制电子束散粒噪声;
  • 水平/垂直 Sobel 核:通过一阶差分近似局部灰度梯度 \(\partial I / \partial x\) 与 \(\partial I / \partial y\),高亮出基体与第二相之间的相界(Phase Boundary);
  • 拉普拉斯核(Laplacian):中心为 \(+4\)、四邻域为 \(-1\),对应二阶算子 \(\nabla^2 I\),对细小析出相颗粒边缘高度敏感。

下面我们生成一张含球状析出相与成像噪声的合成 SEM 微结构图,并用 PyTorch 的函数式接口 F.conv2d 演示这三种经典卷积核的响应效果。

In [3] · Python
# 生成一张 64x64 的合成双相显微图像(暗色基体 + 亮色球状析出相 + 成像噪声)
rng = np.random.RandomState(0)
yy, xx = np.mgrid[0:64, 0:64]
sample_img = np.full((64, 64), 0.2, dtype=np.float32)
centers = [(18, 20, 7), (44, 18, 6), (28, 45, 8), (49, 48, 5)]
for cy, cx, r in centers:
    mask = (yy - cy) ** 2 + (xx - cx) ** 2 <= r ** 2
    sample_img[mask] = 0.85
sample_img = gaussian_filter(sample_img, sigma=0.8) + rng.normal(0, 0.05, (64, 64)).astype(np.float32)
sample_img = np.clip(sample_img, 0.0, 1.0)

# PyTorch 图像张量形状约定为 (Batch, Channels, Height, Width)
img_t = torch.tensor(sample_img).unsqueeze(0).unsqueeze(0)  # (1, 1, 64, 64)

k_blur = torch.ones((1, 1, 3, 3)) / 9.0
k_sobel_x = torch.tensor([[[[-1.0, 0.0, 1.0],
                            [-2.0, 0.0, 2.0],
                            [-1.0, 0.0, 1.0]]]])
k_laplace = torch.tensor([[[[ 0.0, -1.0,  0.0],
                            [-1.0,  4.0, -1.0],
                            [ 0.0, -1.0,  0.0]]]])

out_blur = F.conv2d(img_t, k_blur, padding=1).squeeze().numpy()
out_sobel = F.conv2d(img_t, k_sobel_x, padding=1).squeeze().numpy()
out_laplace = F.conv2d(img_t, k_laplace, padding=1).squeeze().numpy()

fig, axes = plt.subplots(1, 4, figsize=(12, 3.2))
titles = ["Original SEM (Noisy)", "3x3 Box Blur", "Sobel Vertical Edge", "Laplacian Boundary"]
cmaps = ["gray", "gray", "coolwarm", "coolwarm"]
for ax, arr, title, cm in zip(axes, [sample_img, out_blur, out_sobel, out_laplace], titles, cmaps):
    ax.imshow(arr, cmap=cm)
    ax.set_title(title, fontsize=10)
    ax.axis("off")
plt.tight_layout()
plt.show()
Out:
Notebook 输出图像

在传统数字图像处理中,Sobel 或 Laplacian 核里面的 9 个数字是工程师手工指定的;而在卷积神经网络(CNN)中,卷积核的权重全部设为 requires_grad=True 的可学习参数,由反向传播算法根据下游分类或回归任务的目标函数自动学习出最适合当前材料体系的滤波器组。


3. PyTorch CNN 核心组件与特征图尺寸推导

一个标准的二维卷积神经网络由以下几类层交替堆叠而成:

  1. 二维卷积层 nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0):
    • in_channels (\(C_{\text{in}}\)):输入通道数(单通道电镜灰度图为 1,RGB 彩色金相图为 3,中间层则为上一层输出的特征图数目);
    • out_channels (\(C_{\text{out}}\)):并行学习的卷积核个数,每个卷积核生成一张二维特征图(Feature Map);
    • padding (\(p\)):在图像四周补零的圈数。当 kernel_size=3, stride=1, padding=1 时,卷积前后特征图的高宽保持不变(称为 same padding);
    • 通用输出高宽公式:
      \[H_{\text{out}} = \left\lfloor \frac{H_{\text{in}} + 2p - k}{s} \right\rfloor + 1\]
  2. 空间下采样层 nn.MaxPool2d(kernel_size=2, stride=2):
    • 在每个 \(2\times 2\) 局部窗口内取最大值,将特征图高宽减半(\(64\times 64 \to 32\times 32\))。这既降低了计算量,又使后续卷积层在同样的 \(3\times 3\) 窗口下能够覆盖更大物理尺度的微结构区域(扩大感受野 Receptive Field),并对微小局部形变保持鲁棒。
  3. 全局自适应平均池化 nn.AdaptiveAvgPool2d((1, 1)):
    • 对最后一层每个通道的整张特征图求空间平均值,将形状从 \((B, C, H', W')\) 直接浓缩为 \((B, C, 1, 1)\)。由于空间求和/求平均对微结构特征出现的位置不敏感,这一步赋予了整个网络天然的全局平移不变性,同时省去了庞大的全连接展平层。

下面我们在一个张量上追踪各层输出的形状变化:

In [4] · Python
x_demo = torch.zeros(4, 1, 64, 64)  # Batch=4, Channel=1, 64x64 image

conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=3, padding=1)
pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=1)
gap = nn.AdaptiveAvgPool2d((1, 1))

h1 = torch.relu(conv1(x_demo))
h1_pool = pool1(h1)
h2 = torch.relu(conv2(h1_pool))
h_gap = gap(h2).squeeze(-1).squeeze(-1)

print("Input shape:          ", x_demo.shape)
print("After Conv1 (3x3, p=1):", h1.shape)
print("After MaxPool (2x2):   ", h1_pool.shape)
print("After Conv2 (3x3, p=1):", h2.shape)
print("After GlobalAvgPool:   ", h_gap.shape)
Out:
Input shape:           torch.Size([4, 1, 64, 64])
After Conv1 (3x3, p=1): torch.Size([4, 16, 64, 64])
After MaxPool (2x2):    torch.Size([4, 16, 32, 32])
After Conv2 (3x3, p=1): torch.Size([4, 32, 32, 32])
After GlobalAvgPool:    torch.Size([4, 32])

练习 07b-1:计算卷积层参数量与输出空间尺寸

假设输入为一批单通道 \(64\times 64\) 显微图像张量,形状为 (8, 1, 64, 64):

  1. 创建一个卷积层 nn.Conv2d(in_channels=1, out_channels=24, kernel_size=5, stride=2, padding=0);
  2. 先根据公式手算该层输出张量的空间高宽 \(H_{\text{out}} \times W_{\text{out}}\) 以及可训练参数总数(每个卷积核有 \(C_{\text{in}} \times k_h \times k_w\) 个权重加 1 个偏置),然后编写代码验证你的手算结果。
In [5] · Python
# 练习 07b-1:在此编写代码

4. 四类典型材料金相/显微组织分类实战

4.1 构建合成材料微结构图像数据集

为了让实验在本地与 Colab CPU 上都能在数秒内完成,我们基于物理数学模型合成一个包含 4 类典型材料微结构的基准数据集(共 600 张 \(48\times 48\) 灰度显微图,每类 150 张,均带有随机取向、相位偏移与高斯电子噪声):

  1. Spherical Precipitates(球状析出相):模拟时效强化合金中的球形第二相颗粒(如 \(\gamma'\) 相或球化渗碳体),随机分布在不同坐标与半径;
  2. Lamellar Pearlite(层片状共析组织):模拟共析钢中的珠光体或层状共晶组织,具有随机旋转取向角 \(\theta \in [0, \pi)\) 与不同层片间距;
  3. Dendritic Solidification(枝晶凝固组织):模拟铸造合金凝固过程中的正交一次与二次树枝晶干及分枝扰动;
  4. Grain-Boundary Network(多晶晶界网络):基于随机晶核 Voronoi 距离场生成的等轴晶粒与亮色晶界网络。
In [6] · Python
CLASS_NAMES = [
    "0: Spherical Precipitates",
    "1: Lamellar Pearlite",
    "2: Dendritic Solidification",
    "3: Grain-Boundary Network",
]

def generate_microstructure_dataset(n_per_class=150, size=48, seed=42):
    rng = np.random.RandomState(seed)
    yy, xx = np.mgrid[0:size, 0:size].astype(np.float32) / size
    images, labels = [], []

    for cls in range(4):
        for _ in range(n_per_class):
            if cls == 0:  # Spherical precipitates
                img = np.full((size, size), 0.18, dtype=np.float32)
                n_blobs = rng.randint(5, 11)
                for _ in range(n_blobs):
                    cy, cx = rng.uniform(0.12, 0.88, size=2)
                    r = rng.uniform(0.06, 0.13)
                    img[(yy - cy) ** 2 + (xx - cx) ** 2 <= r ** 2] = rng.uniform(0.75, 0.95)
                img = gaussian_filter(img, sigma=0.7)

            elif cls == 1:  # Lamellar pearlite
                theta = rng.uniform(0, np.pi)
                freq = rng.uniform(5.0, 9.0)
                phase = rng.uniform(0, 2 * np.pi)
                coord = xx * np.cos(theta) + yy * np.sin(theta)
                warp = 0.03 * np.sin(2 * np.pi * ( -xx * np.sin(theta) + yy * np.cos(theta)) * 2.0)
                wave = np.sin(2 * np.pi * freq * (coord + warp) + phase)
                img = (wave > 0.0).astype(np.float32) * 0.7 + 0.15
                img = gaussian_filter(img, sigma=0.65)

            elif cls == 2:  # Dendritic solidification
                theta = rng.choice([0.0, np.pi / 4, np.pi / 6, np.pi / 3]) + rng.uniform(-0.1, 0.1)
                u = (xx - 0.5) * np.cos(theta) + (yy - 0.5) * np.sin(theta)
                v = -(xx - 0.5) * np.sin(theta) + (yy - 0.5) * np.cos(theta)
                trunk1 = np.exp(-(u ** 2) / 0.004) * (0.6 + 0.4 * np.cos(2 * np.pi * 7.0 * v))
                trunk2 = np.exp(-(v ** 2) / 0.004) * (0.6 + 0.4 * np.cos(2 * np.pi * 7.0 * u))
                sec_arms = 0.45 * np.exp(-(np.sin(2 * np.pi * 5.0 * u) ** 2) / 0.08) * np.exp(-(v ** 2) / 0.06)
                img = np.clip(0.15 + 0.75 * np.maximum(np.maximum(trunk1, trunk2), sec_arms), 0.0, 1.0)
                img = gaussian_filter(img, sigma=0.5)

            else:  # Grain-boundary network (Voronoi ridges)
                n_seeds = rng.randint(10, 16)
                pts = rng.uniform(0.05, 0.95, size=(n_seeds, 2)).astype(np.float32)
                dists = np.sqrt((yy[:, :, None] - pts[:, 0]) ** 2 + (xx[:, :, None] - pts[:, 1]) ** 2)
                sorted_d = np.sort(dists, axis=-1)
                ridge = sorted_d[:, :, 1] - sorted_d[:, :, 0]
                img = np.exp(-ridge / 0.022).astype(np.float32) * 0.75 + 0.15

            noise = rng.normal(0.0, 0.06, size=(size, size)).astype(np.float32)
            images.append(np.clip(img + noise, 0.0, 1.0))
            labels.append(cls)

    X_img = np.array(images, dtype=np.float32)[:, None, :, :]  # (N, 1, H, W)
    y_lbl = np.array(labels, dtype=np.int64)
    return X_img, y_lbl

X_img, y_lbl = generate_microstructure_dataset()
print("Dataset X shape:", X_img.shape, "| y shape:", y_lbl.shape)

fig, axes = plt.subplots(1, 4, figsize=(12, 3.2))
for cls_idx, ax in enumerate(axes):
    sample_idx = np.where(y_lbl == cls_idx)[0][0]
    ax.imshow(X_img[sample_idx, 0], cmap="gray", vmin=0, vmax=1)
    ax.set_title(CLASS_NAMES[cls_idx], fontsize=9.5)
    ax.axis("off")
plt.suptitle("Synthetic Metallographic / SEM Microstructure Dataset (4 Classes)", y=1.02)
plt.tight_layout()
plt.show()
Out:
Dataset X shape: (600, 1, 48, 48) | y shape: (600,)
Notebook 输出图像

4.2 划分数据集并对比展平 MLP 与 CNN

我们将 600 张微结构图像按分层抽样(stratify=y_lbl)划分为训练集(384 张)、验证集(96 张)与独立测试集(120 张)。

为了直观验证卷积归纳偏置的威力,我们在同一份数据上对比两个模型:

  1. 展平多层感知机 FlattenedMLP:将 \(48\times 48 = 2304\) 个像素直接展平后送入两层全连接网络(含约 15 万个参数);
  2. 卷积神经网络 MicrostructureCNN:由三层 \(3\times 3\) 卷积 + ReLU + 最大池化/全局平均池化组成(仅含约 1.4 万个参数,不到 MLP 的十分之一)。

多分类任务使用交叉熵损失函数 nn.CrossEntropyLoss(),模型输出层维度为类别数 4(对应 4 个类别的未归一化 Logits)。

In [7] · Python
X_trval, X_te, y_trval, y_te = train_test_split(
    X_img, y_lbl, test_size=0.2, stratify=y_lbl, random_state=42
)
X_tr, X_va, y_tr, y_va = train_test_split(
    X_trval, y_trval, test_size=0.2, stratify=y_trval, random_state=42
)

Xtr_t, Xva_t, Xte_t = (torch.tensor(a, dtype=torch.float32) for a in (X_tr, X_va, X_te))
ytr_t, yva_t, yte_t = (torch.tensor(a, dtype=torch.long) for a in (y_tr, y_va, y_te))

train_loader = DataLoader(TensorDataset(Xtr_t, ytr_t), batch_size=32, shuffle=True)
print(f"Train: {len(Xtr_t)} | Valid: {len(Xva_t)} | Test: {len(Xte_t)}")
Out:
Train: 384 | Valid: 96 | Test: 120
In [8] · Python
class FlattenedMLP(nn.Module):
    def __init__(self, img_size=48, hidden_size=64, n_classes=4):
        super().__init__()
        self.net = nn.Sequential(
            nn.Flatten(),
            nn.Linear(img_size * img_size, hidden_size),
            nn.ReLU(),
            nn.Linear(hidden_size, hidden_size),
            nn.ReLU(),
            nn.Linear(hidden_size, n_classes),
        )

    def forward(self, x):
        return self.net(x)


class MicrostructureCNN(nn.Module):
    def __init__(self, n_classes=4):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),                     # 48x48 -> 24x24
            nn.Conv2d(16, 32, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),                     # 24x24 -> 12x12
            nn.Conv2d(32, 32, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.AdaptiveAvgPool2d((1, 1)),        # 12x12 -> 1x1 (Global Average Pooling)
        )
        self.classifier = nn.Linear(32, n_classes)

    def forward(self, x):
        h = self.features(x).flatten(1)
        return self.classifier(h)


mlp_img = FlattenedMLP()
cnn_img = MicrostructureCNN()
print("FlattenedMLP 参数量:     ", sum(p.numel() for p in mlp_img.parameters()))
print("MicrostructureCNN 参数量:", sum(p.numel() for p in cnn_img.parameters()))
Out:
FlattenedMLP 参数量:      151940
MicrostructureCNN 参数量: 14180
In [9] · Python
ce_loss = nn.CrossEntropyLoss()

def evaluate_acc(model, X, y):
    model.eval()
    with torch.no_grad():
        preds = model(X).argmax(dim=1)
        return (preds == y).float().mean().item()

def train_classifier(model, loader, n_epochs=35, lr=2e-3):
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    history = {"train_acc": [], "valid_acc": []}
    best_acc, best_state = -1.0, None
    for epoch in range(n_epochs):
        model.train()
        for xb, yb in loader:
            loss = ce_loss(model(xb), yb)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
        tr_acc = evaluate_acc(model, Xtr_t, ytr_t)
        va_acc = evaluate_acc(model, Xva_t, yva_t)
        history["train_acc"].append(tr_acc)
        history["valid_acc"].append(va_acc)
        if va_acc > best_acc:
            best_acc = va_acc
            best_state = copy.deepcopy(model.state_dict())
    model.load_state_dict(best_state)
    return history

set_seed(42)
mlp_img = FlattenedMLP()
hist_mlp = train_classifier(mlp_img, train_loader, n_epochs=35, lr=1e-3)

set_seed(42)
cnn_img = MicrostructureCNN()
hist_cnn = train_classifier(cnn_img, train_loader, n_epochs=35, lr=3e-3)

print(f"FlattenedMLP 测试集准确率:      {evaluate_acc(mlp_img, Xte_t, yte_t) * 100:.1f}%")
print(f"MicrostructureCNN 测试集准确率: {evaluate_acc(cnn_img, Xte_t, yte_t) * 100:.1f}%")

fig, ax = plt.subplots(figsize=(6.2, 3.6))
ax.plot(hist_mlp["valid_acc"], "--", lw=1.8, label="Flattened MLP (Valid Acc)")
ax.plot(hist_cnn["valid_acc"], "-", lw=2.2, label="Microstructure CNN (Valid Acc)")
ax.set_xlabel("Epoch")
ax.set_ylabel("Validation Accuracy")
ax.set_title("Microstructure Classification: CNN vs. Flattened MLP")
ax.legend(loc="lower right")
plt.tight_layout()
plt.show()
Out:
FlattenedMLP 测试集准确率:      87.5%
MicrostructureCNN 测试集准确率: 100.0%
Notebook 输出图像

对比结果非常鲜明:

  • 展平 MLP 虽然拥有 15 万个参数,并能将训练集准确率刷到接近 100%,但在测试集上由于析出相位置、层片取向和晶界拓扑随样本不断平移变化,泛化准确率大幅跌落;
  • MicrostructureCNN 仅用 1.4 万个参数(不到 MLP 的 1/10),依靠局部卷积滤波器提取边缘、条纹周期和节点交叉特征,并通过全局平均池化消除了空间位置依赖,在测试集上轻松达到接近 98%–100% 的分类准确率。

4.3 物理合理的显微图像数据增强(Data Augmentation)

在材料实验表征中,样品放入电镜样品台时的面内旋转角度(\(90^\circ, 180^\circ, 270^\circ\))或水平/垂直镜像翻转,完全不会改变材料的物相与热处理状态。因此,在训练时对每个小批量图像随机施加 90° 整数倍旋转(torch.rot90)与镜像翻转(torch.flip),相当于免费扩充了 8 倍符合物理对称性的训练样本。

但需要特别警惕违背物理规律的增强操作:如果研究目标是定量测定晶粒尺寸或层片间距,且所有电镜图都在固定放大倍数(标尺 Scale Bar 固定)下拍摄,那么随意进行大比例随机缩放裁剪(Random Resized Crop)就会篡改真实的物理特征尺度,导致模型判断失真。

练习 07b-2:实现旋转与翻转不变的数据增强函数

请编写一个函数 augment_batch(xb),对输入形状为 (B, C, H, W) 的图像批次执行:

  1. 随机抽取 \(k \in \{0, 1, 2, 3\}\),调用 torch.rot90(xb, k=k, dims=(2, 3)) 做 \(k \times 90^\circ\) 面内旋转;
  2. 以 0.5 的概率调用 torch.flip(xb, dims=(3,)) 做水平翻转。 在一张层片状珠光体样本上调用该函数 4 次并并排可视化。
In [10] · Python
# 练习 07b-2:在此编写代码

5. 打开 CNN 黑箱:特征图可视化与析出相定量统计

5.1 卷积神经网络究竟学到了什么特征?

为了避免将 CNN 当作不可解释的黑箱,我们可以取四类显微组织各一张代表性样品,送入训练好的 cnn_img 第一层卷积 + ReLU,直接观察前 4 个通道激活的特征图(Feature Maps)。

In [11] · Python
cnn_img.eval()
first_conv_relu = cnn_img.features[:2]  # Conv2d(1, 16) + ReLU

fig, axes = plt.subplots(4, 5, figsize=(11, 8.2))
for cls_idx in range(4):
    sample_idx = np.where(y_te == cls_idx)[0][0]
    x_single = Xte_t[sample_idx : sample_idx + 1]
    with torch.no_grad():
        fmap = first_conv_relu(x_single).squeeze(0).numpy()  # (16, 48, 48)

    axes[cls_idx, 0].imshow(x_single[0, 0].numpy(), cmap="gray")
    axes[cls_idx, 0].set_title(f"Input Class {cls_idx}", fontsize=9)
    axes[cls_idx, 0].axis("off")

    for ch in range(4):
        axes[cls_idx, ch + 1].imshow(fmap[ch], cmap="viridis")
        axes[cls_idx, ch + 1].set_title(f"Filter {ch}", fontsize=9)
        axes[cls_idx, ch + 1].axis("off")

plt.suptitle("First-Layer Learned Feature Maps Across 4 Microstructure Classes", y=1.01)
plt.tight_layout()
plt.show()
Out:
Notebook 输出图像

从第一层特征图可以清楚地看到,CNN 自发分化出了职责不同的物理检测器:有的通道专门高亮亮色相的内部区域(球状析出相与枝晶干响应强烈),有的通道专门提取特定倾角的相界梯度(珠光体层片边缘与多晶晶界网络清晰浮现)。

5.2 从定性分类到定量金相:析出相面积分数(Area Fraction)回归

在体视学(Stereology)原理中,截面金相图上的第二相**面积分数(Area Fraction, \(A_A\))**是三维体积分数(Volume Fraction, \(V_V\))的无偏估计,直接决定弥散强化合金的 Orowan 强化增量。除定性分类外,只需将 MicrostructureCNN 最后一层的输出维度改为 1 并配合 nn.MSELoss(),网络就能直接从含噪电镜图像中端到端预测析出相面积分数。

练习 07b-3:用 CNN 端到端回归球状析出相面积分数

下方代码已为你生成了 240 张具有不同颗粒密度与尺寸的球状析出相显微图 X_af 及其真实面积分数标签 y_af(取值约 \(0.05 \sim 0.45\))。请完成以下步骤:

  1. 实例化一个 MicrostructureCNN(n_classes=1) 并将输出 .squeeze(1) 作为面积分数预测值;
  2. 使用 Adam(lr=3e-3)与 nn.MSELoss() 在前 180 张训练集上训练 30 轮;
  3. 在后 60 张测试集上计算预测面积分数的平均绝对误差(MAE),并绘制真实面积分数 vs. 预测面积分数的对角线散点图(Parity Plot)。
In [12] · Python
# 数据准备:生成 240 张球状析出相图像及其真实面积分数标签 y_af
def make_precipitate_area_dataset(n_samples=240, size=48, seed=123):
    rng = np.random.RandomState(seed)
    yy, xx = np.mgrid[0:size, 0:size].astype(np.float32) / size
    imgs, area_fracs = [], []
    for _ in range(n_samples):
        mask = np.zeros((size, size), dtype=bool)
        n_blobs = rng.randint(2, 16)
        for _ in range(n_blobs):
            cy, cx = rng.uniform(0.1, 0.9, size=2)
            r = rng.uniform(0.05, 0.14)
            mask |= ((yy - cy) ** 2 + (xx - cx) ** 2 <= r ** 2)
        area_fracs.append(float(mask.mean()))
        img = np.where(mask, 0.85, 0.18).astype(np.float32)
        img = gaussian_filter(img, sigma=0.7) + rng.normal(0, 0.05, (size, size)).astype(np.float32)
        imgs.append(np.clip(img, 0.0, 1.0))
    return torch.tensor(np.array(imgs)[:, None, :, :]), torch.tensor(area_fracs, dtype=torch.float32)

X_af, y_af = make_precipitate_area_dataset()
X_af_tr, X_af_te = X_af[:180], X_af[180:]
y_af_tr, y_af_te = y_af[:180], y_af[180:]
print("Area fraction range:", round(y_af.min().item(), 3), "to", round(y_af.max().item(), 3))

# 练习 07b-3:在此编写训练与评估代码
Out:
Area fraction range: 0.023 to 0.436

6. 小样本电镜迁移学习与两阶段微调(Transfer Learning & Fine-Tuning)

在前面的合成基准里,我们拥有几百张清晰标注的金相图像,从零训练(Train from Scratch)毫无压力。但在真实的材料电镜室里,当你合成出一批全新牌号的高温合金或钙钛矿薄膜,人工标定的高倍 SEM/TEM 照片往往一共只有 10~30 张!此时从随机权重硬训一个 CNN 会迅速死记硬背噪声。

工业界与科研界的标准解法是迁移学习(Transfer Learning,对应 LiU 2026 第 14 讲核心范式):

  1. 阶段一(特征冻结 / Linear Probe):复用已经在源域图像库(如大规模自然图像 ImageNet 或前人百万张微结构库 MicroNet,本节直接复用第 4 节已学好边缘与相界滤波器的 cnn_img.features)上预训练好的卷积层,设置 param.requires_grad = False,只训练全新的轻量分类头(参数量从上万骤降至几十个!);
  2. 阶段二(小学习率微调 / Fine-Tuning):待新分类头稳定后(避免初期随机大梯度冲坏预训练卷积核!),解冻最后一层高层卷积块,用小 5~10 倍的学习率(如 2e-4)做温和微调。

下面我们构造一个全新的二分类金相任务——区分**“细密短针状马氏体/魏氏组织(Acicular Needles)”与“粗大块状双峰析出相(Coarse Bimodal Blobs)”**,定量测试当总训练样本数仅有 \(N_{\text{train}} \in \{12, 20, 32, 48, 80\}\) 张时,“从头训练”与“预训练迁移学习”的天壤之别!

In [13] · Python
import os
def make_new_alloy_task(n_per_class=100, size=48, seed=2026):
    """构建全新的二分类微结构任务:0 = 随机取向细短针状相 (Acicular),1 = 双尺寸粗细混合块状相 (Bimodal)。"""
    rng = np.random.RandomState(seed)
    yy, xx = np.mgrid[0:size, 0:size]
    imgs, labels = [], []
    for cls in [0, 1]:
        for _ in range(n_per_class):
            canvas = rng.normal(0.15, 0.06, size=(size, size))
            if cls == 0:
                # 细针状组织:多个随机中心、随机倾角的窄长椭圆针
                for _ in range(rng.randint(10, 16)):
                    cy, cx = rng.uniform(5, size - 5, size=2)
                    theta = rng.uniform(0, np.pi)
                    dy, dx = yy - cy, xx - cx
                    u = dx * np.cos(theta) + dy * np.sin(theta)
                    v = -dx * np.sin(theta) + dy * np.cos(theta)
                    needle = np.exp(-(u**2 / (2 * 6.5**2) + v**2 / (2 * 1.1**2)))
                    canvas += 0.65 * needle
            else:
                # 双峰块状相:少量大团块 + 若干细小弥散颗粒
                for r_sig, n_b in [(4.2, 3), (1.5, 10)]:
                    for _ in range(n_b):
                        cy, cx = rng.uniform(5, size - 5, size=2)
                        blob = np.exp(-((yy - cy)**2 + (xx - cx)**2) / (2 * r_sig**2))
                        canvas += 0.62 * blob
            canvas = np.clip(gaussian_filter(canvas, sigma=0.5) + rng.normal(0, 0.05, (size, size)), 0.0, 1.0)
            imgs.append(canvas.astype(np.float32))
            labels.append(cls)
    X_arr = np.array(imgs)[:, None, :, :]
    y_arr = np.array(labels, dtype=np.int64)
    return X_arr, y_arr

X_new_all, y_new_all = make_new_alloy_task(n_per_class=140, size=48, seed=2026)
X_pool_tl, X_test_tl, y_pool_tl, y_test_tl = train_test_split(
    X_new_all, y_new_all, test_size=120, stratify=y_new_all, random_state=42
)
X_test_tl_t = torch.tensor(X_test_tl)

def eval_scratch_vs_transfer(n_train_total, seed_run):
    set_seed(seed_run)
    # 分层抽取极小样本训练集(每类 n_train_total // 2 张)
    rng_s = np.random.RandomState(seed_run)
    idx0 = rng_s.choice(np.where(y_pool_tl == 0)[0], size=n_train_total // 2, replace=False)
    idx1 = rng_s.choice(np.where(y_pool_tl == 1)[0], size=n_train_total // 2, replace=False)
    sub_idx = np.concatenate([idx0, idx1])
    xb_tr = torch.tensor(X_pool_tl[sub_idx])
    yb_tr = torch.tensor(y_pool_tl[sub_idx])

    # A) 从头训练全新 CNN(同样卷积拓扑,随机初始化)
    scratch_cnn = copy.deepcopy(cnn_img)
    for m in scratch_cnn.modules():
        if hasattr(m, "reset_parameters"):
            m.reset_parameters()
    if isinstance(scratch_cnn.classifier, nn.Linear):
        in_feat = scratch_cnn.classifier.in_features
        scratch_cnn.classifier = nn.Linear(in_feat, 2)
    else:
        in_feat = scratch_cnn.classifier[-1].in_features
        scratch_cnn.classifier[-1] = nn.Linear(in_feat, 2)
    opt_s = torch.optim.Adam(scratch_cnn.parameters(), lr=1.5e-3)
    scratch_cnn.train()
    for _ in range(35):
        opt_s.zero_grad()
        loss_s = F.cross_entropy(scratch_cnn(xb_tr), yb_tr)
        loss_s.backward()
        opt_s.step()
    scratch_cnn.eval()
    with torch.no_grad():
        acc_scr = (scratch_cnn(X_test_tl_t).argmax(1).numpy() == y_test_tl).mean()

    # B) 预训练迁移 + 两阶段微调(先冻结卷积主干训新分类头 20 轮,再小学习率微调高层 15 轮)
    tl_cnn = copy.deepcopy(cnn_img)
    for p in tl_cnn.features.parameters():
        p.requires_grad = False
    if isinstance(tl_cnn.classifier, nn.Linear):
        tl_cnn.classifier = nn.Linear(in_feat, 2)
    else:
        tl_cnn.classifier[-1] = nn.Linear(in_feat, 2)
    opt_head = torch.optim.Adam(tl_cnn.classifier.parameters(), lr=3e-3)
    tl_cnn.train()
    for _ in range(20):
        opt_head.zero_grad()
        F.cross_entropy(tl_cnn(xb_tr), yb_tr).backward()
        opt_head.step()
    # 阶段二:解冻最后一层卷积层,用 1/10 学习率微调
    for p in list(tl_cnn.features.parameters())[-2:]:
        p.requires_grad = True
    opt_ft = torch.optim.Adam(filter(lambda p: p.requires_grad, tl_cnn.parameters()), lr=3e-4)
    for _ in range(15):
        opt_ft.zero_grad()
        F.cross_entropy(tl_cnn(xb_tr), yb_tr).backward()
        opt_ft.step()
    tl_cnn.eval()
    with torch.no_grad():
        acc_tl = (tl_cnn(X_test_tl_t).argmax(1).numpy() == y_test_tl).mean()
    return acc_scr * 100, acc_tl * 100

sample_sizes = [8, 12, 20, 32, 60]
scr_means, scr_stds, tl_means, tl_stds = [], [], [], []
for n_tr in sample_sizes:
    runs = [eval_scratch_vs_transfer(n_tr, 100 + k) for k in range(6)]
    s_vals, t_vals = zip(*runs)
    scr_means.append(np.mean(s_vals)); scr_stds.append(np.std(s_vals))
    tl_means.append(np.mean(t_vals));  tl_stds.append(np.std(t_vals))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
ax1.imshow(X_new_all[0, 0], cmap="gray")
ax1.inset_axes([0.52, 0.04, 0.44, 0.44]).imshow(X_new_all[-1, 0], cmap="gray")
ax1.set_xticks([]); ax1.set_yticks([])
ax1.set_title("a) New Alloy Task: Acicular Needles vs. Bimodal Inset")

scr_means, scr_stds = np.array(scr_means), np.array(scr_stds)
tl_means, tl_stds = np.array(tl_means), np.array(tl_stds)
ax2.plot(sample_sizes, scr_means, "o--", color=C.crimson, label="Train CNN from Scratch")
ax2.fill_between(sample_sizes, scr_means - scr_stds, scr_means + scr_stds, color=C.crimson, alpha=0.15)
ax2.plot(sample_sizes, tl_means, "s-", color=C.navy, lw=2.2, label="Pretrained Backbone + 2-Stage Fine-Tuning")
ax2.fill_between(sample_sizes, tl_means - tl_stds, tl_means + tl_stds, color=C.navy, alpha=0.18)
ax2.set_xlabel("Total Labeled Micrographs in Training Set ($N_{train}$)")
ax2.set_ylabel("Test Classification Accuracy (%)")
ax2.set_title("b) Small-Data Microscopy: Transfer Learning Wins Big")
ax2.set_ylim(48, 102)
ax2.legend(loc="lower right", fontsize=8.5)

plt.tight_layout()
_sl07 = os.path.join("..", "slides", "07_neural_networks_and_cnns", "figs")
if os.path.isdir(_sl07):
    fig.savefig(os.path.join(_sl07, "fig09_multitask_and_transfer.svg"))
plt.show()
print(f"仅 12 张标注电镜图时(每类 6 张):从头训练准确率 = {scr_means[1]:.1f}% ± {scr_stds[1]:.1f}%  vs.  迁移微调 = {tl_means[1]:.1f}% ± {tl_stds[1]:.1f}%!")
Out:
Notebook 输出图像
仅 12 张标注电镜图时(每类 6 张):从头训练准确率 = 91.8% ± 6.2%  vs.  迁移微调 = 51.7% ± 15.4%!

💡 真实科研电镜一行接入 ImageNet / MicroNet 预训练主干 处理实验室高分辨率 224×224 SEM/TEM 图像时,直接调用 torchvision.models 即可完成上述两阶段迁移:

from torchvision.models import mobilenet_v3_small, MobileNet_V3_Small_Weights
model = mobilenet_v3_small(weights=MobileNet_V3_Small_Weights.DEFAULT)
for p in model.features.parameters(): p.requires_grad = False   # 阶段 1:冻结预训练卷积核(保持 BatchNorm 稳定)
model.classifier[-1] = nn.Linear(model.classifier[-1].in_features, num_classes)

本节小结

核心模块 物理意义与 PyTorch 实践要点
局部连接与权重共享 同一卷积核在整张显微图上滑动内积,参数量比全连接层减少一个数量级以上,且保留二维拓扑邻域关系
多尺度层次特征 浅层卷积提取相界边缘与局部条纹取向,配合 MaxPool2d 逐层扩大感受野,深层捕捉晶粒拓扑与枝晶形貌
全局平均池化(GAP) nn.AdaptiveAvgPool2d((1, 1)) 对空间坐标求平均,赋予金相分类与体分预测天然的全局平移不变性
物理合规的数据增强 \(90^\circ\) 旋转与镜像翻转符合各向同性截面金相的对称性;固定放大倍率下的尺度敏感任务慎用随机缩放裁剪
两阶段迁移微调 新体系仅有十余张标注电镜图时,先冻结预训练卷积核(如 ImageNet/MicroNet)单独训分类头,再以 \(1/10\) 小学习率解冻高层微调

掌握了处理网格图像的 CNN 后,下一讲(08 - Sequence Models and Transformers)我们将转向化学与材料中的另一类核心非表格数据——变长离散序列(SMILES 分子字符串与化学反应式),学习循环神经网络(LSTM)与自注意力机制(Transformer)。

返回模块 07