Views
No views yet
| Component | Details |
|---|---|
| Discriminator | Takes a 1×28×28 grayscale image and a class label (0-9). Embeds the label, expands it to 1×28×28, concatenates with the image, and passes through two downsampling Conv2d blocks (with BatchNorm2d and LeakyReLU). Output is flattened and passed through a Sigmoid activation (1 output). |
| Generator | Takes a 100-dimensional noise vector and a target class label (0-9). Uses embedding layers for the label, concatenates it with noise, and passes through two ConvTranspose2d upsampling blocks (with BatchNorm2d and LeakyReLU). Output uses a Tanh activation function (1×28×28). |
Loss = min_G max_D V(D, G) = E_x[log D(x|y)] + E_z[log(1 - D(G(z|y)|y))]| Loss | Role |
|---|---|
| Discriminator Loss | Penalises the Discriminator for incorrectly classifying real MNIST images as fake, or generated images as real. |
| Generator Loss | Penalises the Generator when the Discriminator successfully identifies its generated images as fake. |
learning_rate {1e-5 to 2e-3}, beta1 {0.0, 0.9}, and noise_dim {50, 100, 128}learning_rate = 0.000112, beta1 = 0.037, noise_dim = 100.0.5 and standard deviation of 0.5, scaling the pixel values to the [-1, 1] range to match the Tanh activation of the Generator.1import torch
2from torch import nn
3from huggingface_hub import hf_hub_download
4import matplotlib.pyplot as plt
5
6class CGAN_Generator(nn.Module):
7 def __init__(self, noise_dim=100, num_classes=10, img_size=28):
8 super().__init__()
9 self.init_size = img_size // 4
10 self.embedding_dim = 20
11 self.label_embedding = nn.Embedding(num_classes, self.embedding_dim)
12
13 self.projection = nn.Sequential(
14 nn.Linear(noise_dim + self.embedding_dim, 128 * self.init_size * self.init_size)
15 )
16
17 self.conv_blocks = nn.Sequential(
18 nn.BatchNorm2d(128),
19 nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1),
20 nn.BatchNorm2d(64),
21 nn.LeakyReLU(0.2, inplace=True),
22 nn.ConvTranspose2d(64, 1, kernel_size=4, stride=2, padding=1),
23 nn.Tanh()
24 )
25
26 def forward(self, noise, labels):
27 label_embed = self.label_embedding(labels)
28 merged_input = torch.cat((noise, label_embed), dim=1)
29 out = self.projection(merged_input)
30 out = out.view(out.shape[0], 128, self.init_size, self.init_size)
31 img = self.conv_blocks(out)
32 return img
33
34model = CGAN_Generator(noise_dim=100)
35
36weights_path = hf_hub_download(repo_id="VioletaR/cgan-mnist", filename="mnist_cgan_generator.pth")
37model.load_state_dict(torch.load(weights_path))
38model.eval()
39
40target_label = torch.tensor([7])
41eval_noise = torch.randn(1, noise_dim)
42
43with torch.no_grad():
44 generated_img = model(eval_noise, target_label)
45
46generated_img = (generated_img + 1) / 2.0
47img_numpy = generated_img.squeeze().cpu().numpy()
48
49plt.imshow(img_numpy, cmap='gray')
50plt.title(f"Generated Label: {target_label.item()}")
51plt.axis('off')
52plt.show()