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
| import torch import torch.nn as nn import torch.nn.utils.prune as prune
class EyeTrackingModel(nn.Module): """ 眼动追踪模型 原始模型:100 MB, 精度 95% 剪枝后:50 MB, 精度 94% """ def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=3, padding=1) self.conv2 = nn.Conv2d(64, 128, kernel_size=3, padding=1) self.conv3 = nn.Conv2d(128, 256, kernel_size=3, padding=1) self.fc = nn.Linear(256 * 28 * 28, 2) def forward(self, x): x = torch.relu(self.conv1(x)) x = torch.relu(self.conv2(x)) x = torch.relu(self.conv3(x)) x = x.view(x.size(0), -1) x = self.fc(x) return x
def apply_weight_pruning(model, amount=0.5): """ 应用权重剪枝 Args: model: 原始模型 amount: 剪枝比例(0-1) Returns: pruned_model: 剪枝后模型 """ for name, module in model.named_modules(): if isinstance(module, nn.Conv2d): prune.l1_unstructured(module, name='weight', amount=amount) return model
if __name__ == "__main__": model = EyeTrackingModel() original_params = sum(p.numel() for p in model.parameters()) print(f"原始参数量:{original_params:,}") pruned_model = apply_weight_pruning(model, amount=0.5) print("剪枝完成")
|