<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kashika Singh  on Medium]]></title>
        <description><![CDATA[Stories by Kashika Singh  on Medium]]></description>
        <link>https://medium.com/@kashika.singh.btech2022?source=rss-4ad64be1929a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Mk5CLxSlM2QuyBEn</url>
            <title>Stories by Kashika Singh  on Medium</title>
            <link>https://medium.com/@kashika.singh.btech2022?source=rss-4ad64be1929a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:44:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kashika.singh.btech2022/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Comparing GAN Variants on Medical Imaging: LSGAN, WGAN, and WGAN-GP with MedMNIST Pneumonia Dataset]]></title>
            <link>https://medium.com/@kashika.singh.btech2022/comparing-gan-variants-on-medical-imaging-lsgan-wgan-and-wgan-gp-with-medmnist-pneumonia-dataset-45d18f7e7214?source=rss-4ad64be1929a------2</link>
            <guid isPermaLink="false">https://medium.com/p/45d18f7e7214</guid>
            <dc:creator><![CDATA[Kashika Singh ]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 09:33:16 GMT</pubDate>
            <atom:updated>2025-04-16T09:33:16.958Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re diving into the world of GANs and biomedical data, this post will walk you through building and training a basic GAN model using the MedMNIST Pneumonia dataset. Along the way, I’ll share how the models were implemented from scratch, what kind of results were generated, and how visualizations helped evaluate progress.</p><h3>Why GANs?</h3><p>Generative Adversarial Networks (GANs) are a powerful framework in deep learning that generate new data samples from learned data distributions. They’re widely used in areas like art generation, data synthesis, and even medical imaging. However, training a GAN is tricky — stability and convergence often depend on the design of the generator and discriminator and how they’re optimized.</p><p>This experiment aims to explore those challenges using the PneumoniaMNIST subset from MedMNIST.</p><h3>Dataset: PneumoniaMNIST from MedMNIST</h3><p>To begin, I used the <strong>PneumoniaMNIST</strong> dataset from the MedMNIST collection. This subset contains grayscale chest X-ray images labeled for binary classification (pneumonia vs. normal). I applied a transformation to convert images to tensors and normalize them for better model training.</p><p>Here’s a breakdown of how the dataset was prepared:</p><ul><li><strong>Imported</strong> the PneumoniaMNIST dataset from the medmnist library</li><li><strong>Applied</strong> a transformation using ToTensor() and Normalize() to scale pixel values</li><li><strong>Loaded</strong> the training data with a batch size of 64 using PyTorch’s DataLoader</li></ul><p><strong>Steps:</strong></p><ol><li>Import the dataset using:<br>from medmnist import PneumoniaMNIST</li><li>Define the image transformation:<br>transforms.Compose([ToTensor(), Normalize(mean=[0.5], std=[0.5])])</li><li>Load the dataset for the ‘train’ split with downloading enabled:<br>PneumoniaMNIST(split=&quot;train&quot;, download=True, transform=transform)</li><li>Wrap the dataset in a DataLoader for batching and shuffling:<br>DataLoader(train_dataset, batch_size=64, shuffle=True)</li></ol><p>This simple setup made it easy to feed real medical data into the GAN for training.</p><h3>Building the GAN: Generator vs. Discriminator</h3><p>To generate realistic images from noise, I implemented a <strong>simple yet effective GAN architecture</strong> using PyTorch. GANs consist of two core components: a Generator (G) and a Discriminator (D), which compete in a zero-sum game. While the Generator learns to produce synthetic images, the Discriminator learns to distinguish between real and fake ones.</p><h4>Generator Architecture</h4><p>The <strong>Generator</strong> takes in a random noise vector (often called latent vector) and transforms it into a synthetic 28x28 grayscale image that mimics the dataset distribution.</p><p>Key architectural choices:</p><p><strong>Input</strong>: A 100-dimensional noise vector sampled from a standard normal distribution.</p><p><strong>Hidden Layers</strong>:</p><ul><li>First linear layer with 128 units</li><li>Second linear layer with 256 units</li><li>Activation function: <strong>ReLU</strong> after each hidden layer for non-linearity</li></ul><p><strong>Output Layer</strong>:</p><ul><li>One final linear layer projecting to 784 units (28×28 pixels)</li><li><strong>Tanh activation</strong> to scale pixel values between -1 and 1 (matching the normalized input)</li></ul><p>This design is intentionally simple to demonstrate the foundational mechanics of a GAN. Despite its simplicity, it learns to generate fairly structured and meaningful outputs over time.</p><h4>Discriminator Architecture</h4><p>The <strong>Discriminator</strong> is essentially a binary classifier. It evaluates images (either real from the dataset or fake from the generator) and tries to classify them as real (label 1) or fake (label 0).</p><p>Key architectural components:</p><p><strong>Input</strong>: Flattened image of shape 28x28 (784-dimensional vector)</p><p><strong>Hidden Layers</strong>:</p><ul><li>First linear layer with 256 units</li><li>Activation function: <strong>LeakyReLU</strong> to allow a small gradient flow even when neurons are not activated</li></ul><p><strong>Output Layer</strong>:</p><ul><li>One linear layer with a single unit</li><li><strong>Sigmoid activation</strong> to return a probability between 0 and 1</li></ul><p>The Discriminator is trained to become very good at identifying subtle features that distinguish real images from generated ones — which in turn forces the Generator to improve its outputs.</p><h4>Why This Architecture?</h4><p>While convolutional layers usually perform better for image data, I opted for fully connected (linear) layers in this experiment for clarity and ease of understanding. The goal was to:</p><ul><li>Keep the architecture lightweight</li><li>Train faster on limited hardware</li><li>Focus on the <strong>training dynamics of GANs</strong> rather than architectural complexity</li></ul><p>This minimal design still captures the essence of adversarial learning and works well on smaller datasets like PneumoniaMNIST.</p><h3>Training Setup: Behind the Scenes of Adversarial Learning</h3><p>Once the GAN architecture was built, the next step was training it — which is where the real magic (and chaos) of GANs happens. GAN training is notoriously unstable, and small tweaks in setup can lead to drastically different results.</p><p>Here’s how I structured the training process:</p><ul><li><strong>Loss Function</strong>: Binary Cross-Entropy Loss (BCE)<br>Used for both Generator and Discriminator. BCE works well for the binary classification task the Discriminator handles — distinguishing real from fake.</li><li><strong>Optimizers</strong>: Adam<br>Both models used the Adam optimizer with a learning rate of 0.0002 and betas (0.5, 0.999). These hyperparameters are widely recommended for GANs because they stabilize the training process.</li><li><strong>Latent Dimension</strong>: 100<br>The input noise vector for the Generator had 100 dimensions, sampled from a standard normal distribution. This latent space is where the “creativity” of the Generator originates.</li><li><strong>Device</strong>: CPU or CUDA<br>The training automatically detects and uses a GPU (CUDA) if available, which significantly speeds up the process.</li><li><strong>Epochs</strong>: 50<br>The model was trained for 50 full passes over the training dataset.</li><li><strong>Batch Size</strong>: 64<br>Balanced between speed and diversity in each training step.</li></ul><h3>Training Loop: Step-by-Step Workflow</h3><p>Each training epoch involves two main phases — one for the Discriminator and one for the Generator. Here’s how they interact in each iteration:</p><ol><li><strong>Discriminator Training</strong></li></ol><ul><li>Takes a batch of real images from the dataset</li><li>Generates a batch of fake images using the Generator</li><li>Calculates BCE loss on both real and fake images</li><li>Updates weights to better classify real vs. fake</li></ul><p><strong>2. Generator Training</strong></p><ul><li>Takes a fresh batch of noise vectors</li><li>Produces fake images</li><li>Passes them through the Discriminator</li><li>Calculates loss based on how well it fooled the Discriminator</li><li>Updates Generator to create more “real-looking” images</li></ul><p>This adversarial cycle repeats over and over, gradually improving both models through competition.</p><h3>Training Insights: What the Numbers (and Curves) Told Me</h3><p>Watching a GAN train is part science, part art. The metrics only tell half the story — the rest comes from <strong>visual feedback</strong>.</p><p>Here’s what stood out:</p><ul><li><strong>Generator Loss</strong>:<br>Decreased gradually over time, suggesting that the Generator was learning to produce more convincing images.</li><li><strong>Discriminator Loss</strong>:<br>Showed regular fluctuations — a good sign in GAN training. It means both models are actively learning and adapting.</li><li><strong>Visual Inspection</strong>:<br>Around epoch 30, the generated images began to show visible structure, moving beyond noisy blobs and starting to resemble actual chest X-rays.</li><li><strong>TensorBoard Visualization</strong>:<br>Losses and model graphs were logged using TensorBoard, offering a real-time view of training progress. This made it easy to spot if either model started to dominate (which could lead to mode collapse).</li></ul><h3>Diving Deeper: Comparing LSGAN, WGAN, and WGAN-GP</h3><p>After building and training a vanilla GAN, the next step was to explore advanced GAN variants that promise improved stability and image quality. I implemented and compared three popular GAN variants:</p><ul><li>LSGAN (Least Squares GAN)</li><li>WGAN (Wasserstein GAN)</li><li>WGAN-GP (Wasserstein GAN with Gradient Penalty)</li></ul><p>Each model was trained from scratch using the PneumoniaMNIST dataset, and evaluated based on both quantitative metrics and visual inspection.</p><h3>LSGAN — Least Squares GAN</h3><p><strong>Concept</strong>:<br>LSGAN modifies the loss function of the traditional GAN by replacing binary cross-entropy with <strong>least squares loss</strong>. The motivation is to overcome the issue of vanishing gradients, which often stalls training in vanilla GANs.</p><p><strong>Loss Function</strong>:</p><ul><li>Discriminator minimizes:<br>(D(x) - 1)² + (D(G(z)))²</li><li>Generator minimizes:<br>(D(G(z)) - 1)²</li></ul><p><strong>Why it matters</strong>:<br>By penalizing predictions that are far from the target value, the gradient signal is stronger and more informative — especially during the early stages of training.</p><p><strong>Pros</strong>:</p><ul><li>Easier convergence than vanilla GANs</li><li>Smooth gradient flow for Generator</li><li>Simple to implement</li></ul><p><strong>Cons</strong>:</p><ul><li>Prone to blurry outputs</li><li>Can still suffer from mode collapse</li><li>Doesn’t significantly improve diversity</li></ul><p><strong>Results</strong>:</p><ul><li><strong>Image Quality</strong>: Basic structure, lacking texture</li><li><strong>Training Stability</strong>: Moderate, some fluctuations</li><li><strong>Visuals</strong>: Passable but lacked realism</li></ul><h3>WGAN — Wasserstein GAN</h3><p>Concept:<br>WGAN introduces the Wasserstein (Earth Mover’s) distance as a measure of distribution divergence, offering smoother and more meaningful gradients. It moves away from a probabilistic classification-based loss to a more continuous distance metric.</p><p><strong>Loss Function</strong>:</p><ul><li>Discriminator becomes a “critic” (no Sigmoid)</li><li>Loss = difference in critic scores between real and fake images</li></ul><p><strong>Key Innovation</strong>:<br><strong>Weight clipping</strong> is used to enforce the Lipschitz constraint, which is crucial for the Wasserstein distance to be valid.</p><p><strong>Pros</strong>:</p><ul><li>Stable training</li><li>Solves vanishing gradient issues</li><li>Handles mode collapse better</li></ul><p><strong>Cons</strong>:</p><ul><li>Requires careful tuning of weight clipping range</li><li>Sometimes underfits due to weight clipping</li><li>Sensitive to architecture choices</li></ul><p><strong>Results</strong>:</p><ul><li><strong>Image Quality</strong>: Better contrast and shape structure</li><li><strong>Training Stability</strong>: Smooth but critic loss spiked occasionally</li><li><strong>Visuals</strong>: More coherent patterns resembling lung structures</li></ul><h3>WGAN-GP — WGAN with Gradient Penalty</h3><p><strong>Concept</strong>:<br>WGAN-GP improves on WGAN by <strong>replacing weight clipping with a gradient penalty</strong>. This makes the enforcement of the Lipschitz constraint much more effective and leads to <strong>faster and more stable convergence</strong>.</p><p><strong>Gradient Penalty Term</strong>:<br>Adds an extra loss component that penalizes gradients that deviate from a norm of 1:</p><pre>λ * (||∇(D(ẋ))||₂ - 1)²</pre><p>Where ẋ is a linear combination of real and fake data.</p><p><strong>Pros</strong>:</p><ul><li>Most stable GAN variant in this comparison</li><li>Produces high-quality, sharp images</li><li>Easier to tune than WGAN</li></ul><p><strong>Cons</strong>:</p><ul><li>More computationally intensive</li><li>Training can be slower per epoch</li></ul><p><strong>Results</strong>:</p><ul><li><strong>Image Quality</strong>: Most detailed and defined</li><li><strong>Training Stability</strong>: Smoothest loss curves observed</li><li><strong>Visuals</strong>: Clear lung contours and texture — very promising</li></ul><h3>Evaluation: How Did I Measure Performance?</h3><p>GANs are tricky to evaluate. Unlike classifiers, they don’t output accuracy scores. So I used a mix of <strong>quantitative metrics</strong> and <strong>qualitative visuals</strong>.</p><h3>Metrics Used</h3><ol><li><strong>Visual Inspection</strong>:<br>Observed the generated images across training epochs. I focused on clarity, structure, and realism in the outputs.</li><li><strong>Loss Curve Analysis</strong>:<br>Logged Generator and Discriminator losses using TensorBoard to evaluate:</li></ol><ul><li>Stability of convergence</li><li>Relative dominance of either model</li><li>Frequency of spikes or oscillations</li></ul><p><strong>3. </strong>Quantitative GAN Metrics like:</p><ul><li><strong>Inception Score (IS)</strong> — Measures how realistic and diverse the images are</li><li><strong>Fréchet Inception Distance (FID)</strong> — Compares distributions of real vs. fake images</li></ul><h3>Summary of Model Performance</h3><p><strong>Results:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_JfgwGwjweTSpfn-X7yRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lD4hgTroNF4t90QylavoWQ.png" /></figure><h3>Key Learnings</h3><p>Every GAN experiment teaches you something new. Here’s what stood out in this project:</p><ul><li><strong>Hyperparameters Matter</strong>: Especially learning rates, optimizer betas, and batch size. Even slight changes can lead to divergence.</li><li><strong>Normalization is Crucial</strong>: Normalizing both inputs and outputs to the same scale (in this case, -1 to 1 using Tanh and Normalize) ensured smoother gradients and better convergence.</li><li><strong>Visual Debugging is Powerful</strong>: No metric beats actually looking at the generated samples over time.</li><li><strong>Simple Models Can Still Shine</strong>: Even without convolutional layers or advanced loss functions, meaningful results can be achieved.</li></ul><h3>Future Scope: Where to Go From Here</h3><p>This project was a foundational exploration — but GANs have so much more to offer. Some next steps I’d love to explore:</p><ul><li><strong>Quantitative Evaluation</strong>: Use metrics like Fréchet Inception Distance (FID) or Inception Score (IS) for a numerical comparison.</li><li><strong>Model Variants</strong>: Try out LSGAN, WGAN, and WGAN-GP to see how training stability and image quality improve.</li><li><strong>Convolutional Architectures</strong>: Replace linear layers with Conv2D and ConvTranspose2D for more spatially aware image generation.</li><li><strong>Larger Datasets</strong>: Expand the training to multi-class datasets like PathMNIST or OrganMNIST.</li><li><strong>Conditional GANs</strong>: Generate class-specific samples by conditioning on labels.</li></ul><h3>Which GAN Performed Best?</h3><p>After implementing, training, and analyzing all three models — <strong>LSGAN</strong>, <strong>WGAN</strong>, and <strong>WGAN-GP</strong> — the results were clear:</p><h3>Winner: WGAN-GP (Wasserstein GAN with Gradient Penalty)</h3><p>WGAN-GP stood out as the most robust and reliable GAN architecture in this experiment. Here’s why:</p><ul><li><strong>Stability</strong>: Training curves were consistently smooth, without spikes or collapse. This indicates balanced learning between the Generator and Discriminator.</li><li><strong>Image Quality</strong>: The generated outputs had the sharpest patterns, most realistic textures, and resembled medical imagery more closely than any other variant.</li><li><strong>Convergence</strong>: WGAN-GP converged steadily, with minimal tuning compared to WGAN’s clip-value sensitivity and LSGAN’s instability.</li><li><strong>Scalability</strong>: The architecture showed promise for scaling to more complex datasets or larger images, making it a future-proof choice.</li></ul><h3>Runner-Up: WGAN</h3><p>WGAN also performed well — offering better visuals and more stable training than LSGAN — but it required <strong>careful clipping and parameter tuning</strong>, and the outputs, while improved, lacked the finer texture that WGAN-GP achieved.</p><h3>Trailing: LSGAN</h3><p>LSGAN served as a great baseline, but its outputs lacked detail and definition. While it’s easier to implement and train, the model plateaued early, and generated images were noticeably blurrier and less structured.</p><h3>Conclusion</h3><p>This project was an eye-opener into the world of advanced GAN architectures. Starting from a basic GAN trained on the PneumoniaMNIST dataset, I explored how subtle changes in loss functions and training strategies can drastically impact results.</p><p>From the <strong>blurry, basic outputs of LSGAN</strong>, to the <strong>structured but sensitive WGAN</strong>, and finally to the <strong>sharp, stable results from WGAN-GP</strong>, the journey highlighted one key lesson: <strong>architecture and stability matter just as much as data</strong>.</p><p>WGAN-GP proved to be the most effective — delivering consistent training performance and the most realistic images. It’s a great reminder that when working with generative models, especially in critical domains like medical imaging, <strong>choosing the right architecture can make all the difference</strong>.</p><p>Whether you’re a beginner experimenting with PyTorch or a researcher working on biomedical data synthesis, this project offers a clear path forward:</p><ul><li>Start simple, but don’t stop there.</li><li>Use visualizations to guide your training.</li><li>Always back intuition with metrics.</li></ul><p>And most importantly — <strong>never underestimate the power of a well-tuned GAN</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45d18f7e7214" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>