### Train WGAN with Adam Optimizer Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Command to train a Wasserstein GAN using the Adam optimizer instead of the default RMSprop. This example uses a custom image folder as the dataset. ```bash python main.py \ --dataset folder \ --dataroot /data/my_images \ --cuda \ --adam \ --lrD 0.00005 \ --lrG 0.00005 \ --experiment samples_adam ``` -------------------------------- ### Reproduce LSUN Experiments with DCGAN Source: https://github.com/martinarjovsky/wassersteingan/blob/master/README.md Command to run the LSUN dataset experiment using the DCGAN architecture. Ensure you have the LSUN dataset downloaded and specify its path. ```bash python main.py --dataset lsun --dataroot [lsun-train-folder] --cuda ``` -------------------------------- ### Generate Images from WGAN Checkpoint (GPU) Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Script to generate images using a pre-trained WGAN generator. Loads the generator configuration and weights, specifying the output directory, number of images to generate, and enabling GPU acceleration. ```bash python generate.py \ --config samples_lsun/generator_config.json \ --weights samples_lsun/netG_epoch_24.pth \ --output_dir generated_images/ \ --nimages 16 \ --cuda ``` -------------------------------- ### Resume WGAN Training from Checkpoint Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Command to resume training of a Wasserstein GAN from previously saved generator and discriminator checkpoints. Specifies the paths to the checkpoint files. ```bash python main.py \ --dataset lsun \ --dataroot /data/lsun \ --cuda \ --netG samples_lsun/netG_epoch_10.pth \ --netD samples_lsun/netD_epoch_10.pth \ --experiment samples_lsun ``` -------------------------------- ### Generate Single Image with WGAN (CPU) Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Command to generate a single image using a trained WGAN generator on the CPU. Uses shorthand arguments for configuration, weights, output directory, and number of images. ```bash python generate.py \ -c samples_mlp/generator_config.json \ -w samples_mlp/netG_epoch_49.pth \ -o outputs/ \ -n 1 ``` -------------------------------- ### Loss Monitoring and Median Filtering Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Monitors WGAN training using negated critic loss and applies median filtering for smooth learning curves. Requires numpy, scipy, and matplotlib. ```python import numpy as np import scipy.signal # Collect Loss_D values from training logs # Example log line: "[0/25][500/1000][500] Loss_D: -0.4521 ..." loss_d_values = [-0.45, -0.38, -0.31, -0.28, -0.22, -0.19, -0.15] # parsed from stdout # Negate and median-filter to reproduce paper curves loss_d_array = np.array(loss_d_values, dtype='float64') med_filtered_loss = scipy.signal.medfilt(-loss_d_array, 101) # kernel=101 as in paper # Plot with matplotlib import matplotlib.pyplot as plt plt.plot(-loss_d_array, alpha=0.4, label='Raw -Loss_D') plt.plot(med_filtered_loss, label='Median filtered (k=101)') plt.xlabel('Generator iterations') plt.ylabel('Wasserstein estimate') plt.legend() plt.savefig('learning_curve.png') # A rising curve = generator improving # Sudden drop = critic drifted from optimum (try lower LR or more Diters) ``` -------------------------------- ### DCGAN Generator Implementation Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Builds and uses a DCGAN generator. Outputs images squashed to [-1, 1] via Tanh. Custom weight initialization is applied. Requires PyTorch and torchvision. ```python import torch from torch.autograd import Variable from models import dcgan # Build generator: output 64x64 RGB, latent dim 100, 64 base filters netG = dcgan.DCGAN_G(isize=64, nz=100, nc=3, ngf=64, ngpu=1, n_extra_layers=0) # No-BN variant netG_nobn = dcgan.DCGAN_G_nobn(isize=64, nz=100, nc=3, ngf=64, ngpu=1) # Custom weight initialization (normal distribution, as used in main.py) def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: m.weight.data.normal_(0.0, 0.02) elif classname.find('BatchNorm') != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) netG.apply(weights_init) # Generate a batch of 64 fake images noise = Variable(torch.FloatTensor(64, 100, 1, 1).normal_(0, 1)) fake = netG(noise) print(fake.shape) # torch.Size([64, 3, 64, 64]) print(fake.min(), fake.max()) # values in [-1, 1] due to Tanh # Denormalize to [0, 1] for saving fake_display = fake.data.mul(0.5).add(0.5) import torchvision.utils as vutils vutils.save_image(fake_display, 'generated_grid.png') ``` -------------------------------- ### Train WGAN on CIFAR-10 with MLP (CPU) Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Command to train a Wasserstein GAN on the CIFAR-10 dataset using MLP for both generator and discriminator, running on CPU. Configures network feature dimensions and number of iterations. ```bash python main.py \ --dataset cifar10 \ --dataroot /data/cifar10 \ --mlp_G \ --mlp_D \ --ngf 512 \ --ndf 512 \ --niter 50 \ --experiment samples_mlp ``` -------------------------------- ### Train WGAN on LSUN with DCGAN (GPU) Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Command to train a Wasserstein GAN on the LSUN dataset using a DCGAN architecture with GPU acceleration. Specifies batch size, image size, number of iterations, learning rates, weight clipping range, and critic iterations per generator iteration. ```bash python main.py \ --dataset lsun \ --dataroot /data/lsun \ --cuda \ --batchSize 64 \ --imageSize 64 \ --niter 25 \ --lrD 0.00005 \ --lrG 0.00005 \ --clamp_lower -0.01 \ --clamp_upper 0.01 \ --Diters 5 \ --experiment samples_lsun ``` -------------------------------- ### Reproduce LSUN Experiments with MLP Source: https://github.com/martinarjovsky/wassersteingan/blob/master/README.md Command to run the LSUN dataset experiment using an MLP-based generator. Adjust 'ngf' for generator feature maps. ```bash python main.py --mlp_G --ngf 512 ``` -------------------------------- ### DCGAN Critic Forward Pass and Weight Clamping Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Python code demonstrating the forward pass of the DCGAN critic and the essential weight clamping mechanism for WGANs. The critic outputs a raw score, and its parameters are clamped to a specified range after each critic update. ```python # Forward pass — output is a scalar (no sigmoid) real_images = Variable(torch.FloatTensor(64, 3, 64, 64).normal_(0, 1)) score = netD(real_images) print(score) # tensor([0.0312]) — raw Wasserstein score # Weight clamping (core WGAN constraint, applied each D step) clamp_lower, clamp_upper = -0.01, 0.01 for p in netD.parameters(): p.data.clamp_(clamp_lower, clamp_upper) ``` -------------------------------- ### MLP Generator Implementation Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Builds and uses an MLP generator. Takes a flattened latent vector and reshapes output. Useful as a baseline when spatial bias is not needed. Requires PyTorch. ```python import torch from torch.autograd import Variable from models import mlp # Build MLP generator: 64x64 output, latent 100, 512 hidden units netG_mlp = mlp.MLP_G(isize=64, nz=100, nc=3, ngf=512, ngpu=1) # Noise input shape is (batch, nz, 1, 1) — flattened internally noise = Variable(torch.FloatTensor(32, 100, 1, 1).normal_(0, 1)) fake = netG_mlp(noise) print(fake.shape) # torch.Size([32, 3, 64, 64]) # Train MLP variant from CLI # python main.py --dataset cifar10 --dataroot /data --mlp_G --ngf 512 ``` -------------------------------- ### WGAN Critic Loss Calculation Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Calculates the critic loss for WGAN. Maximizes the score on real data and minimizes it on fake data. Requires PyTorch tensors. ```python one = torch.FloatTensor([1]) mone = one * -1 err_real = netD(real_images) err_real.backward(one) # maximize score on real fake_images = Variable(torch.FloatTensor(64, 3, 64, 64).normal_(0, 1)) err_fake = netD(fake_images) err_fake.backward(mone) # minimize score on fake err_D = err_real - err_fake # Wasserstein estimate (want this large) ``` -------------------------------- ### MLP Critic Implementation Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Builds and uses an MLP critic. Flattens input image internally and returns a single scalar Wasserstein score. Requires PyTorch. ```python import torch from torch.autograd import Variable from models import mlp # Build MLP critic: 64x64 RGB input, 512 hidden units netD_mlp = mlp.MLP_D(isize=64, nz=100, nc=3, ndf=512, ngpu=1) images = Variable(torch.FloatTensor(32, 3, 64, 64).normal_(0, 1)) score = netD_mlp(images) print(score) # tensor([0.0071]) — single scalar, no sigmoid # Train MLP D+G from CLI # python main.py --dataset cifar10 --dataroot /data --mlp_G --mlp_D --ngf 512 --ndf 512 ``` -------------------------------- ### Apply Median Filter to Discriminator Loss Source: https://github.com/martinarjovsky/wassersteingan/blob/master/README.md Python code snippet demonstrating how to apply a median filter to the discriminator loss, as used for reproducing paper curves. Requires scipy. ```python med_filtered_loss = scipy.signal.medfilt(-Loss_D, dtype='float64'), 101) ``` -------------------------------- ### DCGAN Critic Model Definition Source: https://context7.com/martinarjovsky/wassersteingan/llms.txt Python code defining the DCGAN critic (discriminator) model for Wasserstein GANs. This convolutional network takes images and outputs a raw scalar score, crucial for calculating the Wasserstein distance. It supports an optional batch normalization-free variant. ```python import torch from torch.autograd import Variable from models import dcgan # Build critic: 64x64 RGB images, latent dim 100, 64 base filters netD = dcgan.DCGAN_D(isize=64, nz=100, nc=3, ndf=64, ngpu=1, n_extra_layers=0) # No-BN variant for experiments without batch normalization netD_nobn = dcgan.DCGAN_D_nobn(isize=64, nz=100, nc=3, ndf=64, ngpu=1) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.