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 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/1ej0WbfYuLvWhK2E43A_WVZ6V1ojEWtSh
|
8 |
+
"""
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import torchvision.transforms as transforms
|
12 |
+
import torchvision.models as models
|
13 |
+
import gradio as gr
|
14 |
+
import numpy as np
|
15 |
+
from PIL import Image
|
16 |
+
from sklearn.preprocessing import StandardScaler # Required for feature scaling
|
17 |
+
import joblib # To load the scaler
|
18 |
+
|
19 |
+
# Set device
|
20 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
21 |
+
|
22 |
+
# Load trained ViT model
|
23 |
+
vit_model = models.vit_b_16(pretrained=False)
|
24 |
+
vit_model.heads = torch.nn.Linear(in_features=768, out_features=2) # Binary classification
|
25 |
+
|
26 |
+
# Load ViT model weights
|
27 |
+
vit_model_path = "/content/drive/MyDrive/ViT_BCC/vit_bc"
|
28 |
+
vit_model.load_state_dict(torch.load(vit_model_path, map_location=device))
|
29 |
+
vit_model.to(device)
|
30 |
+
vit_model.eval()
|
31 |
+
|
32 |
+
# Define ViT image transformations
|
33 |
+
transform = transforms.Compose([
|
34 |
+
transforms.Resize((224, 224)),
|
35 |
+
transforms.ToTensor(),
|
36 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
37 |
+
])
|
38 |
+
|
39 |
+
# Class labels
|
40 |
+
class_names = ["Benign", "Malignant"]
|
41 |
+
|
42 |
+
# Load trained Neural Network model (ensure this is properly trained)
|
43 |
+
nn_model_path = "/content/drive/MyDrive/NN_BCC/nn_bc.pth" # Update path
|
44 |
+
nn_model = torch.load(nn_model_path, map_location=device) # Assuming a PyTorch model
|
45 |
+
nn_model.to(device)
|
46 |
+
nn_model.eval()
|
47 |
+
|
48 |
+
# Load scaler for feature normalization
|
49 |
+
scaler_path = "/content/drive/MyDrive/NN_BCC/scaler.pkl" # Update path
|
50 |
+
scaler = joblib.load(scaler_path) # Load pre-fitted scaler
|
51 |
+
|
52 |
+
# Define feature names for NN model
|
53 |
+
feature_names = [
|
54 |
+
"Mean Radius", "Mean Texture", "Mean Perimeter", "Mean Area", "Mean Smoothness",
|
55 |
+
"Mean Compactness", "Mean Concavity", "Mean Concave Points", "Mean Symmetry", "Mean Fractal Dimension",
|
56 |
+
"SE Radius", "SE Texture", "SE Perimeter", "SE Area", "SE Smoothness",
|
57 |
+
"SE Compactness", "SE Concavity", "SE Concave Points", "SE Symmetry", "SE Fractal Dimension",
|
58 |
+
"Worst Radius", "Worst Texture", "Worst Perimeter", "Worst Area", "Worst Smoothness",
|
59 |
+
"Worst Compactness", "Worst Concavity", "Worst Concave Points", "Worst Symmetry", "Worst Fractal Dimension"
|
60 |
+
]
|
61 |
+
|
62 |
+
def classify(model_choice, image=None, *features):
|
63 |
+
"""Classify using ViT (image) or NN (features)."""
|
64 |
+
if model_choice == "ViT":
|
65 |
+
if image is None:
|
66 |
+
return "Please upload an image for ViT classification."
|
67 |
+
image = image.convert("RGB") # Ensure RGB format
|
68 |
+
input_tensor = transform(image).unsqueeze(0).to(device) # Preprocess image
|
69 |
+
|
70 |
+
with torch.no_grad():
|
71 |
+
output = vit_model(input_tensor)
|
72 |
+
predicted_class = torch.argmax(output, dim=1).item()
|
73 |
+
|
74 |
+
return class_names[predicted_class]
|
75 |
+
|
76 |
+
elif model_choice == "Neural Network":
|
77 |
+
if any(f is None for f in features):
|
78 |
+
return "Please enter all 30 numerical features."
|
79 |
+
|
80 |
+
# Convert input features to NumPy array
|
81 |
+
input_data = np.array(features).reshape(1, -1)
|
82 |
+
|
83 |
+
# Standardize using pre-trained scaler
|
84 |
+
input_data_std = scaler.transform(input_data)
|
85 |
+
|
86 |
+
# Convert to tensor and run prediction
|
87 |
+
input_tensor = torch.tensor(input_data_std, dtype=torch.float32).to(device)
|
88 |
+
|
89 |
+
with torch.no_grad():
|
90 |
+
output = nn_model(input_tensor)
|
91 |
+
predicted_class = torch.argmax(output, dim=1).item()
|
92 |
+
|
93 |
+
return class_names[predicted_class]
|
94 |
+
|
95 |
+
# Define Gradio UI components
|
96 |
+
model_selector = gr.Radio(["ViT", "Neural Network"], label="Choose Model")
|
97 |
+
image_input = gr.Image(type="pil", label="Upload Mammogram Image")
|
98 |
+
|
99 |
+
# Feature inputs labeled correctly
|
100 |
+
feature_inputs = [gr.Number(label=feature_names[i]) for i in range(30)]
|
101 |
+
|
102 |
+
# Gradio Interface
|
103 |
+
iface = gr.Interface(
|
104 |
+
fn=classify,
|
105 |
+
inputs=[model_selector, image_input] + feature_inputs, # Image + Feature inputs
|
106 |
+
outputs="text",
|
107 |
+
title="Breast Cancer Classification",
|
108 |
+
description="Choose between ViT (image-based) and Neural Network (feature-based) classification."
|
109 |
+
)
|
110 |
+
|
111 |
+
iface.launch()
|
112 |
+
|
113 |
+
!pip install gradio
|
114 |
+
|
115 |
+
import torch
|
116 |
+
import torchvision.transforms as transforms
|
117 |
+
import torchvision.models as models
|
118 |
+
import gradio as gr
|
119 |
+
import numpy as np
|
120 |
+
import tensorflow as tf
|
121 |
+
from PIL import Image
|
122 |
+
from sklearn.preprocessing import StandardScaler # Required for feature scaling
|
123 |
+
import joblib # To load the scaler
|
124 |
+
|
125 |
+
# Set device for ViT model (PyTorch)
|
126 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
127 |
+
|
128 |
+
# Load trained ViT model (PyTorch)
|
129 |
+
vit_model = models.vit_b_16(pretrained=False)
|
130 |
+
vit_model.heads = torch.nn.Linear(in_features=768, out_features=2) # Binary classification
|
131 |
+
|
132 |
+
# Load ViT model weights
|
133 |
+
vit_model_path = "/content/drive/MyDrive/ViT_BCC/vit_bc"
|
134 |
+
vit_model.load_state_dict(torch.load(vit_model_path, map_location=device))
|
135 |
+
vit_model.to(device)
|
136 |
+
vit_model.eval()
|
137 |
+
|
138 |
+
# Define ViT image transformations
|
139 |
+
transform = transforms.Compose([
|
140 |
+
transforms.Resize((224, 224)),
|
141 |
+
transforms.ToTensor(),
|
142 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
143 |
+
])
|
144 |
+
|
145 |
+
# Class labels
|
146 |
+
class_names = ["Benign", "Malignant"]
|
147 |
+
|
148 |
+
# Load trained Neural Network model (TensorFlow/Keras)
|
149 |
+
nn_model_path = "/content/drive/MyDrive/Breast_Cancer_Prediction_2024/DIR_NN_BC/my_NN_BC_model.keras" # Ensure the correct path
|
150 |
+
nn_model = tf.keras.models.load_model(nn_model_path)
|
151 |
+
|
152 |
+
# Load scaler for feature normalization
|
153 |
+
scaler_path = "/content/drive/MyDrive/Breast_Cancer_Prediction_2024/DIR_NN_BC/nn_bc_scaler.pkl" # Update path
|
154 |
+
scaler = joblib.load(scaler_path) # Load pre-fitted scaler
|
155 |
+
|
156 |
+
# Define feature names for NN model
|
157 |
+
feature_names = [
|
158 |
+
"Mean Radius", "Mean Texture", "Mean Perimeter", "Mean Area", "Mean Smoothness",
|
159 |
+
"Mean Compactness", "Mean Concavity", "Mean Concave Points", "Mean Symmetry", "Mean Fractal Dimension",
|
160 |
+
"SE Radius", "SE Texture", "SE Perimeter", "SE Area", "SE Smoothness",
|
161 |
+
"SE Compactness", "SE Concavity", "SE Concave Points", "SE Symmetry", "SE Fractal Dimension",
|
162 |
+
"Worst Radius", "Worst Texture", "Worst Perimeter", "Worst Area", "Worst Smoothness",
|
163 |
+
"Worst Compactness", "Worst Concavity", "Worst Concave Points", "Worst Symmetry", "Worst Fractal Dimension"
|
164 |
+
]
|
165 |
+
|
166 |
+
def classify(model_choice, image=None, *features):
|
167 |
+
"""Classify using ViT (image) or NN (features)."""
|
168 |
+
if model_choice == "ViT":
|
169 |
+
if image is None:
|
170 |
+
return "Please upload an image for ViT classification."
|
171 |
+
image = image.convert("RGB") # Ensure RGB format
|
172 |
+
input_tensor = transform(image).unsqueeze(0).to(device) # Preprocess image
|
173 |
+
|
174 |
+
with torch.no_grad():
|
175 |
+
output = vit_model(input_tensor)
|
176 |
+
predicted_class = torch.argmax(output, dim=1).item()
|
177 |
+
|
178 |
+
return class_names[predicted_class]
|
179 |
+
|
180 |
+
elif model_choice == "Neural Network":
|
181 |
+
if any(f is None for f in features):
|
182 |
+
return "Please enter all 30 numerical features."
|
183 |
+
|
184 |
+
# Convert input features to NumPy array
|
185 |
+
input_data = np.array(features).reshape(1, -1)
|
186 |
+
|
187 |
+
# Standardize using pre-trained scaler
|
188 |
+
input_data_std = scaler.transform(input_data)
|
189 |
+
|
190 |
+
# Run prediction using TensorFlow model
|
191 |
+
prediction = nn_model.predict(input_data_std)
|
192 |
+
predicted_class = np.argmax(prediction)
|
193 |
+
|
194 |
+
return class_names[predicted_class]
|
195 |
+
|
196 |
+
# Define Gradio UI components
|
197 |
+
model_selector = gr.Radio(["ViT", "Neural Network"], label="Choose Model")
|
198 |
+
image_input = gr.Image(type="pil", label="Upload Mammogram Image")
|
199 |
+
|
200 |
+
# Feature inputs labeled correctly
|
201 |
+
feature_inputs = [gr.Number(label=feature_names[i]) for i in range(30)]
|
202 |
+
|
203 |
+
# Gradio Interface
|
204 |
+
iface = gr.Interface(
|
205 |
+
fn=classify,
|
206 |
+
inputs=[model_selector, image_input] + feature_inputs, # Image + Feature inputs
|
207 |
+
outputs="text",
|
208 |
+
title="Breast Cancer Classification",
|
209 |
+
description="Choose between ViT (image-based) and Neural Network (feature-based) classification."
|
210 |
+
)
|
211 |
+
|
212 |
+
# launch app
|
213 |
+
iface.launch()
|