In the world of medical AI, a "99% accuracy" score isn't enough. If an algorithm flags a suspicious mole but can't tell the doctor why, it's just a black box. This is where Explainable AI (XAI) changes the game. Today, we are upgrading our dermatology screening tool to Derm-Scan-v2, moving beyond simple classification to high-fidelity visualization.
By leveraging the power of Vision Transformers (ViT) and Grad-CAM (Gradient-weighted Class Activation Mapping), we are building a system that not only predicts skin conditions but also highlights the specific pathological features it identified. In this tutorial, we'll bridge the gap between deep learning and clinical trust using a modern Computer Vision stack and a FastAPI backend.
The Architecture: How It Works 🏗️
The flow is simple but powerful: we take an image from a mobile device, process it through a transformer-based backbone, and generate a heatmap that overlays the original image to show the model's "attention."
graph TD A[React Native App] -->|Upload Image| B(FastAPI Backend) B --> C{ViT Model Inference} C --> D[Class Prediction] C --> E[Grad-CAM Heatmap Generation] D --> F[Final Result JSON] E --> G[Overlay Image] F --> H[User Dashboard] G --> H style C fill:#f9f,stroke:#333,stroke-width:2px style E fill:#bbf,stroke:#333,stroke-width:2px Prerequisites 🛠️
To follow along, you'll need:
- Python 3.10+
- PyTorch & Timms (for Vision Transformer)
- FastAPI (for the high-performance API)
- React Native (for the cross-platform mobile UI)
Step 1: Defining the Vision Transformer (ViT) Model
We use the vit_tiny_patch16_224 model for its efficiency on mobile-ready backends. Unlike CNNs, ViT looks at global dependencies between patches of the image.
import torch from timm import create_model class DermViT(torch.nn.Module): def __init__(self, num_classes=7): super().__init__() # Using a pre-trained Vision Transformer backbone self.model = create_model('vit_tiny_patch16_224', pretrained=True) self.model.head = torch.nn.Linear(self.model.head.in_features, num_classes) def forward(self, x): return self.model(x) # Load our fine-tuned weights model = DermViT() model.load_state_dict(torch.load("derm_scan_weights.pth", map_location="cpu")) model.eval() Step 2: Adding the "Explainability" Layer with Grad-CAM
To visualize what the ViT is focusing on, we use Grad-CAM. For Transformers, we target the last LayerNorm or the attention blocks.
from pytorch_grad_cam import GradCAM from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget from pytorch_grad_cam.utils.image import show_cam_on_image import numpy as np def generate_heatmap(input_tensor, input_image): # Target the last block of the ViT target_layers = [model.model.blocks[-1].norm1] cam = GradCAM(model=model, target_layers=target_layers) # Generate the grayscale attention map grayscale_cam = cam(input_tensor=input_tensor, targets=[ClassifierOutputTarget(1)]) grayscale_cam = grayscale_cam[0, :] # Overlay the heatmap onto the original image visualization = show_cam_on_image(input_image, grayscale_cam, use_rgb=True) return visualization Step 3: Deploying with FastAPI 🚀
FastAPI handles the heavy lifting of receiving images and returning both the diagnosis and the visualized heatmap.
from fastapi import FastAPI, UploadFile, File import io from PIL import Image app = FastAPI(title="Derm-Scan API") @app.post("/analyze") async def analyze_skin(file: UploadFile = File(...)): # 1. Read and preprocess image contents = await file.read() image = Image.open(io.BytesIO(contents)).convert("RGB").resize((224, 224)) img_array = np.float32(image) / 255 input_tensor = preprocess(image) # Standard Normalize/ToTensor # 2. Run Inference with torch.no_grad(): output = model(input_tensor) probs = torch.nn.functional.softmax(output, dim=1) top_prob, top_class = torch.max(probs, dim=1) # 3. Generate Heatmap (Grad-CAM) heatmap_img = generate_heatmap(input_tensor, img_array) # 4. Return results (encoded image + metadata) return { "condition": "Melanoma" if top_class == 1 else "Benign", "confidence": float(top_prob), "heatmap_url": "data:image/jpeg;base64,..." # Base64 encoded result } Step 4: The Mobile Experience (React Native) 📱
On the frontend, we want the user to see the result and the explainability map side-by-side.
import React, { useState } from 'react'; import { View, Image, Button, Text } from 'react-native'; const DermScanner = () => { const [result, setResult] = useState(null); const uploadImage = async (uri) => { const formData = new FormData(); formData.append('file', { uri, name: 'skin_lesion.jpg', type: 'image/jpeg' }); const response = await fetch('https://api.your-server.com/analyze', { method: 'POST', body: formData, }); const data = await response.json(); setResult(data); }; return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> {result && ( <> <Text style={{ fontSize: 20, fontWeight: 'bold' }}>{result.condition}</Text> <Image source={{ uri: result.heatmap_url }} style={{ width: 300, height: 300 }} /> <Text>Confidence: {(result.confidence * 100).toFixed(2)}%</Text> </> )} <Button title="Pick an Image" onPress={/* Select Image Logic */} /> </View> ); }; The "Official" Way to Build Health-Tech 🥑
While this tutorial provides a solid foundation for screening tools, building production-ready medical AI involves complex regulatory compliance (HIPAA/GDPR), data privacy, and model robustness.
For advanced architectural patterns and more production-ready examples of how to scale AI in the health-tech space, I highly recommend exploring the deep-dive articles at the WellAlly Tech Blog. They cover everything from secure data pipelines to optimizing inference for low-latency clinical environments.
Conclusion: Trust is the Ultimate Feature 🌟
By combining Vision Transformers with Grad-CAM, we’ve moved from a simple "Yes/No" machine to a collaborative tool that provides visual evidence for its decisions. This transparency is vital for AI adoption in dermatology and beyond.
What's next for Derm-Scan?
- Implementing Multi-modal inputs (patient age, lesion location).
- Moving to Quantized ViT for edge-device inference.
Have you worked with Explainable AI before? Drop your thoughts or questions in the comments below! 👇

