therealestcoder commited on
Commit
caf134c
·
verified ·
1 Parent(s): 1a686dd

Upload src\model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src//model.py +56 -0
src//model.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Модель детекции дефектов на основе EfficientNetV2-S из timm (transfer learning)."""
2
+ from __future__ import annotations
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import timm
7
+
8
+ from . import config as C
9
+
10
+
11
+ class DefectClassifier(nn.Module):
12
+ """Бинарный классификатор патч/деталь: defect vs clean.
13
+
14
+ Используем предобученный backbone из timm и свою классификационную голову
15
+ с дропаутом — это устойчиво на малых датасетах.
16
+ """
17
+
18
+ def __init__(self, backbone: str = C.BACKBONE, num_classes: int = C.NUM_CLASSES,
19
+ pretrained: bool = True, drop_rate: float = 0.3):
20
+ super().__init__()
21
+ self.backbone = timm.create_model(
22
+ backbone,
23
+ pretrained=pretrained,
24
+ num_classes=0, # без головы — берём фичи
25
+ global_pool="avg",
26
+ )
27
+ feat_dim = self.backbone.num_features
28
+ self.head = nn.Sequential(
29
+ nn.Dropout(drop_rate),
30
+ nn.Linear(feat_dim, 256),
31
+ nn.GELU(),
32
+ nn.Dropout(drop_rate),
33
+ nn.Linear(256, num_classes),
34
+ )
35
+
36
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
37
+ feats = self.backbone(x)
38
+ return self.head(feats)
39
+
40
+ @torch.no_grad()
41
+ def predict_proba(self, x: torch.Tensor) -> torch.Tensor:
42
+ return torch.softmax(self.forward(x), dim=1)
43
+
44
+ def gradcam_target_layer(self) -> nn.Module:
45
+ """Слой для построения Grad-CAM (последний conv-блок backbone'а)."""
46
+ # У EfficientNet-семейства это последний блок перед глобальным пулингом
47
+ if hasattr(self.backbone, "conv_head"):
48
+ return self.backbone.conv_head
49
+ # Fallback: последний блок features
50
+ if hasattr(self.backbone, "blocks"):
51
+ return self.backbone.blocks[-1]
52
+ raise RuntimeError("Не нашёл подходящий слой для Grad-CAM")
53
+
54
+
55
+ def build_model(pretrained: bool = True) -> DefectClassifier:
56
+ return DefectClassifier(pretrained=pretrained)