Bird
Raised Fist0
Computer Visionml~5 mins

GAN for image generation in Computer Vision

Choose your learning style10 modes available
Introduction
GANs help computers create new images that look real by learning from many example pictures.
Creating new artwork or photos that don't exist yet.
Improving blurry or low-quality images.
Making realistic faces for games or movies.
Generating images for training other AI models when data is limited.
Syntax
Computer Vision
class Generator(nn.Module):
    def __init__(self):
        super().__init__()
        # layers to create images from noise

class Discriminator(nn.Module):
    def __init__(self):
        super().__init__()
        # layers to decide if image is real or fake

# Training loop:
for epoch in range(num_epochs):
    # Train discriminator on real and fake images
    # Train generator to fool discriminator
Generator creates fake images from random noise.
Discriminator learns to tell real images from fake ones.
Examples
Generate fake images by giving random noise to the generator.
Computer Vision
noise = torch.randn(batch_size, noise_dim)
fake_images = generator(noise)
Discriminator predicts if images are real or fake.
Computer Vision
real_preds = discriminator(real_images)
fake_preds = discriminator(fake_images.detach())
Generator tries to make discriminator think fake images are real.
Computer Vision
loss_gen = loss_function(discriminator(fake_images), real_labels)
Sample Model
This code creates a simple GAN with a generator and discriminator. It trains both for one step using random data to show how losses change.
Computer Vision
import torch
import torch.nn as nn
import torch.optim as optim

# Simple Generator
class Generator(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Linear(100, 256),
            nn.ReLU(True),
            nn.Linear(256, 784),
            nn.Tanh()
        )
    def forward(self, x):
        return self.model(x)

# Simple Discriminator
class Discriminator(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Linear(784, 256),
            nn.LeakyReLU(0.2, inplace=True),
            nn.Linear(256, 1),
            nn.Sigmoid()
        )
    def forward(self, x):
        return self.model(x)

# Initialize models
G = Generator()
D = Discriminator()

# Loss and optimizers
criterion = nn.BCELoss()
optimizer_G = optim.Adam(G.parameters(), lr=0.001)
optimizer_D = optim.Adam(D.parameters(), lr=0.001)

# Training data: random real images (for demo)
real_images = torch.randn(16, 784)
real_labels = torch.ones(16, 1)
fake_labels = torch.zeros(16, 1)

# Training loop for 1 epoch
for epoch in range(1):
    # Train Discriminator
    optimizer_D.zero_grad()
    outputs_real = D(real_images)
    loss_real = criterion(outputs_real, real_labels)

    noise = torch.randn(16, 100)
    fake_images = G(noise)
    outputs_fake = D(fake_images.detach())
    loss_fake = criterion(outputs_fake, fake_labels)

    loss_D = loss_real + loss_fake
    loss_D.backward()
    optimizer_D.step()

    # Train Generator
    optimizer_G.zero_grad()
    outputs = D(fake_images)
    loss_G = criterion(outputs, real_labels)
    loss_G.backward()
    optimizer_G.step()

    print(f"Epoch {epoch+1} | Loss D: {loss_D.item():.4f} | Loss G: {loss_G.item():.4f}")
OutputSuccess
Important Notes
GAN training can be tricky; losses may not always decrease smoothly.
Use real datasets like MNIST or CIFAR for better results.
Normalize images between -1 and 1 when using Tanh activation.
Summary
GANs have two parts: a generator that makes images and a discriminator that checks them.
They learn together by competing, improving image quality over time.
You can use GANs to create new, realistic images from random noise.

Practice

(1/5)
1. What are the two main parts of a GAN used for image generation?
easy
A. Convolution and Pooling
B. Encoder and Decoder
C. Input Layer and Output Layer
D. Generator and Discriminator

Solution

  1. Step 1: Understand GAN components

    A GAN consists of two parts: a generator that creates images and a discriminator that evaluates them.
  2. Step 2: Match parts to options

    Only Generator and Discriminator correctly names these two parts as Generator and Discriminator.
  3. Final Answer:

    Generator and Discriminator -> Option D
  4. Quick Check:

    GAN parts = Generator and Discriminator [OK]
