deven / app.py
stevafernandes's picture
Upload 3 files
3215d3a verified
Raw History Blame Contribute Delete
2.31 kB
import gradio as gr
import tensorflow as tf
from matplotlib import colormaps
# Same order as in training: label 0, then label 1
CLASSES = ["Demented", "Non_Demented"]
IMAGE_SIZE = (224, 224)
model = tf.keras.models.load_model("project_model.h5", compile=False)
# Split the model after the last convolutional layer: its feature maps,
# weighted by the weights of the output layer, give the class activation map
conv_layers = tf.keras.Sequential(model.layers[:-2])
output_layers = tf.keras.Sequential(model.layers[-2:])
output_weights = model.layers[-1].get_weights()[0]
def predict(path):
# Same decoding and resize as image_dataset_from_directory in training
# (the model rescales to 0-1 itself)
image = tf.io.decode_image(tf.io.read_file(path), channels=3, expand_animations=False)
image = tf.image.resize(image, IMAGE_SIZE)
features = conv_layers(image[None])
# The sigmoid output is the probability of label 1 (Non_Demented)
probability = float(output_layers(features)[0, 0])
# Positive values support Non_Demented, negative values support Demented.
# Keep what supports the predicted class
cam = features @ output_weights
cam = tf.nn.relu(cam if probability > 0.5 else -cam)
cam = tf.image.resize(cam, IMAGE_SIZE)[0, :, :, 0].numpy()
cam = (cam - cam.min()) / (cam.max() - cam.min() + 1e-8)
# Same overlay as the notebook: jet colormap at 40% opacity
heatmap = colormaps["jet"](cam)[:, :, :3] * 255
overlay = (0.6 * image.numpy() + 0.4 * heatmap).astype("uint8")
return {CLASSES[0]: 1 - probability, CLASSES[1]: probability}, overlay
demo = gr.Interface(
fn=predict,
# filepath + image_mode=None hands the uploaded file to predict unchanged
inputs=gr.Image(type="filepath", image_mode=None, label="Brain MRI slice"),
outputs=[
gr.Label(label="Prediction"),
gr.Image(label="Class activation map"),
],
title="Alzheimer's MRI Classification with Class Activation Maps",
description=(
"Upload an axial brain MRI slice. The model predicts Demented or "
"Non_Demented, and the heat map shows the regions that support that "
"prediction. Research demo only, not a diagnostic tool."
),
flagging_mode="never",
)
if __name__ == "__main__":
demo.launch()