OneFineStarstuff
commited on
Commit
โข
3f2b233
1
Parent(s):
9cb1630
Create Custom ResNet SHAP
Browse files- Custom ResNet SHAP +126 -0
Custom ResNet SHAP
ADDED
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import shap
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from torchvision import models
|
6 |
+
import numpy as np
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
|
9 |
+
# Custom BasicBlock to avoid in-place operations
|
10 |
+
class CustomBasicBlock(nn.Module):
|
11 |
+
expansion = 1
|
12 |
+
|
13 |
+
def __init__(self, in_planes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None):
|
14 |
+
super(CustomBasicBlock, self).__init__()
|
15 |
+
if norm_layer is None:
|
16 |
+
norm_layer = nn.BatchNorm2d
|
17 |
+
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
|
18 |
+
self.bn1 = norm_layer(planes)
|
19 |
+
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1, bias=False)
|
20 |
+
self.bn2 = norm_layer(planes)
|
21 |
+
self.downsample = downsample
|
22 |
+
self.stride = stride
|
23 |
+
|
24 |
+
def forward(self, x):
|
25 |
+
identity = x.clone()
|
26 |
+
|
27 |
+
out = self.conv1(x)
|
28 |
+
out = self.bn1(out)
|
29 |
+
out = F.relu(out.clone(), inplace=False)
|
30 |
+
|
31 |
+
out = self.conv2(out)
|
32 |
+
out = self.bn2(out)
|
33 |
+
|
34 |
+
if self.downsample is not None:
|
35 |
+
identity = self.downsample(x.clone())
|
36 |
+
|
37 |
+
out = out.clone() + identity # Clone before addition to avoid in-place modification
|
38 |
+
out = F.relu(out.clone(), inplace=False)
|
39 |
+
|
40 |
+
return out
|
41 |
+
|
42 |
+
# Custom ResNet using CustomBasicBlock
|
43 |
+
class CustomResNet(nn.Module):
|
44 |
+
def __init__(self, block, layers, num_classes=1000):
|
45 |
+
super(CustomResNet, self).__init__()
|
46 |
+
self.inplanes = 64
|
47 |
+
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
|
48 |
+
self.bn1 = nn.BatchNorm2d(64)
|
49 |
+
self.relu = nn.ReLU(inplace=False)
|
50 |
+
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
|
51 |
+
self.layer1 = self._make_layer(block, 64, layers[0])
|
52 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
|
53 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
|
54 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
|
55 |
+
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
|
56 |
+
self.fc = nn.Linear(512 * block.expansion, num_classes)
|
57 |
+
|
58 |
+
for m in self.modules():
|
59 |
+
if isinstance(m, nn.Conv2d):
|
60 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
61 |
+
elif isinstance(m, nn.BatchNorm2d):
|
62 |
+
nn.init.constant_(m.weight, 1)
|
63 |
+
nn.init.constant_(m.bias, 0)
|
64 |
+
|
65 |
+
def _make_layer(self, block, planes, blocks, stride=1):
|
66 |
+
norm_layer = nn.BatchNorm2d
|
67 |
+
downsample = None
|
68 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
69 |
+
downsample = nn.Sequential(
|
70 |
+
nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False),
|
71 |
+
norm_layer(planes * block.expansion),
|
72 |
+
)
|
73 |
+
|
74 |
+
layers = []
|
75 |
+
layers.append(block(self.inplanes, planes, stride, downsample, groups=1, base_width=64, dilation=1, norm_layer=norm_layer))
|
76 |
+
self.inplanes = planes * block.expansion
|
77 |
+
for _ in range(1, blocks):
|
78 |
+
layers.append(block(self.inplanes, planes, groups=1, base_width=64, dilation=1, norm_layer=norm_layer))
|
79 |
+
|
80 |
+
return nn.Sequential(*layers)
|
81 |
+
|
82 |
+
def forward(self, x):
|
83 |
+
x = self.conv1(x)
|
84 |
+
x = self.bn1(x)
|
85 |
+
x = self.relu(x.clone()) # Clone to avoid in-place operation
|
86 |
+
x = self.maxpool(x)
|
87 |
+
|
88 |
+
x = self.layer1(x.clone()) # Clone to avoid in-place operation
|
89 |
+
x = self.layer2(x.clone()) # Clone to avoid in-place operation
|
90 |
+
x = self.layer3(x.clone()) # Clone to avoid in-place operation
|
91 |
+
x = self.layer4(x.clone()) # Clone to avoid in-place operation
|
92 |
+
|
93 |
+
x = self.avgpool(x)
|
94 |
+
x = torch.flatten(x, 1)
|
95 |
+
x = self.fc(x.clone()) # Clone to avoid in-place operation
|
96 |
+
|
97 |
+
return x
|
98 |
+
|
99 |
+
# Initialize the custom model with pre-trained weights
|
100 |
+
model = CustomResNet(CustomBasicBlock, [2, 2, 2, 2])
|
101 |
+
state_dict = models.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1).state_dict()
|
102 |
+
model.load_state_dict(state_dict)
|
103 |
+
model.eval()
|
104 |
+
|
105 |
+
# Initialize SHAP explainer with the custom model
|
106 |
+
explainer = shap.DeepExplainer(model, torch.randn(1, 3, 224, 224))
|
107 |
+
|
108 |
+
# Generate SHAP values for an input image
|
109 |
+
sample_image = torch.randn(1, 3, 224, 224)
|
110 |
+
shap_values = explainer.shap_values(sample_image, check_additivity=False)
|
111 |
+
|
112 |
+
# Convert SHAP values and sample image to numpy for SHAP visualization
|
113 |
+
shap_values_class_0 = shap_values[0][0] # Extract SHAP values for the first class
|
114 |
+
sample_image_np = sample_image.squeeze().permute(1, 2, 0).detach().numpy()
|
115 |
+
|
116 |
+
# Normalize sample image and SHAP values to range [0, 1] for visualization
|
117 |
+
sample_image_np = np.clip(sample_image_np, 0, 1)
|
118 |
+
shap_min, shap_max = shap_values_class_0.min(), shap_values_class_0.max()
|
119 |
+
shap_values_class_0 = (shap_values_class_0 - shap_min) / (shap_max - shap_min)
|
120 |
+
|
121 |
+
# Ensure both `sample_image_np` and `shap_values_class_0` are NumPy arrays with correct shapes for image_plot
|
122 |
+
sample_image_np = np.array([sample_image_np]) # Add batch dimension for SHAP
|
123 |
+
shap_values_class_0 = np.array([shap_values_class_0]) # Add batch dimension for SHAP
|
124 |
+
|
125 |
+
# Visualize SHAP values for the first class
|
126 |
+
shap.image_plot(shap_values_class_0, sample_image_np)
|