Machine Learning
Deepfake Image Detection Using Artificial Intelligence
# Deepfake Image Detection Using Artificial Intelligence
## What I Built
The speed at which AI can generate photorealistic imagery has massively outpaced the human eye's ability to detect it. This project is an automated **AI-Generated Image Detector**, a binary classification system that takes any image and predicts whether it is a real photograph or machine-generated.
More importantly, it doesn't just give a prediction; it explains its reasoning. By integrating **Grad-CAM** (Gradient-weighted Class Activation Mapping), the application generates a heatmap over the uploaded image, highlighting the exact pixels and artifacts the neural network focused on to make its decision.
## Tech Stack & Architecture
* **Backbone:** EfficientNet-B0 (Pre-trained on ImageNet for transfer learning)
* **Framework:** PyTorch
* **Explainability:** Custom Grad-CAM implementation using PyTorch hooks
* **Deployment:** Streamlit, Docker, Hugging Face Spaces
EfficientNet-B0 was chosen for its compound scaling approach, which provides state-of-the-art accuracy with a highly efficient parameter count (~5.3 million), making it lightweight enough to run inference smoothly in a browser.
## Dataset & Training
To ensure the model learns generalized AI artifacts rather than memorizing a specific generator, I curated a dataset of over **45,000 images** from more than 10 different sources:
* **FAKE (AI):** DiffusionDB, Synthbuster (Stable Diffusion, DALL·E 2, GLIDE), StyleGAN Faces.
* **REAL:** RAISE 4K, Flickr, Imagenette, and the **DPED dataset** (smartphone photos from iPhone/Sony to fix domain shift biases).
Crucially, modern generators like **DALL·E 3 and Midjourney v5 were withheld entirely from training** and only used in the test set to evaluate true zero-shot generalization.
## Code Example: Grad-CAM Explainability
Instead of using external libraries that can break in headless deployment environments, I implemented Grad-CAM using pure PyTorch forward and backward hooks:
```python
import torch
import torch.nn.functional as F
def generate_gradcam_heatmap(model, input_tensor, target_class):
feature_maps, gradients = [], []
target_layer = model.features[-1]
# Register hooks to capture activations and gradients
handle_f = target_layer.register_forward_hook(lambda m, i, o: feature_maps.append(o))
handle_b = target_layer.register_full_backward_hook(lambda m, gi, go: gradients.append(go[0]))
output = model(input_tensor)
model.zero_grad()
output[0, target_class].backward()
handle_f.remove()
handle_b.remove()
# Global average pooling and heatmap generation
weights = torch.mean(gradients[0], dim=(2, 3), keepdim=True)
cam = F.relu(torch.sum(weights * feature_maps[0], dim=1).squeeze())
cam = (cam - cam.min()) / (cam.max() - cam.min() + 1e-8)
return cam.detach().cpu().numpy()
Python
PyTorch
EfficientNet
Streamlit
OpenCV