Of course. This is a very interesting and unique training objective. It essentially asks the generator to produce a diverse set of images ("apples") that are all individually close to the manifold of real data ("dots"). The loss function encourages two things simultaneously:
- Attraction to Data Manifold: Each generated "apple" should be close to the cloud of real MNIST "dots". This is achieved by minimizing
mean(distance(apple, dot)).
- Repulsion from other Apples: Each generated "apple" should be far away from the other "apples" in the same batch. This is achieved by maximizing
mean(distance(apple, other_apple)), which is equivalent to minimizing the negative of that value.
Your formula mean(dist_to_dots - dist_to_apples / 2) combines these two objectives into a single loss.
Here is a complete, runnable PyTorch implementation that does exactly what you've described.
Core Components
- Generator Model: A standard DCGAN-style generator that takes a latent vector and upsamples it to a 28x28 image.
- Data Loader: A
DataLoader for MNIST to provide the real "dots".
- Loss Function: A Python function
calculate_euclidean_loss that implements your specific formula.
- Training Loop: A function that orchestrates the training, including the "fast learning schedule."
The Code
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from torchvision.datasets import MNIST
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import torchvision.utils as vutils
import os
import numpy as np
# --- 1. Hyperparameters & Setup ---
# Training parameters
EPOCHS = 25
LR = 0.0002 # A good learning rate for Adam in GAN-like models
BETA1 = 0.5 # Recommended beta1 for Adam in GANs
# Batch sizes as requested
BATCH_SIZE_APPLES = 64 # Number of images to generate per step
BATCH_SIZE_DOTS = 512 # Number of real MNIST images for comparison
# Model and Data parameters
IMG_SIZE = 28
CHANNELS = 1
LATENT_DIM = 100 # Size of the noise vector for the generator
# Setup
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Create a directory to save generated images
os.makedirs("generated_images", exist_ok=True)
# --- 2. Generator Model Definition ---
class Generator(nn.Module):
def __init__(self, latent_dim, channels, img_size):
super(Generator, self).__init__()
self.img_size = img_size
self.channels = channels
self.model = nn.Sequential(
# Input is Z, going into a convolution
nn.ConvTranspose2d(latent_dim, 256, 7, 1, 0, bias=False),
nn.BatchNorm2d(256),
nn.ReLU(True),
# state size. 256 x 7 x 7
nn.ConvTranspose2d(256, 128, 4, 2, 1, bias=False),
nn.BatchNorm2d(128),
nn.ReLU(True),
# state size. 128 x 14 x 14
nn.ConvTranspose2d(128, channels, 4, 2, 1, bias=False),
nn.Tanh() # Output values between -1 and 1
# final state size. channels x 28 x 28
)
def forward(self, z):
# Reshape noise from (batch, latent_dim) to (batch, latent_dim, 1, 1)
z = z.view(z.size(0), -1, 1, 1)
img = self.model(z)
return img
# --- 3. Data Loading ---
# We need to normalize MNIST images to be in the range [-1, 1] to match the Tanh output
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5])
])
mnist_dataset = MNIST(root="./data", train=True, download=True, transform=transform)
dots_loader = DataLoader(mnist_dataset, batch_size=BATCH_SIZE_DOTS, shuffle=True, num_workers=4)
# --- 4. The Custom Loss Function ---
def calculate_euclidean_loss(apples, dots):
"""
Calculates the loss as described:
mean(
mean(euclidean_dist(apple_i, all_dots)) -
mean(euclidean_dist(apple_i, all_apples)) / 2
)
where the outer mean is over all apples in the batch.
"""
num_apples = apples.shape[0]
num_dots = dots.shape[0]
# Flatten images into vectors for distance calculation
# Shape: (batch_size, num_pixels)
apples_flat = apples.view(num_apples, -1)
dots_flat = dots.view(num_dots, -1)
# Use torch.cdist for efficient pairwise distance calculation
# It calculates the p-norm distance between each pair of rows. p=2 is Euclidean.
# 1. Attraction term: Distance from each apple to each dot
# Shape: (num_apples, num_dots) -> (64, 512)
dist_apple_to_dot = torch.cdist(apples_flat, dots_flat, p=2)
# Average distance from each apple to the cloud of dots
# Shape: (num_apples,) -> (64,)
mean_dist_to_dots = torch.mean(dist_apple_to_dot, dim=1)
# 2. Repulsion term: Distance from each apple to each other apple
# Shape: (num_apples, num_apples) -> (64, 64)
dist_apple_to_apple = torch.cdist(apples_flat, apples_flat, p=2)
# Average distance from each apple to all other apples (including itself, dist=0)
# Shape: (num_apples,) -> (64,)
mean_dist_to_apples = torch.mean(dist_apple_to_apple, dim=1)
# 3. Combine terms for each apple as per the formula
# The repulsion term is divided by 2 as requested
loss_per_apple = mean_dist_to_dots - (mean_dist_to_apples / 2.0)
# 4. Final loss is the mean over all apples in the batch
total_loss = torch.mean(loss_per_apple)
return total_loss
# --- 5. The Training Function ---
def train_model():
"""
Main training loop with the custom loss and fast learning schedule.
"""
# Initialize model, optimizer, and scheduler
generator = Generator(LATENT_DIM, CHANNELS, IMG_SIZE).to(device)
generator.train() # Set model to training mode
# Fast Learning Schedule: Adam with a StepLR scheduler
optimizer = optim.Adam(generator.parameters(), lr=LR, betas=(BETA1, 0.999))
# The scheduler will decrease the learning rate by a factor of 0.5 every 5 epochs
scheduler = StepLR(optimizer, step_size=5, gamma=0.5)
print("Starting Training Loop...")
# Use an iterator for the dots_loader to fetch a new batch of dots every step
dots_iterator = iter(dots_loader)
# Fixed noise for consistent visualization of progress
fixed_noise = torch.randn(BATCH_SIZE_APPLES, LATENT_DIM, device=device)
for epoch in range(EPOCHS):
# We'll run 200 steps per epoch. This is arbitrary but gives enough training time.
for i in range(200):
# --- Get Data ---
# 1. Generate a batch of "apples"
noise = torch.randn(BATCH_SIZE_APPLES, LATENT_DIM, device=device)
generated_apples = generator(noise)
# 2. Get a batch of real "dots"
try:
real_dots, _ = next(dots_iterator)
except StopIteration:
# Restart the iterator if the dataset is exhausted
dots_iterator = iter(dots_loader)
real_dots, _ = next(dots_iterator)
real_dots = real_dots.to(device)
# --- Training Step ---
# 1. Zero the gradients
generator.zero_grad()
# 2. Calculate the custom loss
loss = calculate_euclidean_loss(generated_apples, real_dots)
# 3. Backpropagate the loss and update weights
loss.backward()
optimizer.step()
# --- Logging and Visualization ---
if i % 50 == 0:
print(
f"[Epoch {epoch}/{EPOCHS}] [Step {i}/200] "
f"[Loss: {loss.item():.4f}] [LR: {scheduler.get_last_lr()[0]:.6f}]"
)
# After each epoch, update the learning rate
scheduler.step()
# Save a grid of generated images to see the progress
with torch.no_grad():
generator.eval() # Set model to evaluation mode for inference
fixed_apples = generator(fixed_noise).detach().cpu()
vutils.save_image(
fixed_apples,
f"generated_images/epoch_{epoch}.png",
normalize=True,
nrow=8
)
generator.train() # Set back to training mode
print("Training finished.")
# Save the trained model
torch.save(generator.state_dict(), "generator.pth")
# --- Main execution ---
if __name__ == "__main__":
train_model()
How to Run the Code
- Prerequisites: Make sure you have PyTorch and Torchvision installed.
pip install torch torchvision numpy
- Save the Code: Save the code above as a Python file (e.g.,
train_custom_loss.py).
- Execute: Run the script from your terminal.
python train_custom_loss.py
Explanation of Key Parts
- Generator (
Generator): This is a fairly standard architecture that uses ConvTranspose2d layers to upsample a random noise vector into an image. The final Tanh activation function means the output pixel values are between -1 and 1.
- Data Normalization: Because the generator outputs values in
[-1, 1], the real MNIST images ("dots") are also normalized to the same range using transforms.Normalize([0.5], [0.5]). This is crucial for the distance calculation to be meaningful.
- Loss Function (
calculate_euclidean_loss):
- It takes the batch of 64 generated
apples and 512 real dots.
apples.view(num_apples, -1) flattens each [1, 28, 28] image into a vector of 784 pixels.
torch.cdist(..., p=2) is a highly optimized function for calculating all pairwise Euclidean distances between two sets of vectors. It's much faster than using manual loops.
- The rest of the function directly implements your formula by taking the means across the correct dimensions (
dim=1).
- Fast Learning Schedule:
- Optimizer: We use
Adam with lr=0.0002 and beta1=0.5. These are standard, high-performing parameters for training GAN-like models, known to lead to stable and relatively fast convergence.
- Scheduler:
StepLR with step_size=5 and gamma=0.5 provides a simple yet effective fast schedule. It will run with the initial learning rate for 5 epochs, then cut it in half, run for another 5, cut it in half again, and so on. This helps the model make large progress initially and then fine-tune as training progresses.
- Training Loop (
train_model):
- The
dots_iterator is a neat way to ensure you get a new batch of 512 dots for every single training step, which is what the logic requires.
- A
fixed_noise vector is used at the end of each epoch to generate images. This is a great debugging and visualization tool because you can see how the same input noise evolves into a better image over time, showing true learning rather than random changes. The results are saved in the generated_images folder.