Create model.py
Browse files
model.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import OrderedDict
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class SceneCNN(nn.Module):
|
| 8 |
+
def __init__(self, base=16, num_classes=6, conv_dropout=0.1, fc_dropout=0.4):
|
| 9 |
+
super().__init__()
|
| 10 |
+
channels = [base, base * 2, base * 4, base * 8]
|
| 11 |
+
|
| 12 |
+
layers = OrderedDict()
|
| 13 |
+
in_ch = 3
|
| 14 |
+
for i, out_ch in enumerate(channels, 1):
|
| 15 |
+
layers[f"conv{i}a"] = nn.Conv2d(in_ch, out_ch, 3, padding=1, bias=False)
|
| 16 |
+
layers[f"bn{i}a"] = nn.BatchNorm2d(out_ch)
|
| 17 |
+
layers[f"relu{i}a"] = nn.ReLU()
|
| 18 |
+
layers[f"conv{i}b"] = nn.Conv2d(out_ch, out_ch, 3, padding=1, bias=False)
|
| 19 |
+
layers[f"bn{i}b"] = nn.BatchNorm2d(out_ch)
|
| 20 |
+
layers[f"relu{i}b"] = nn.ReLU()
|
| 21 |
+
layers[f"pool{i}"] = nn.MaxPool2d(2)
|
| 22 |
+
layers[f"drop{i}"] = nn.Dropout2d(conv_dropout)
|
| 23 |
+
in_ch = out_ch
|
| 24 |
+
self.features = nn.Sequential(layers)
|
| 25 |
+
|
| 26 |
+
self.gap = nn.AdaptiveAvgPool2d(1)
|
| 27 |
+
self.flatten = nn.Flatten()
|
| 28 |
+
self.drop_fc = nn.Dropout(fc_dropout)
|
| 29 |
+
self.fc1 = nn.Linear(channels[-1], 128)
|
| 30 |
+
self.relu_fc = nn.ReLU()
|
| 31 |
+
self.fc2 = nn.Linear(128, num_classes)
|
| 32 |
+
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
x = self.features(x)
|
| 35 |
+
x = self.flatten(self.gap(x))
|
| 36 |
+
x = self.drop_fc(x)
|
| 37 |
+
x = self.relu_fc(self.fc1(x))
|
| 38 |
+
return self.fc2(x)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def grad_cam(model, x):
|
| 42 |
+
"""x: normalized tensor (3,H,W). Returns (cam HxW in [0,1], softmax probs)."""
|
| 43 |
+
model.eval()
|
| 44 |
+
store = {}
|
| 45 |
+
|
| 46 |
+
def hook(_, __, out):
|
| 47 |
+
store["act"] = out
|
| 48 |
+
out.register_hook(lambda g: store.__setitem__("grad", g))
|
| 49 |
+
|
| 50 |
+
h = model.features.relu4b.register_forward_hook(hook)
|
| 51 |
+
with torch.enable_grad():
|
| 52 |
+
logits = model(x.unsqueeze(0))
|
| 53 |
+
h.remove()
|
| 54 |
+
cls = logits.argmax(1).item()
|
| 55 |
+
model.zero_grad()
|
| 56 |
+
logits[0, cls].backward()
|
| 57 |
+
|
| 58 |
+
act, grad = store["act"][0], store["grad"][0]
|
| 59 |
+
weights = grad.mean(dim=(1, 2))
|
| 60 |
+
cam = F.relu((weights[:, None, None] * act).sum(0))
|
| 61 |
+
cam = F.interpolate(cam[None, None], size=x.shape[1:], mode="bilinear", align_corners=False)[0, 0]
|
| 62 |
+
cam = (cam - cam.min()) / (cam.max() - cam.min() + 1e-8)
|
| 63 |
+
probs = F.softmax(logits, 1)[0]
|
| 64 |
+
return cam.detach().numpy(), probs.detach().numpy()
|