<?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 RajD on Medium]]></title>
        <description><![CDATA[Stories by RajD on Medium]]></description>
        <link>https://medium.com/@dhyaneshmrthy?source=rss-e090da35a66c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_SY0KSAVx7R05W-L</url>
            <title>Stories by RajD on Medium</title>
            <link>https://medium.com/@dhyaneshmrthy?source=rss-e090da35a66c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:23:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhyaneshmrthy/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[Why GANs Are Hard (And Why Most Fail Quietly)]]></title>
            <link>https://medium.com/@dhyaneshmrthy/why-gans-are-hard-and-why-most-fail-quietly-80961a92c715?source=rss-e090da35a66c------2</link>
            <guid isPermaLink="false">https://medium.com/p/80961a92c715</guid>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[art]]></category>
            <dc:creator><![CDATA[RajD]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 19:33:05 GMT</pubDate>
            <atom:updated>2026-03-30T19:33:05.284Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a distinct moment of happiness when GAN produces something recognizable, the colors align, texture find their rhythm and for a fleeting second, you are convinced you’ve finally bridged the gap between noise and reality.</p><p>But the stability is a mirage. Then the artifacts emerge. Brushstrokes begin to loop in endless patterns; colors drift into digital decay. The illusion shatters.</p><p>Then you realize that GAN is never truly “finished”. It is a negotiation between two neural networks locked in a zero-sum game where the Generator perfects the art of the lie, the Discriminator masters the art of the truth, and progress only exists as long as neither side wins.</p><p>The unique cruelty of a GAN is that its signals are deceptive. Loss curves may be perfect, and metrics can behave.</p><p>At this stage, debugging GANs stops feeling like machine learning and starts feeling like <strong>forensic analysis </strong>— inspecting articafts, tracing subtle instabilities and fixing metrics that refuses to reveal.</p><p>The <strong>full notebook</strong> is on <a href="https://www.kaggle.com/code/rajdhyaneshvar/enhanced-cyclegan-with-resnet?scriptVersionId=288985101"><strong>Kaggle</strong></a> and the code is on <a href="https://github.com/RajDhyaneshvarCJ/Enhanced-CycleGAN-with-RESNET/tree/main"><strong>GitHub</strong></a><strong>.</strong></p><h4><strong>Why CycleGAN Is Still Relevant (in 2025)</strong></h4><p>CycleGAN was introduced in 2017.</p><p>In deep learning years, that’s practically ancient. Yet CycleGAN remains relevant: unpaired translation is still unsolved. While modern models “hallucinate” new details, CycleGAN introduces a simple but powerful idea <strong>Cycle Consistency</strong><em>:</em></p><blockquote>If you translate A→B, you must be able to translate it back</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*SeuYwKL_pw9f32kMrIA7tw.png" /><figcaption>Diagram 1: CycleGAN Cycle Flow</figcaption></figure><p>This Cycle Consistency constraint:</p><ul><li>prevents the generator from hallucinating arbitrarily</li><li>Forces structural preservation</li></ul><p>In the Monet task, this distinction is crucial.<br>A photograph shouldn’t turn into just any painting. It should become <strong>the same photograph</strong>, rewritten in Monet’s visual language</p><h4>Data Matters More Than the Model (Why TFRecords Win)</h4><p>Training a GAN is like trying to keep a high-performance engine running at redline. If the fuel (data) arrives in spurts, the engine chokes.</p><p>GANs are extremely sensitive to input consistency, and small data issues that a classifier might tolerate can quietly destabilize adversarial training.</p><ul><li><strong>The Bottleneck: </strong>Raw JPEGs require the CPU to stop, open a file, decode the compression, and resize causing <strong>variable latency.</strong></li><li><strong>The Consequence:</strong> While the CPU struggles, the GPU/TPU sits idle, causing optimizer to take erratic steps leading to divergence.</li><li><strong>The Solution:</strong> <strong>TFRecords </strong>serialize data into a continuous stream, ensuring the accelerator is always “fed” a perfect, constant batch.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*8OTMJdCRA-d3daMXMVhSPg.png" /><figcaption>Diagram 2: TFRecord pipeline vs raw JPEG</figcaption></figure><p><strong>Normalization</strong> and <strong>shuffling</strong> are just as critical. CycleGAN generators expect inputs scaled to <strong>[-1, 1]</strong>, and even slight mismatches can turn the optimization landscape upside down. Without proper shuffling,the Discriminator will stop looking at your “art” and <strong>start memorizing</strong> the sequence like a cheat code.</p><p>Augmentation is important but in moderation, over augmentation forces generator to try and correct the distortion instead of learning texture and patterns. So the golden rule is stick to Resize, Crop, and Flip — simple spatial jitter.</p><p>So takeaway is that most GAN failures aren’t caused by the bad architectures, they start with poorly prepared data. It’s crucial to fix pipeline before tuning the model.</p><h4>Architecture(Learning what to Change, Not what to Rebuild)</h4><p>After getting the foundational pipeline right, the next focus is the architecture.</p><blockquote>You don’t want your model to reinvent the wheel every time.</blockquote><p>That’s why a ResNet-based generator works so well. Residual Residual blocks act like “delta” updates. The model asks, <em>“What is the minimum change needed to make this look like a Monet?” </em>rather than relearning the entire image from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*QS8ZEU3bckImo_pID0ogvA.png" /><figcaption>Diagram 3: ResNet generator architecture</figcaption></figure><p><strong>Normalization: The Invisible Failure Point</strong></p><p>Normalization quietly plays a critical role. Batch Normalization mixes statistics across images in the batch, which muddies the style of individual outputs. Instance Normalization treats each image as its own universe, computing mean and variance per-channel, per-image. This independence is what keeps colors crisp and textures consistent. The difference rarely shows up in loss curves, but it’s immediately visible in the outputs.</p><p>I implemented Instance Normalization as a custom Keras layer rather than using a library. It’s straightforward: compute per-instance mean and variance across spatial dimensions, normalize, then apply learnable scale and shift parameters. Ten lines of code, but they matter more than most architecture decisions.</p><p><strong>The Discriminator: PatchGAN’s Microscope</strong></p><p>A standard discriminator is a “Yes/No” judge for the whole image. A PatchGAN is a forensic investigator with a magnifying glass. Instead of asking whether an entire image looks real, it evaluates small patches across the image. This forces the generator to get textures right everywhere, not just at a distance. In style transfer, that local pressure makes all the difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*snoynziETT5ILHAOOssIRA.png" /><figcaption>Diagram 4: Single PatchGAN discriminator</figcaption></figure><p>The discriminator stacks four convolutional layers: Conv(64, stride 2) → Conv(128, stride 2) → Conv(256, stride 2) → Conv(512, stride 1), each with 4x4 kernels and LeakyReLU activations. Instance Normalization is applied from the second layer onward. A final Conv(1) layer produces the patch map, a spatial grid of real/fake judgments. The whole thing is compact and fast, which is important because the discriminator runs twice per training step (once for real, once for fake).</p><p>In CycleGAN, success comes from balance. The generator must be expressive but restrained, and the discriminator must be strong but not overwhelming. Bigger models don’t win. Stable ones do.</p><h3>Training Dynamics: Where the Fun Begins (and Ends)</h3><p>Training GAN is less like traditional “optimization” and more like trying to balance a pencil on a moving truck. Adversarial loss alone is not enough, yes it encourages realism but without additional constraints the generator can drift, hallucinate and even collapse. That is why CycleGAN relies on a combination of Adversatial, Cycle Consistency, and Identity losses. Together they define<em> how </em>the model can change the image and to what extent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*RKnokGJ1mEgVL1_PQS5a8Q.png" /><figcaption>Diagram 5: Loss function connections</figcaption></figure><p><strong>Adversarial Loss (LSGAN)</strong></p><p>The classic binary cross-entropy GAN loss has a well-known problem: vanishing gradients. When the discriminator gets too confident, the generator receives almost no useful signal. LSGAN replaces the binary classification with a least-squares objective. The generator tries to make the discriminator output close to 1, and the discriminator tries to output 1 for real images and 0 for fakes. The quadratic penalty means gradients stay informative even when the discriminator is winning. The training signal doesn’t just tell the generator “you’re wrong,” it tells it “you’re this far from right.”</p><pre>L_adv(G) = MSE(D(G(x)), 1)<br><br>L_adv(D) = 0.5 × [ MSE(D(real), 1) + MSE(D(fake), 0) ]</pre><p><strong>Cycle Consistency Loss</strong></p><p>This is the backbone of CycleGAN. If generator G turns photos into Monets and generator F turns Monets into photos, then F(G(photo)) should return the original photo. And G(F(monet)) should return the original Monet. The cycle loss penalizes any deviation, computed as the mean absolute error between the original and the round-tripped image, scaled by a weight of 10.0.</p><pre>L_cyc = λ_cyc × ( mean|x - F(G(x))| + mean|y - G(F(y))| )<br><br>where λ_cyc = 10.0</pre><p>This weight matters more than it looks. Too low and the generator starts hallucinating freely, adding details that have no basis in the input. Too high and the generator becomes timid, barely changing anything. 10.0 is the default from the original CycleGAN paper, and it worked well here.</p><p><strong>Identity Loss</strong></p><p>Identity loss is a subtle but important regularizer. When you feed a Monet painting directly into the Monet generator, the output should be identical to the input. The generator should recognize “this is already in my target domain” and leave it alone. Without this constraint, the generator can shift the color palette of images that already look correct, introducing unwanted tinting across the board.</p><pre>L_id = λ_cyc × λ_id × ( mean|y - G(y)| + mean|x - F(x)| )<br><br>where λ_cyc = 10.0, λ_id = 0.5</pre><p>I weighted identity loss at half the cycle loss weight (λ_cyc × 0.5). This is more aggressive than some implementations that use 0.1, but for Monet style transfer the stronger identity constraint helped preserve color fidelity. When the identity weight was too low, the generator would tint everything with a yellow-green wash regardless of the input.</p><p><strong>Total Generator Loss</strong></p><pre>L_G = L_adv + L_cyc + L_id</pre><p>Three signals, each pulling the generator in a different direction. Adversarial loss pushes toward realism. Cycle loss prevents hallucination. Identity loss anchors the color space. The training dynamics emerge from these competing forces finding equilibrium.</p><h3>Training Details</h3><p>The training ran for 25 epochs at 500 steps per epoch, with a batch size of 4. All four optimizers (one per network) are Adam with a constant learning rate of 2e-4 and beta_1=0.5. The lower momentum compared to the default 0.9 matters. It means the optimizer reacts faster to changing gradients, which is important when two networks are constantly shifting each other’s loss landscape.</p><p>The training step uses a persistent gradient tape so both generators and both discriminators are updated from the same forward pass. This avoids redundant computation and ensures all four networks see exactly the same batch of real and fake images.</p><p>No learning rate decay, no replay buffers, no feature matching. Just the three losses, four Adam optimizers, and a clean data pipeline. Not every problem needs more machinery. Sometimes the leverage is in getting the basics exactly right.</p><h3>Reading the Training Logs (What the Numbers Actually Mean)</h3><p>GAN training logs are notoriously hard to interpret. Unlike a classifier where loss going down means things are improving, GAN losses exist in a dynamic equilibrium. Here’s what to actually watch for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*ynqkkxVY7eo2q5Xf8xDnEw.gif" /><figcaption>Animation 1: Training loss curves</figcaption></figure><p>Generator losses (Gg and Gf) should gradually decrease and stabilize. In this run, they started around 6.0–6.4 in epoch 1, which is high because the generators are producing noise. By epoch 5 they dropped to the 3.9 range as the generators learned coarse structure. The losses continued falling to the 2.3–2.5 range by epoch 25, but the decline slowed. Most of the learning happens in the first 10 epochs. The remaining 15 are refinement.</p><p>Discriminator losses (Dx and Dy) tell a different story. They should hover in a moderate range, not too high, not too low. In this run they stayed remarkably stable around 0.19–0.22 throughout all 25 epochs. This is healthy. It means the discriminator is keeping up with the generator but never running away with it. If the discriminator loss dropped to near-zero while the generator loss stayed high, it would mean the discriminator has won and the generator has stopped learning. That never happened here.</p><p>The occasional spike is normal. Epoch 16 shows a Dy of 0.542 at one step, which means the discriminator briefly struggled with a batch. But it recovered by the next step. These transient spikes are part of adversarial training, not signs of failure.</p><h3>Results</h3><p>This configuration scored 61.33 on the Kaggle <a href="https://www.kaggle.com/competitions/gan-getting-started">“I’m Something of a Painter Myself”</a> competition’s public leaderboard. The score is MiFID (Memorization-informed Fréchet Inception Distance), where lower is better.</p><p>The combination of ResNet generator with nine residual blocks, PatchGAN discriminator, LSGAN adversarial loss, cycle consistency, and identity loss produced results that capture Monet’s impressionist qualities. Soft brushstrokes, muted color palettes, atmospheric light, and the particular way Monet dissolved hard edges into suggestion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*ArRGSr4etO3eKyagnBYIdA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*cac1ebEV-6ieQUqRKImJeA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*Mx38Na6YMLslb9QI6XvATQ.jpeg" /><figcaption>Generated Image output samples</figcaption></figure><p>The model generated 7,000 images from the photo dataset, each one a photograph translated into Monet’s visual vocabulary. Not every output is a masterpiece. Some images fight the translation, particularly those with sharp geometric structures that resist the organic brushwork Monet favored. But the best outputs genuinely evoke the feeling of standing in front of a Monet, which is more than most neural networks can claim.</p><h3>What I’d Try Next</h3><p>No GAN project is ever finished. It’s just abandoned at a point where the outputs are good enough and the debugging has consumed enough weekends. But if I were to push further, there are a few directions worth exploring.</p><p>A multi-scale discriminator would add pressure at two levels of detail. Running a second PatchGAN on a downsampled version of the image forces the generator to get both fine textures and global composition right. The current single-scale PatchGAN only enforces local realism.</p><p>Feature matching loss, where you compare intermediate discriminator representations of real and fake images, would give the generator a richer training signal than the final “real/fake” verdict alone. It’s like checking a student’s working, not just their answer.</p><p>Learning rate decay in the second half of training could help squeeze out extra quality during late epochs. A linear decay from 2e-4 to near-zero would let the model make increasingly fine adjustments without overshooting.</p><p>An image replay buffer that shows the discriminator older fake images alongside current ones would prevent it from forgetting earlier failure modes. Right now the discriminator only sees the current batch of fakes, which means it can oscillate.</p><p>And the elephant in the room: <strong>diffusion models</strong>. CycleGAN is elegant, but it’s fighting with one hand tied behind its back compared to modern diffusion-based style transfer. The question isn’t whether diffusion models produce better results. They do. The question is whether they can do it unpaired, without examples of “this photo maps to this painting.” That’s the problem CycleGAN was built to solve, and it’s still not fully answered.</p><p>For now, though, 61.33 on MiFID with clean fundamentals and no exotic tricks in 4.5 hours isn’t bad. Sometimes the old tools still cut.</p><h4>Code &amp; Resources</h4><p>To make the project easier to explore and reproduce, here are the implementation links:</p><p><strong>- </strong><a href="https://www.kaggle.com/code/rajdhyaneshvar/enhanced-cyclegan-with-resnet?scriptVersionId=288985101"><strong>Kaggle Notebook</strong></a><strong> <br>- </strong><a href="https://github.com/RajDhyaneshvarCJ/Enhanced-CycleGAN-with-RESNET/tree/main"><strong>GitHub Repository</strong></a></p><h3>References</h3><ol><li>Zhu, J.Y., Park, T., Isola, P., &amp; Efros, A.A. (2017). Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks. <a href="https://arxiv.org/abs/1703.10593">arXiv:1703.10593</a></li><li>Mao, X., Li, Q., Xie, H., Lau, R.Y., Wang, Z., &amp; Smolley, S.P. (2017). Least Squares Generative Adversarial Networks. <a href="https://arxiv.org/abs/1611.04076">arXiv:1611.04076</a></li><li>Isola, P., Zhu, J.Y., Zhou, T., &amp; Efros, A.A. (2017). Image-to-Image Translation with Conditional Adversarial Networks. <a href="https://arxiv.org/abs/1611.07004">arXiv:1611.07004</a></li><li>Parmar, G., Park, T., Narasimhan, S., &amp; Zhu, J.Y. (2024). One-Step Image Translation with Text-to-Image Models. <a href="https://arxiv.org/abs/2403.12036">arXiv:2403.12036</a></li><li>Torbunov, D., Huang, Y., Yu, H., Huang, J., Yoo, S., Lin, M., Viren, B., &amp; Ren, Y. (2023). Rethinking CycleGAN: Improving Quality of GANs for Unpaired Image-to-Image Translation. <a href="https://arxiv.org/abs/2303.16280">arXiv:2303.16280</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80961a92c715" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>