1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
| import torch import torch.nn as nn import numpy as np
class KANLayer(nn.Module): """ Kolmogorov-Arnold Network层 核心区别:可学习激活函数在边上而非节点上 使用B样条逼近任意一维函数 """ def __init__(self, in_dim: int, out_dim: int, grid_size: int = 5, spline_order: int = 3): super().__init__() self.in_dim = in_dim self.out_dim = out_dim self.grid_size = grid_size self.spline_order = spline_order self.base_weight = nn.Parameter( torch.randn(out_dim, in_dim) * 0.1 ) self.spline_weight = nn.Parameter( torch.randn(out_dim, in_dim, grid_size + spline_order) * 0.1 ) h = 1.0 / grid_size grid = torch.arange(-spline_order, grid_size + spline_order + 1) * h self.register_buffer('grid', grid) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: [batch, in_dim] Returns: output: [batch, out_dim] """ batch_size = x.shape[0] base = torch.einsum('bi,oi->bo', x, self.base_weight) x_expanded = x.unsqueeze(-1) grid_expanded = self.grid.view(1, 1, -1) b_splines = self._bspline_basis( x_expanded.expand(-1, -1, grid_expanded.shape[-1]), grid_expanded.expand(x.shape[0], -1, -1) ) spline = torch.einsum( 'big,oig->bog', b_splines, self.spline_weight ) return base + spline def _bspline_basis(self, x: torch.Tensor, grid: torch.Tensor) -> torch.Tensor: """计算B样条基函数值(简化版)""" order = self.spline_order if order == 0: return ((x >= grid[..., :-1]) & (x < grid[..., 1:])).float() B_prev = self._bspline_basis(x, grid) if B_prev.shape[-1] > 1: denom1 = grid[..., order:B_prev.shape[-1]] - grid[..., :-order] denom1 = torch.where(denom1 != 0, denom1, torch.ones_like(denom1)) term1 = (x - grid[..., :-order]) / denom1 * B_prev[..., :-1] denom2 = grid[..., order+1:] - grid[..., 1:B_prev.shape[-1]] denom2 = torch.where(denom2 != 0, denom2, torch.ones_like(denom2)) term2 = (grid[..., order+1:] - x) / denom2 * B_prev[..., 1:] return term1 + term2 return B_prev
class KANCLUEModel(nn.Module): """ KAN-CLUE: CNN骨干 + KAN分类器 + 不确定性量化 架构: 1. 轻量CNN提取眼周图像特征 2. KAN层替代MLP进行分类 3. 蒙特卡洛Dropout量化不确定性 """ def __init__(self, num_classes: int = 3, feature_dim: int = 128, kan_grid: int = 5): super().__init__() self.backbone = nn.Sequential( nn.Conv2d(1, 16, 3, stride=2, padding=1), nn.BatchNorm2d(16), nn.ReLU6(), nn.Conv2d(16, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU6(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU6(), nn.AdaptiveAvgPool2d(1), ) self.flatten = nn.Flatten() self.kan1 = KANLayer(64, feature_dim, grid_size=kan_grid) self.kan2 = KANLayer(feature_dim, num_classes, grid_size=kan_grid) self.dropout = nn.Dropout(0.1) def forward(self, x: torch.Tensor, n_samples: int = 1) -> tuple: """ 前向传播 Args: x: [batch, 1, H, W] 近红外眼周图像 n_samples: MC采样次数(>1时输出不确定性) Returns: logits: [batch, num_classes] uncertainty: [batch] 预测熵 """ features = self.backbone(x) features = self.flatten(features) logits_list = [] for _ in range(n_samples): h = self.dropout(features) h = self.kan1(h) h = torch.relu(h) logits = self.kan2(h) logits_list.append(logits) logits_stack = torch.stack(logits_list) if n_samples > 1: avg_logits = logits_stack.mean(dim=0) probs = torch.softmax(avg_logits, dim=-1) entropy = -torch.sum( probs * torch.log(probs + 1e-8), dim=-1 ) return avg_logits, entropy else: return logits_stack[0], torch.zeros(x.shape[0])
if __name__ == "__main__": model = KANCLUEModel(num_classes=3) x = torch.randn(4, 1, 48, 48) logits, _ = model(x, n_samples=1) print(f"单次推理 logits: {logits.shape}") logits, uncertainty = model(x, n_samples=10) print(f"不确定性推理 logits: {logits.shape}") print(f"不确定性: {uncertainty}") print(f"高置信度(低熵): {(uncertainty < 0.5).sum()}/4") total_params = sum(p.numel() for p in model.parameters()) print(f"\nKAN-CLUE总参数: {total_params:,}") mlp_model = nn.Sequential( nn.Conv2d(1, 16, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 32, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 3) ) mlp_params = sum(p.numel() for p in mlp_model.parameters()) print(f"等效MLP参数: {mlp_params:,}") print(f"压缩比: {mlp_params/total_params:.1f}x")
|