processoptimisationsystem commited on
Commit
2beb7c3
·
verified ·
1 Parent(s): 4b8cd89

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +162 -30
src/streamlit_app.py CHANGED
@@ -1,8 +1,3 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
- import streamlit as st
5
-
6
  """
7
  # Welcome to Streamlit!
8
 
@@ -13,28 +8,165 @@ forums](https://discuss.streamlit.io).
13
  In the meantime, below is an example of what you can do with just a few lines of code:
14
  """
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
  # Welcome to Streamlit!
3
 
 
8
  In the meantime, below is an example of what you can do with just a few lines of code:
9
  """
10
 
11
+ import streamlit as st
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ import torchvision.transforms as transforms
16
+ from PIL import Image as Img
17
+ import numpy as np
18
+ import cv2
19
+ import matplotlib.pyplot as plt
20
+ from pytorch_grad_cam import GradCAM
21
+ from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
22
+ from pytorch_grad_cam.utils.image import show_cam_on_image
23
+ from lime.lime_image import LimeImageExplainer
24
+ from skimage.segmentation import mark_boundaries
25
+ import shap
26
+ from shap import GradientExplainer
27
+ device = "cuda" if torch.cuda.is_available() else "cpu"
28
+ num_classes = 4
29
+ image_size = (224, 224)
30
+ # Define CNN Model
31
+ class MyModel(nn.Module):
32
+ def __init__(self, num_classes=4):
33
+ super(MyModel, self).__init__()
34
+ self.features = nn.Sequential(
35
+ nn.Conv2d(3, 64, kernel_size=3, padding=1),
36
+ nn.BatchNorm2d(64),
37
+ nn.ReLU(inplace=True),
38
+ nn.MaxPool2d(kernel_size=2, stride=2),
39
+
40
+ nn.Conv2d(64, 128, kernel_size=3, padding=1),
41
+ nn.BatchNorm2d(128),
42
+ nn.ReLU(inplace=True),
43
+ nn.MaxPool2d(kernel_size=2, stride=2),
44
+
45
+ nn.Conv2d(128, 128, kernel_size=3, padding=1),
46
+ nn.BatchNorm2d(128),
47
+ nn.ReLU(inplace=True),
48
+ nn.MaxPool2d(kernel_size=2, stride=2),
49
+
50
+ nn.Conv2d(128, 256, kernel_size=3, padding=1),
51
+ nn.BatchNorm2d(256),
52
+ nn.ReLU(inplace=True),
53
+ nn.MaxPool2d(kernel_size=2, stride=2),
54
+
55
+ nn.Conv2d(256, 256, kernel_size=3, padding=1),
56
+ nn.BatchNorm2d(256),
57
+ nn.ReLU(inplace=True),
58
+ nn.MaxPool2d(kernel_size=2, stride=2),
59
+
60
+ nn.Conv2d(256, 512, kernel_size=3, padding=1),
61
+ nn.BatchNorm2d(512),
62
+ nn.ReLU(inplace=True),
63
+ nn.MaxPool2d(kernel_size=2, stride=2),
64
+ )
65
+ self.classifier = nn.Sequential(
66
+ nn.Flatten(),
67
+ nn.Linear(512 * 3 * 3, 1024),
68
+ nn.ReLU(inplace=True),
69
+ nn.Dropout(0.25),
70
+
71
+ nn.Linear(1024, 512),
72
+ nn.ReLU(inplace=True),
73
+ nn.Dropout(0.25),
74
+
75
+ nn.Linear(512, num_classes)
76
+ )
77
+ def forward(self, x):
78
+ x = self.features(x)
79
+ x = self.classifier(x)
80
+ return x
81
+ # Load model
82
+ model = MyModel(num_classes=num_classes).to(device)
83
+ model.load_state_dict(torch.load("brainCNNpytorch_model", map_location=torch.device('cpu')))
84
+ model.eval()
85
+ # Label dictionary
86
+ label_dict = {0: "Meningioma", 1: "Glioma", 2: "No Tumor", 3: "Pituitary"}
87
+ # Preprocessing
88
+ def preprocess_image(image):
89
+ transform = transforms.Compose([
90
+ transforms.Resize((224, 224)),
91
+ transforms.ToTensor(),
92
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
93
+ ])
94
+ return transform(image).unsqueeze(0).to(device)
95
+ # Grad-CAM
96
+ def visualize_grad_cam(image, model, target_layer, label):
97
+ img_np = np.array(image) / 255.0
98
+ img_np = cv2.resize(img_np, (224, 224))
99
+ img_tensor = preprocess_image(image)
100
+ with torch.no_grad():
101
+ output = model(img_tensor)
102
+ _, target_index = torch.max(output, 1)
103
+ cam = GradCAM(model=model, target_layers=[target_layer])
104
+ grayscale_cam = cam(input_tensor=img_tensor, targets=[ClassifierOutputTarget(target_index.item())])[0]
105
+ grayscale_cam_resized = cv2.resize(grayscale_cam, (224, 224))
106
+ visualization = show_cam_on_image(img_np, grayscale_cam_resized, use_rgb=True)
107
+ return visualization
108
+ # LIME
109
+ def model_predict(images):
110
+ preprocessed_images = [preprocess_image(Img.fromarray(img)) for img in images]
111
+ images_tensor = torch.cat(preprocessed_images).to(device)
112
+ with torch.no_grad():
113
+ logits = model(images_tensor)
114
+ probabilities = F.softmax(logits, dim=1)
115
+ return probabilities.cpu().numpy()
116
+ def visualize_lime(image):
117
+ explainer = LimeImageExplainer()
118
+ original_image = np.array(image)
119
+ explanation = explainer.explain_instance(original_image, model_predict, top_labels=3, hide_color=0, num_samples=100)
120
+ top_label = explanation.top_labels[0]
121
+ temp, mask = explanation.get_image_and_mask(label=top_label, positive_only=True, num_features=10, hide_rest=False)
122
+ return mark_boundaries(temp / 255.0, mask)
123
+ # SHAP
124
+ def visualize_shap(image):
125
+ img_tensor = preprocess_image(image).to(device)
126
+ if img_tensor.shape[1] == 1:
127
+ img_tensor = img_tensor.expand(-1, 3, -1, -1)
128
+ background = torch.cat([img_tensor] * 10, dim=0)
129
+ explainer = shap.GradientExplainer(model, background)
130
+ shap_values = explainer.shap_values(img_tensor)
131
+ # Prepare image
132
+ img_numpy = img_tensor.squeeze().permute(1, 2, 0).cpu().numpy()
133
+ shap_values = np.array(shap_values[0]).squeeze()
134
+ shap_values = shap_values / np.abs(shap_values).max() if np.abs(shap_values).max() != 0 else shap_values
135
+ shap_values = np.transpose(shap_values, (1, 2, 0))
136
+ # Plotting
137
+ fig, ax = plt.subplots(figsize=(5, 5))
138
+ ax.imshow(img_numpy)
139
+ ax.imshow(shap_values, cmap='jet', alpha=0.5)
140
+ ax.axis('off')
141
+ plt.tight_layout()
142
+ return fig
143
+ # Streamlit UI
144
+ st.title("Brain Tumor Classification with Grad-CAM, LIME, and SHAP")
145
+ uploaded_file = st.file_uploader("Upload an MRI Image", type=["jpg", "png", "jpeg"])
146
+ if uploaded_file is not None:
147
+ image = Img.open(uploaded_file).convert("RGB")
148
+ st.image(image, caption="Uploaded Image", use_container_width=True)
149
+ if st.button("Classify & Visualize"):
150
+ image_tensor = preprocess_image(image)
151
+ with torch.no_grad():
152
+ output = model(image_tensor)
153
+ _, predicted = torch.max(output, 1)
154
+ label = label_dict[predicted.item()]
155
+ st.write(f"### Prediction: {label}")
156
+ # Grad-CAM
157
+ target_layer = model.features[16] # Last Conv layer
158
+ grad_cam_img = visualize_grad_cam(image, model, target_layer, label)
159
+ # LIME
160
+ lime_img = visualize_lime(image)
161
+ # SHAP is shown directly in Streamlit
162
+ col1, col2, col3 = st.columns(3)
163
+ with col1:
164
+ st.subheader("Grad-CAM")
165
+ st.image(grad_cam_img, caption="Grad-CAM", use_container_width=True)
166
+ with col2:
167
+ st.subheader("LIME")
168
+ st.image(lime_img, caption="LIME Explanation", use_container_width=True)
169
+ with col3:
170
+ st.subheader("SHAP")
171
+ fig = visualize_shap(image)
172
+ st.pyplot(fig)