A compact PyTorch project for training a convolutional neural network on cats vs dogs, then visualizing what the trained model associates with either class using activation maximization.
The visualization step starts from random noise and directly optimizes the image pixels to increase the chosen class logit.
DogvCat/
├── data/
│ ├── Cat/ # cat images
│ └── Dog/ # dog images
├── outputs/
│ └── models/
│ └── pranaynet.pth # saved best model checkpoint
├── src/
│ ├── dataset.py # data loading and transforms
│ ├── model.py # PranayNet CNN architecture
│ ├── train.py # training and evaluation loop
│ ├── dream.py # activation-maximization visualization
│ ├── inference.py
│ └── utils.py
└── main.py # training entrypoint
Install the required packages:
pip install torch torchvision matplotlibIf you want GPU acceleration, install the PyTorch build that matches your CUDA version from the official PyTorch install page.
This project uses torchvision.datasets.ImageFolder, so the data must be arranged like this:
data/
├── Cat/
│ ├── cat_001.jpg
│ └── ...
└── Dog/
├── dog_001.jpg
└── ...
ImageFolder assigns class IDs alphabetically:
Cat -> 0
Dog -> 1
Images are resized to 128x128. The training transform uses random horizontal flips; the test transform only resizes and converts images to tensors.
Run:
python main.pyCurrent training configuration:
model = PranayNet
epochs = 20
learning_rate = 0.002
optimizer = AdamW
weight_decay = 1e-4
loss = CrossEntropyLoss
batch_size = 64
split = 80% train / 20% test
During training, the best model by test accuracy is saved to:
outputs/models/pranaynet.pth
After training, run:
python -m src.dreamThe core objective in src/dream.py is:
loss = -model(x)[0][logit]Because the optimizer minimizes loss, this maximizes the selected class logit.
Use:
logit = 0 # Cat
logit = 1 # Dog
The current script calls:
x = dream(50, 0)To visualize a dog instead, change it to:
x = dream(50, 1)The dream image is initialized as random noise:
x = torch.rand((1, 3, 128, 128), requires_grad=True)The image itself is optimized using SGD:
optimizer = SGD
learning_rate = 1
Every 10 epochs, Gaussian blur is applied:
kernel_size = 5
sigma = 1.0
This smooths high-frequency noise and makes the activation-maximized image more interpretable.
- Place images in
data/Cat/anddata/Dog/. - Install dependencies.
- Train the classifier:
python main.py- Generate a class visualization:
python -m src.dream- Change the
logitargument insrc/dream.pyto switch between cat and dog visualization.
- The trained checkpoint is expected at
outputs/models/pranaynet.pth. Catis class0andDogis class1when using the folder names shown above.- Training and dream outputs can vary slightly depending on hardware and PyTorch version.
- This is activation maximization, not GAN-based image generation. The generated image shows patterns that increase the model's class score, not necessarily a photorealistic animal.