Hint: Remember GAN = Generator + Discriminator [OK]
Common Mistakes:
  • Confusing GAN parts with autoencoder parts
  • Thinking GAN uses Encoder and Decoder
  • Mixing up layers with GAN components
2. Which of the following is the correct way to define the generator model in PyTorch for a GAN?
easy
A. generator = nn.Sequential(nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 100), nn.Softmax())
B. generator = nn.Sequential(nn.Conv2d(1, 64, 3), nn.Sigmoid())
C. generator = nn.Sequential(nn.Linear(100, 256), nn.ReLU(), nn.Linear(256, 784), nn.Tanh())
D. generator = nn.Sequential(nn.ConvTranspose2d(100, 1, 3), nn.ReLU())

Solution

  1. Step 1: Identify generator input and output sizes

    The generator takes a noise vector (size 100) and outputs an image vector (size 784 for 28x28 images).
  2. Step 2: Check model layers and activations

    generator = nn.Sequential(nn.Linear(100, 256), nn.ReLU(), nn.Linear(256, 784), nn.Tanh()) correctly uses Linear layers from 100 to 256 to 784 with ReLU and Tanh activations, common in GAN generators.
  3. Final Answer:

    generator = nn.Sequential(nn.Linear(100, 256), nn.ReLU(), nn.Linear(256, 784), nn.Tanh()) -> Option C
  4. Quick Check:

    Generator input=100, output=784 with ReLU and Tanh [OK]
Hint: Generator maps noise to image size with Linear + Tanh [OK]
Common Mistakes:
  • Using Conv2d instead of Linear for generator input
  • Reversing input-output sizes
  • Using Softmax instead of Tanh at output
3. Given this PyTorch snippet for a GAN training step, what will be the shape of the generated images tensor?
noise = torch.randn(16, 100)
generated_images = generator(noise)
medium
A. (16, 784)
B. (16, 100)
C. (100, 16)
D. (784, 16)

Solution

  1. Step 1: Understand input noise shape

    The noise tensor has shape (16, 100), meaning batch size 16 and noise vector length 100.
  2. Step 2: Check generator output shape

    The generator maps each noise vector of size 100 to an image vector of size 784, so output shape is (16, 784).
  3. Final Answer:

    (16, 784) -> Option A
  4. Quick Check:

    Batch size 16, output image size 784 [OK]
Hint: Output shape matches batch size and image vector size [OK]
Common Mistakes:
  • Confusing input noise shape with output shape
  • Swapping batch size and feature dimensions
  • Assuming output shape is (16, 100)
4. You have this error during GAN training: RuntimeError: size mismatch in Linear layer. What is the most likely cause?
medium
A. The input noise vector size does not match the first Linear layer input size
B. The discriminator output is not a probability
C. The generator uses ReLU instead of Tanh
D. The batch size is too large

Solution

  1. Step 1: Understand size mismatch error

    This error usually means the input tensor size does not match the expected input size of a Linear layer.
  2. Step 2: Identify likely cause in GAN

    If the noise vector size does not match the first Linear layer's input features in the generator, this error occurs.
  3. Final Answer:

    The input noise vector size does not match the first Linear layer input size -> Option A
  4. Quick Check:

    Size mismatch = input noise size error [OK]
Hint: Check noise vector size matches Linear layer input [OK]
Common Mistakes:
  • Blaming activation functions for size errors
  • Thinking batch size causes size mismatch
  • Ignoring input dimension mismatch
5. You want to improve the quality of images generated by your GAN. Which of these strategies is most effective?
hard
A. Increase the size of the noise vector and train longer
B. Use a deeper generator and discriminator with batch normalization
C. Remove the discriminator and train only the generator
D. Use random labels instead of real/fake labels for training

Solution

  1. Step 1: Consider model architecture improvements

    Deeper networks with batch normalization help stabilize training and improve image quality.
  2. Step 2: Evaluate other options

    Increasing noise size alone or removing discriminator harms quality; random labels confuse training.
  3. Final Answer:

    Use a deeper generator and discriminator with batch normalization -> Option B
  4. Quick Check:

    Better architecture + batch norm = improved GAN images [OK]
Hint: Better models + batch norm improve GAN image quality [OK]
Common Mistakes:
  • Thinking bigger noise vector alone improves quality
  • Removing discriminator to simplify training
  • Using random labels instead of correct ones
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard