π§ DCGAN: Generate Realistic Human Faces using PyTorch
This project uses Deep Convolutional GAN (DCGAN) architecture implemented in PyTorch to generate realistic human face images from a noise vector. It includes full training and image generation pipeline.
π§ Features
- Uses
torchvision.datasets.ImageFolder
to load real face images. - Implements a DCGAN:
Generator
usingConvTranspose2d
layers.Discriminator
usingConv2d
layers without Sigmoid.
- Trains on 64x64 images.
- Supports CUDA (GPU) acceleration.
- Saves sample images every 10 epochs.
- Includes function to generate and display one random face at the end.
π Folder Structure
project/
β
βββ images/ # Folder with real training face images
β βββ class_x/ # ImageFolder requires class subdirectories
β βββ image1.jpg
β βββ image2.jpg
β
βββ generated_epoch_10.png # Sample outputs saved every 10 epochs
βββ generator.pth # Saved Generator weights after training
βββ gan_faces.py # Python script with model and training code
βββ README.md # This file
π Getting Started
β Prerequisites
Install Python and required libraries:
pip install torch torchvision matplotlib tqdm
Make sure you have a folder ./images/ structured like:
images/
βββ faces/
βββ img1.jpg
βββ img2.jpg
Where faces/ is any class name (required by ImageFolder).
π§ How It Works
Generator: Takes a random noise vector and generates a 64x64x3 image.
Discriminator: Takes a real or fake image and returns a score (real or fake).
Loss Function: BCEWithLogitsLoss is used for both Generator and Discriminator.
Label Smoothing: Real images use soft labels (0.9 instead of 1.0) to stabilize training.
βοΈ Training
To start training:
python gan_faces.py
The script will:
Load images from ./images/
Train for 100 epochs (can be changed)
Save sample images every 10 epochs as generated_epoch_X.png
Save final model as generator.pth
π§ͺ Generate One Face
At the end of training, a sample face will be displayed using matplotlib.
- You can also use this standalone function:
generate_one_face("generator.pth")
To generate and visualize a face anytime.
- Downloads last month
- -