<?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 Atul Ranjan on Medium]]></title>
        <description><![CDATA[Stories by Atul Ranjan on Medium]]></description>
        <link>https://medium.com/@atulranjan975?source=rss-f37e22283ec6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*msIcmNphj5WGBd29</url>
            <title>Stories by Atul Ranjan on Medium</title>
            <link>https://medium.com/@atulranjan975?source=rss-f37e22283ec6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:08:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atulranjan975/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[The 9-Test Gauntlet: How I Decide Whether a Trading Strategy Is Real]]></title>
            <link>https://medium.com/@atulranjan975/the-9-test-gauntlet-how-i-decide-whether-a-trading-strategy-is-real-d1c23d2d97a9?source=rss-f37e22283ec6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1c23d2d97a9</guid>
            <category><![CDATA[quantitative-strategies]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Atul Ranjan]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 19:30:19 GMT</pubDate>
            <atom:updated>2026-08-31T19:30:19.771Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I’ve backtested hundreds of trading strategies. I trade a handful. This is the filter in between.</em></p><p>Here is the most expensive lesson in quantitative trading, compressed into one sentence:</p><p><strong>A good backtest is where skepticism starts, not where it ends.</strong></p><p>Almost every impressive equity curve you will ever produce is fake. Not fraudulent, but <em>fake</em>, in the specific technical sense that the profits exist in the simulation and will not exist in your account. In my experience, roughly one candidate strategy in a hundred survives honest scrutiny. The rest die in one of three ways: they were secretly using information from the future (<strong>look-ahead bias</strong>), they were secretly just holding the market (<strong>beta in a costume</strong>), or they were fitted to noise that will never repeat (<strong>overfitting</strong>).</p><p>So I run every strategy through a fixed gauntlet of nine tests, in a fixed order, and I stop believing at the first failure. The order matters: cheap tests that catch common frauds come first, expensive tests that quantify subtle ones come last. The prime directive behind all nine:</p><blockquote><strong><em>Assume every edge is fake until proven otherwise. Your job is to kill your own strategy. Whatever survives your best assassination attempt is the edge.</em></strong></blockquote><p>Let’s go through them.</p><h3>Test 1: The look-ahead audit</h3><p><em>What it catches: strategies that peek at the future.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdV8nJ5v9Y8YF2kQvUjD4A.png" /></figure><p>Look-ahead bias means your simulated decision at time <em>t</em> used information that only became available after <em>t</em>. It is the most common and most devastating bug in backtesting, and the chart above shows why it’s so seductive: the two equity curves are <strong>the same rule</strong>. The blue one is honest. The orange one is allowed to see the bar it’s trading, and it “returns” +372% with a coin-flip signal.</p><p>The formal statement: a trading signal must be <strong>adapted to the filtration</strong>. In plain language, the position you hold over bar <em>t+1</em> may only be a function of information available at the close of bar <em>t</em>:</p><pre>position[t+1] = f( data[1], data[2], ..., data[t] )     # and nothing else</pre><p>In pandas terms, this is why experienced quants are obsessive about .shift(1): every indicator, every rolling window, every regime flag gets lagged by one bar before it touches a trading decision.</p><p>The audit has two parts:</p><p><strong>1. Signal causality.</strong> Walk through the code line by line and ask of every input: <em>at the exact moment this decision fires, was this number knowable?</em> The killers are subtle. My favorite example from my own research: a daily trend signal sampled on the bar’s <em>own calendar date</em> inside an intraday loop. The daily value is computed from that day’s close, which doesn’t exist yet for a bar at 4 a.m. That single bug was worth +2.3 percentage points a year of fake performance, and here is the scary part: <strong>statistical tests cannot catch it.</strong> Shuffling-based controls destroy the peek along with the signal, so the contaminated strategy passes them. Only a line-by-line audit, or re-implementing the strategy in a second codebase and comparing trades, finds it.</p><p><strong>2. Executable fills.</strong> When your backtest says “buy at the breakout level,” ask whether that price was actually attainable. If price gapped through your level overnight, you didn’t get the level. You got the open. The pessimistic fill rules:</p><pre>long entry  = max(breakout_level, bar_open)     # you never fill better than the open<br>stop exit   = min(stop_level, bar_open)         # gaps hurt you, never help you</pre><p><strong>Pass bar:</strong> every input lagged, every fill pessimistic, and, as the gold standard, a second independent implementation produces the same trade list.</p><h3>Test 2: Realistic fills and costs</h3><p><em>What it catches: strategies that are profitable only in a frictionless universe.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7coFD_RRc2qNzmAa3MdVgg.png" /></figure><p>Every trade pays: <strong>spread + commission + slippage + overnight financing</strong>. The net return of one bar is:</p><pre>net_return[t] = position[t] × market_return[t]  −  (cost/2) × |Δposition[t]|  −  swap × |position[t]|</pre><p>The crucial insight is that costs don’t just shrink your edge; they <strong>decide which time horizons are allowed to exist</strong>. If your round-trip cost is 12 basis points and your signal earns 2bp of gross edge per trade, no amount of modeling brilliance saves you; you need a horizon long enough that the gross edge per trade towers over the cost. I once built a machine-learning model that genuinely predicted short-horizon mean reversion (the information was real, the controls were clean), and it was still worthless, because its gross ceiling was +1 to 2bp against a 12bp cost floor. Run the cost arithmetic <em>before</em> the research, and you’ll save yourself weeks.</p><p><strong>Pass bar:</strong> positive expectancy at <em>conservative</em> cost assumptions for your actual venue, not exchange-fee assumptions when you trade CFDs.</p><h3>Test 3: The Monte-Carlo permutation test</h3><p><em>What it catches: results that are luck wearing a lab coat.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hClX0tUN9dmEJvEqPV81g.png" /></figure><p>This is the decisive test, the one that has killed more of my strategies than any other. The question it answers: <strong>could a market with no exploitable structure have produced my result anyway?</strong></p><p>The procedure:</p><ol><li>Take the real price series and shuffle the order of its bars (for OHLC data, permute bar-to-bar <em>changes</em> and rebuild the series). This <strong>destroys temporal structure</strong> such as trends, momentum and mean reversion, while <strong>preserving the return distribution</strong>: same volatility, same fat tails, same drift.</li><li>Run the <em>identical</em> strategy code on the shuffled series. Record its performance.</li><li>Repeat 1,000 times. You now have the <strong>null distribution</strong>: what your strategy earns in worlds where there is nothing to find.</li><li>Compute the p-value:</li></ol><pre>p = ( count(null_results ≥ real_result) + 1 ) / ( N + 1 )</pre><p>The +1s make the estimate conservative: you count yourself as one of the draws. If the real result sits deep in the right tail (I require <strong>p &lt; 0.01</strong>), the strategy is exploiting structure that shuffling destroyed, which is exactly what a real edge is. If the real result sits <em>inside</em> the cloud, your beautiful equity curve is a lottery ticket that already won.</p><p>For strategies with a learned component (ML models, optimized policies), the same idea becomes a <strong>placebo control</strong>: retrain on permuted targets. A model trained on garbage must lose. If it still profits, the environment, usually a bull market, was doing all the work. And one hard-won addendum: if an <em>optimizer</em> built your strategy, rerun the optimization from several random seeds. I once had a policy score a 0.92 Sharpe out-of-sample, confirmed across every year, and two fresh optimizer seeds on identical data produced −0.11 and −0.23. The “edge” was one lucky trajectory through a many-basin fitness landscape. <strong>Fold-consistency cannot save you from optimizer lottery; only re-optimization can.</strong></p><p><strong>Pass bar:</strong> p &lt; 0.01 against 1,000+ permutations; placebo collapses; all optimizer seeds positive.</p><h3>Test 4: Walk-forward, out of sample</h3><p><em>What it catches: models grading their own homework.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BxI7wvASh0PDqFXbkkV2PQ.png" /></figure><p>Any strategy with fitted parameters will look good on the data it was fitted to. That is what fitting <em>means</em>. The only performance that predicts the future is performance on data the strategy has never seen.</p><p>Walk-forward analysis formalizes this. Split the timeline into folds. For each fold: train (or fix parameters) using <strong>only the past</strong>, then trade the next unseen block, then roll forward. Concatenate all the out-of-sample blocks into one equity curve. That curve is your honest estimate. Two refinements that matter:</p><ul><li><strong>Embargo:</strong> leave a gap of a few days between train-end and test-start, so information can’t leak across the boundary through overlapping windows.</li><li><strong>Escrow:</strong> hold back the final one or two years entirely, sealed, and read it <strong>exactly once</strong>, at the very end of the whole research program. Not once per idea. Once, ever, per dataset. I have watched a strategy go +0.58 Sharpe on the validation years and <strong>−0.66 on the sealed escrow</strong>. That single read prevented a live deployment. The moment you peek twice, your escrow has silently become another validation set.</li></ul><p><strong>Pass bar:</strong> every fold positive (or nearly), pooled OOS consistent with in-sample. A large IS→OOS collapse is overfitting announcing itself.</p><h3>Test 5: The regime split</h3><p><em>What it catches: strategies that are secretly a bet on one kind of market.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jyFfTaHGpLG05aprkKghvA.png" /></figure><p>Average performance hides everything interesting. Slice it: by year, by trend-vs-chop (ADX or realized efficiency), by volatility tercile. Two questions:</p><ol><li><strong>Where does the money actually come from?</strong> If 80% of profits come from one regime, you don’t have a strategy. You have a regime bet, and you’d better believe that regime returns.</li><li><strong>Does the hostile regime kill you?</strong> For a crypto strategy, that’s the 2022 bear. For an oil strategy, it’s the quiet years <em>between</em> crises. The most instructive kill of my career: a “weekend risk premium” in crude oil, with Fridays strongly positive, weekend gaps negative, a textbook mechanism and statistical significance. Then the regime exclusion: remove 2020 and 2022 (COVID and the Ukraine invasion) and the edge went from +24bp to <strong>−1.6bp per trade</strong>. The entire premium was two crisis years. That’s not an edge you can harvest; that’s crisis beta you can’t time.</li></ol><p><strong>Pass bar:</strong> positive in (nearly) every year; survives the hostile regime; no single year or handful of trades carrying the total (check the concentration: what fraction of total profit comes from the top 5 trades?).</p><h3>Test 6: Cost stress</h3><p><em>What it catches: strategies that live and die inside your spread assumption.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkmbAPr25MbBpbw3OdWZXA.png" /></figure><p>You estimated your costs in Test 2. Now assume you were wrong, because live, you will be. Re-run everything at 1.5×, 2×, and 3× the assumed cost. The mathematics of why this is diagnostic:</p><pre>net_edge(m) = gross_edge − m × cost_per_trade × turnover</pre><p>Net performance is <em>linear</em> in the cost multiplier, with slope proportional to turnover. A low-turnover strategy with a fat gross edge degrades gently, as in the blue line. A high-turnover strategy skimming a thin edge collapses through zero between ×1 and ×2, as in the orange line. The slope of this line is your turnover telling on you.</p><p><strong>Pass bar:</strong> still solidly profitable at ×2; I like to see at least half the baseline return retained.</p><h3>Test 7: Is it just beta?</h3><p><em>What it catches: the market’s returns, re-badged as your skill.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i6iZ48s788SDKnf0gPGuxw.png" /></figure><p>This is the most humbling test, because it catches strategies that pass everything else. Regress your strategy’s daily returns on the market’s:</p><pre>strategy_return[t] = α + β × market_return[t] + ε[t]</pre><ul><li><strong>β</strong> is how much of your performance is just market exposure. A “crypto strategy” with β = 0.95 to BTC is a leveraged BTC position with extra steps. You could have bought and held.</li><li><strong>α</strong> is what remains after removing the market, the part that is actually yours. Demand α &gt; 0 with a real t-statistic (α divided by its standard error; you want it above 2 or 3).</li></ul><p>Three refinements that catch what the regression misses:</p><ol><li><strong>The two-sided test.</strong> Check the long trades and short trades <em>separately</em>. If longs make money everywhere and shorts lose money everywhere, your “signal” is a long-only market bet in disguise. This single check killed time-series momentum on metals for me, twice.</li><li><strong>The shuffle giveaway.</strong> In machine-learning strategies, if an agent trained on <em>permuted</em> rewards performs almost as well as the real one, the environment (a bull market) is the whole edge. I’ve seen a “1.99 Sharpe” reinforcement-learning agent whose garbage-trained twin scored 1.80.</li><li><strong>The risk-matched control</strong> for overlays and filters: any regime filter must beat <em>simply levering the unfiltered strategy to the same risk</em>. Most “improvements” are implicit leverage.</li></ol><p><strong>Pass bar:</strong> |β| small (I use &lt; 0.25), α positive and significant, both legs non-negative.</p><h3>Test 8: Parameter robustness</h3><p><em>What it catches: the one lucky cell in the grid.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IG8hQ3s-0B2ZlkyV2SBxpA.png" /></figure><p>Every parameter you chose (lookback 20, stop 2×ATR) was chosen somehow, and the honest question is: <strong>do the neighbors work too?</strong></p><p>Sweep every parameter across a wide grid and look at the <em>shape</em> of the performance surface. A real market effect is not precise. Trend-following works at lookback 15 and 25 if it works at 20, so a real effect shows up as a <strong>smooth plateau</strong> (left panel). Overfitting shows up as a <strong>spike</strong>: one glowing cell in a dead grid (right panel). If you must quote a number, quote the <em>neighborhood median</em>, not the peak. And if the neighborhood median is unimpressive, the peak was noise.</p><p>Two companion checks at this stage:</p><ul><li><strong>Count your experiments.</strong> If you tested 200 configurations across your research program, the best one is partly a winner of a 200-ticket lottery. The <strong>Deflated Sharpe Ratio</strong> (Bailey &amp; López de Prado) formalizes the correction. It asks whether your Sharpe beats the <em>expected maximum</em> Sharpe of N random tries:</li></ul><pre>SR₀ ≈ sqrt(1/T) × [ (1−γ)·Φ⁻¹(1 − 1/N) + γ·Φ⁻¹(1 − 1/(N·e)) ]      γ ≈ 0.5772<br>DSR = Φ( (SR − SR₀) · sqrt(T−1) / sqrt(1 − skew·SR + (kurt−1)/4 · SR²) )</pre><p>Keep a <em>ledger</em> of everything you ever tried. The N in that formula is your career, not your afternoon.</p><ul><li><strong>Never re-optimize to recent data.</strong> The optimal parameters of the last two years are the noise of the last two years.</li></ul><p><strong>Pass bar:</strong> chosen parameters sit on a plateau; DSR &gt; 0.95 at your honest, career-length N.</p><h3>Test 9: Honest forward projection</h3><p><em>What it catches: your own optimism.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SaQsJ4i_T3SmshTg9seZfg.png" /></figure><p>You’ve passed eight tests. The last one is arithmetic humility: <strong>the backtest is the ceiling, not the forecast.</strong> Two systematic haircuts before any capital moves:</p><ol><li><strong>Edge decay (× 0.85).</strong> Markets adapt. Even permutation-validated edges erode as the anomaly gets arbitraged, the regime shifts, or your fills degrade. If the edge <em>isn’t</em> permutation-validated, the haircut should be much harsher, or infinite.</li><li><strong>Drawdown sizing (× 0.75).</strong> Your live maximum drawdown will exceed your backtest maximum drawdown. The backtest saw one path; the future will draw another, and bootstrap simulations of your own daily P&amp;L will show you 95th-percentile drawdowns well past the historical one. Size positions for <em>that</em> drawdown, which means running smaller.</li></ol><pre>planning_return ≈ backtest_return × 0.85 × 0.75      ≈ 64% of the backtest</pre><p>Then pre-register your live expectations <em>now</em>, while you’re objective: expected win rate, longest losing streak (for a strategy with win rate w, the expected longest streak in n trades is roughly ln(n)/ln(1/(1−w)); for a 40%-win trend system over 200 trades, that&#39;s 10+ consecutive losses, <em>while healthy</em>), and the drawdown level at which you&#39;ll cut size, decided in advance, so a bad month triggers a lookup instead of a panic. When my own live book had its worst month, replaying the backtest distribution showed the loss was a 1-in-90 window, inside the plan. We changed nothing. That is what Test 9 buys you: the ability to distinguish <em>a drawdown</em> from <em>a death</em>, before you&#39;re inside one.</p><p><strong>Pass bar:</strong> you would still deploy at the haircut number. If the strategy is only attractive at the backtest number, it isn’t attractive.</p><h3>The gauntlet as a whole</h3><p>Nine tests, in order, stopping at the first failure:</p><p># Test The question Kills 1 Look-ahead audit Could you actually have known this? Future-peeking 2 Fills &amp; costs Could you actually have traded this? Friction-blind edges 3 Permutation test Could luck have produced this? Statistical mirages 4 Walk-forward + escrow Does it work on unseen data? Curve-fitting 5 Regime split Where does it earn, and does the bad year kill it? Regime bets 6 Cost stress What if costs are double? Thin, high-turnover edges 7 Beta decomposition Is it just the market? Beta in costume 8 Parameter plateau Do the neighbors work? The lucky cell 9 Forward haircut Would you deploy at 64% of this? Your own optimism</p><p>The output of this process is mostly the word <strong>no</strong>. That is the point. Run a hundred ideas through it and expect one or two survivors. But those survivors are strategies you can hold through a ten-trade losing streak without flinching, because you know exactly how hard they were to kill.</p><p>The market pays you for one thing: being right when it was <em>hard</em> to be right. The gauntlet is how you find out, before your money does.</p><p><em>All charts in this article are synthetic illustrations, generated to show each failure mode clearly. The tests, the math, and the war stories are real.</em></p><p>Here is something I built to validate my edges with these tests built in</p><p><a href="https://edgekit.pro/">edgekit - prove the edge</a></p><p>Follow me on LinkedIn</p><p><a href="https://www.linkedin.com/in/atul-ranjan-gott-data/">Atul Ranjan - Gott Data | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1c23d2d97a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Queues: The Most Powerful Data Structure for scalable systems— System Design Part 1]]></title>
            <link>https://medium.com/@atulranjan975/queues-the-most-powerful-data-structure-for-scalable-systems-system-design-part-1-d586dfb67830?source=rss-f37e22283ec6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d586dfb67830</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Atul Ranjan]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 22:47:09 GMT</pubDate>
            <atom:updated>2025-10-10T22:47:09.986Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A casual, but deep dive into building resilient, concurrent, and state-driven automation pipelines and worker-based architecture.</blockquote><h4>What Are Automation Pipelines — and Why Concurrency Takes Them to the Next Level</h4><p>Automation is everywhere. From running build scripts to processing images, sending emails, or rendering videos — almost every modern system runs some form of automated pipeline behind the scenes.</p><p>But here’s the catch: most pipelines still run in a pretty <em>old-school</em> way — one job at a time. Job A finishes, then Job B starts. It’s simple, predictable, and easy to debug. But once the workload starts growing, this design starts showing cracks. Imagine having hundreds of jobs waiting in line, all depending on one slow task to finish before the next even begins. That’s when automation stops feeling like automation — it feels like waiting for a printer to unjam.</p><p>This sequential approach limits your throughput, burns compute time, and makes scaling painful. A single stuck job can block the whole pipeline. That’s where concurrency steps in. When you let multiple jobs run <strong>in parallel</strong>, your automation suddenly becomes faster, more efficient, and more resilient. Instead of waiting in line, every task gets its own lane.</p><p>But running things concurrently isn’t as easy as “just run them all at once.” You need a system that can handle job distribution, retries, and state management without everything collapsing into chaos.</p><p>That’s where queues come in — the secret ingredient to scaling automation without losing control.</p><h4>Solution to Concurrency and Automation: Store It in a Queue</h4><p>Queues are one of the most powerful yet underrated data structures in system design. Simple in concept — a line of tasks waiting their turn — but incredibly effective when applied right. A queue gives structure to concurrency. Instead of jobs competing for attention or running chaotically, they flow in and out of the system in an organized, predictable way. Workers can pick up tasks, process them independently, and report back when done. That’s how you turn scattered automation into a controlled, scalable pipeline.</p><p>But here’s where it gets tricky. If your queue lives locally — maybe an in-memory structure or a lightweight library — it’s only as reliable as your server. The moment that server crashes, every queued job disappears with it. And in production, that’s not just inconvenient; it’s dangerous. Lost jobs mean lost progress, broken workflows, and angry users.</p><p>That’s why persistent, hosted queues exist — to make concurrency <em>reliable</em>. Services like <strong>Amazon SQS</strong> handle the heavy lifting for you: message durability, retries, scaling, and even distributed delivery. You push a job to the queue, and no matter what happens to your local machine, that job lives safely in the cloud until a worker picks it up. It’s like having a dependable middleman between your automation logic and your infrastructure — one that never sleeps or crashes.</p><p>By offloading your job distribution to a hosted queue, you decouple your automation logic from the server’s uptime. Your workers can scale up, shut down, or even crash — and the queue will quietly keep the system in order. That’s the beauty of using queues for automation: they don’t just make concurrency possible, they make it dependable.</p><h4>A Simple Worker-Queue Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74aP0x5iLr97hUf36pnVxA.png" /></figure><p>Clients push jobs into the queue, and workers are <strong>subscribed to the queue</strong>, picking up tasks as they arrive. Each worker processes its job independently and updates the job’s status in a database — this could be a fast in-memory store like <strong>Redis</strong>, or a persistent relational database like <strong>PostgreSQL</strong>. A cache can sit in front of the database to accelerate reads for frequently accessed job data.</p><p>This architecture decouples the producer (client) from the consumers (workers), ensures reliable job handling, and makes scaling straightforward: add more workers, and the system automatically handles higher loads without changing the client logic.</p><p><strong>How are workers subscribed to the queue?<br></strong>Once you have a queue in place, the next question is: <strong>how do workers know when there’s a job to process?</strong> There are two common approaches:</p><ol><li><strong>Event-driven triggers:</strong> The queue can notify workers as soon as a new job arrives. This is highly efficient — workers sleep until a task appears, reducing idle CPU usage. Many hosted queues, like <strong>AWS SQS with Lambda</strong> or <strong>RabbitMQ</strong>, support this pattern out-of-the-box.</li><li><strong>Polling the queue:</strong> A simpler approach is for workers to periodically check the queue for new jobs. While this may introduce slight latency and more network calls, it’s straightforward to implement and works well for many systems. Workers repeatedly “ask” the queue if any jobs are ready, pick them up, and process them.</li></ol><p>Both approaches have trade-offs. Event triggers are more efficient and scalable, while polling is easier to implement and debug, especially when starting small.</p><h4>A very simple implementation and design pattern</h4><blockquote>This is one of the very few times I find <strong>inheritance and object-oriented programming useful</strong>, although admittedly this could also be achieved with composition.</blockquote><p>For this example, I’m using <strong>TypeScript in the context of an Express server</strong>, but the pattern can be replicated in <strong>any language</strong>. The idea is simple: define a <strong>base worker</strong> that handles all the queue and state logic, and let specific workers just implement the actual job processing.</p><pre>import {<br>  receiveFromQueue,<br>  deleteFromQueue,<br>  pushToQueue,<br>  JobMessage,<br>  JobState,<br>} from &quot;../utils/queue&quot;;<br>import { updateJobProgress } from &quot;../utils/redis&quot;;<br><br>export abstract class BaseWorker {<br>  protected workerName: string; // Name of the worker, useful for logging<br>  protected targetState: JobState; // The specific job state this worker handles<br>  protected isRunning: boolean = false; // Flag to control the worker loop<br><br>  constructor(workerName: string, targetState: JobState) {<br>    this.workerName = workerName;<br>    this.targetState = targetState;<br>  }<br><br>  // Each worker must implement this method with custom job logic<br>  protected abstract processJob(message: JobMessage): Promise&lt;{<br>    success: boolean;<br>    nextState?: JobState; // Optionally push to next state after completion<br>    s3Location?: string; // Optional result location (e.g., file URL)<br>    error?: string; // Optional error message if processing fails<br>    metadata?: any; // Optional additional metadata<br>  }&gt;;<br><br>  // Start the worker loop<br>  public async start(): Promise&lt;void&gt; {<br>    this.isRunning = true;<br>    console.log(`🚀 Starting ${this.workerName} worker (listening for state: ${this.targetState})`);<br><br>    while (this.isRunning) {<br>      try {<br>        // Poll the queue for messages (1 at a time here)<br>        const messages = await receiveFromQueue(1);<br><br>        if (messages.length === 0) continue; // No jobs, continue polling<br><br>        for (const queueMessage of messages) {<br>          // Skip messages that are not meant for this worker<br>          if (queueMessage.body.state !== this.targetState) {<br>            await deleteFromQueue(queueMessage.receiptHandle); // Remove from queue<br>            await pushToQueue(queueMessage.body); // Re-add for the correct worker<br>            continue;<br>          }<br><br>          // Update job status to &quot;processing&quot; in Redis/Postgres<br>          await updateJobProgress(queueMessage.body.jobId, this.targetState, &quot;processing&quot;);<br><br>          // Run the custom job logic<br>          const result = await this.processJob(queueMessage.body);<br><br>          if (result.success) {<br>            // Job completed successfully<br>            await updateJobProgress(queueMessage.body.jobId, this.targetState, &quot;completed&quot;, result.s3Location);<br><br>            // Push to next state if specified<br>            if (result.nextState) {<br>              await pushToQueue({<br>                ...queueMessage.body,<br>                state: result.nextState,<br>                metadata: result.metadata || queueMessage.body.metadata,<br>              });<br>            }<br>          } else {<br>            // Job failed<br>            await updateJobProgress(queueMessage.body.jobId, this.targetState, &quot;failed&quot;, undefined, result.error);<br>          }<br><br>          // Remove the job from the queue to prevent reprocessing<br>          await deleteFromQueue(queueMessage.receiptHandle);<br>        }<br><br>        // Small delay between polling cycles (only if we processed messages)<br>        if (messages.length &gt; 0) await this.sleep(1000);<br>      } catch (error) {<br>        // Log errors and back off before retrying<br>        console.error(`❌ ${this.workerName} error:`, error);<br>        await this.sleep(5000);<br>      }<br>    }<br>  }<br><br>  // Stop the worker loop<br>  public stop(): void {<br>    this.isRunning = false;<br>    console.log(`🛑 Stopping ${this.workerName} worker`);<br>  }<br><br>  // Utility function to pause execution for a given time<br>  protected sleep(ms: number): Promise&lt;void&gt; {<br>    return new Promise((resolve) =&gt; setTimeout(resolve, ms));<br>  }<br>}</pre><p><strong>How this works:</strong></p><ul><li>BaseWorker handles the <strong>queue polling</strong>, <strong>job status updates</strong>, and <strong>retry/deletion logic</strong>.</li><li>Workers use <strong>Redis (or another database)</strong> via updateJobProgress to store the current state (processing, completed, failed) so that job progress is always visible and persistent.</li><li>The processJob method is <strong>abstract</strong>—each child worker just needs to implement the actual job logic. Everything else is already handled.</li></ul><p>This approach makes it <strong>easy to add new workers</strong> without rewriting the queue-handling logic:</p><pre>export class SomeWorker extends BaseWorker {<br>  constructor() {<br>    super(&quot;SomeWorker&quot;, &quot;queued&quot;);<br>  }<br><br>  protected async processJob(message: JobMessage) {<br>    // Your custom processing logic here<br>    return { success: true, nextState: &quot;processed&quot; };<br>  }<br>}</pre><h4>Managing Multiple Workers</h4><p>To start multiple workers together, you can use a <strong>worker manager</strong>. Here’s a general approach:</p><pre>import { NanoWorker } from &quot;./nano-worker&quot;;<br>import { VeoWorker } from &quot;./veo-worker&quot;;<br><br>export class WorkerManager {<br>  private workers: BaseWorker[];<br><br>  constructor() {<br>    this.workers = [<br>      new SomeWorker(),<br>      new SomeWorker2(),<br>      // Add other workers here<br>    ];<br>  }<br><br>  public async startAll(): Promise&lt;void&gt; {<br>    console.log(&quot;🚀 Starting all workers...&quot;);<br>    const workerPromises = this.workers.map((worker) =&gt; worker.start());<br><br>    process.on(&quot;SIGINT&quot;, () =&gt; this.stopAll());<br>    process.on(&quot;SIGTERM&quot;, () =&gt; this.stopAll());<br><br>    await Promise.all(workerPromises);<br>  }<br><br>  public stopAll(): void {<br>    console.log(&quot;🛑 Stopping all workers...&quot;);<br>    this.workers.forEach((worker) =&gt; worker.stop());<br>  }<br>}<br><br>// Make it executable<br>if (require.main === module) {<br>  const manager = new WorkerManager();<br>  manager.startAll().catch((err) =&gt; {<br>    console.error(&quot;❌ Worker manager failed:&quot;, err);<br>    process.exit(1);<br>  });<br>}</pre><p><strong>Why this pattern works well:</strong></p><ul><li><strong>Reusability:</strong> BaseWorker handles everything boilerplate.</li><li><strong>Scalability:</strong> Add new workers without touching existing code.</li><li><strong>Resilience:</strong> Jobs are always tracked in Redis/Postgres; failed jobs don’t get lost.</li><li><strong>Extensibility:</strong> Easy to swap out polling for event-driven triggers later.</li></ul><h4>Wrapping Up</h4><p>Queues and worker-based architectures might seem simple at first glance, but as we’ve seen, they are <strong>the backbone of scalable, resilient automation systems</strong>. By decoupling job producers from workers, handling state reliably in Redis or Postgres, and allowing concurrency to flow naturally, you can turn even complex pipelines into systems that are <strong>predictable, debuggable, and robust</strong>.</p><p>Whether you’re building a video rendering pipeline, an email delivery system, or any other automated workflow, starting with a <strong>queue + worker design pattern</strong> will save you headaches, lost jobs, and server downtime down the line.</p><blockquote>Automation isn’t just about doing things faster — it’s about doing them <strong>reliably</strong> at scale. And queues are what make that possible.</blockquote><h4>Connect with me</h4><p>Follow me on medium:</p><p><a href="https://medium.com/@atulranjan975">Atul Ranjan - Medium</a></p><p>Connect with me on LinkedIn:</p><p><a href="https://www.linkedin.com/in/atul-ranjan-gott-data/">https://www.linkedin.com/in/atul-ranjan-gott-data/</a></p><p>See where I work:</p><p><a href="https://gottdata.com/">Gott Data</a></p><p>Visit my website:</p><p><a href="https://atulranjan.com/">Atul Ranjan</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d586dfb67830" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Simplest way to build reservation calendars on React with Gott Calendar UI]]></title>
            <link>https://medium.com/@atulranjan975/the-simplest-way-to-build-reservation-calendars-on-react-with-gott-calendar-ui-2cce6dceee05?source=rss-f37e22283ec6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cce6dceee05</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Atul Ranjan]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 14:41:14 GMT</pubDate>
            <atom:updated>2024-09-20T14:41:14.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTa0x5UcorFdx6dmkT2-jA.png" /></figure><h3>A Short Introduction and the Motivation</h3><p>Building reservation calendars can especially be difficult in React, because of the nature of calendars itself. Calendars are one of those trivial things you don’t want to spend too much time on, so you start searching the web for packages with good calendars, and to your surprise, you find none.</p><p>When you sit down and start writing one yourself, you realize that building calendars is not as simple as they seem, especially one with all the logic required for your reservation system, and then you end up spending a lot of time on the trivial thing you wanted to avoid in the first place.</p><p>What I just described was exactly what happened to me, and led me to develop gott-calendar-ui. A complete UI component for all the kinds of calendars you are ever going to need in your project so you don’t have to waste time on it.</p><p>To get started, install gott-calendar-ui with npm or yarn.</p><pre>npm install gott-calendar-ui</pre><pre>yarn add gott-calendar-ui</pre><h3>A Simple Reservation Calendar</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVgGh25HqHjNkPU5A7Kxwg.png" /></figure><p>You can build the reservation calendar with the SimpleReservationCalendar component. Here is an example of it</p><p>With this component you can:<br>1. Pass Reservation dates and timings that the component can display<br>2. Pass additional field names for any user who wishes to make a reservation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CAiQCKFtSCIHXET8Vns5ug.png" /></figure><p>First, let&#39;s set up some sample data for us to use in SimpleReservationCalendar</p><pre>export const sampleReservationDates: ReservationDate[] = [<br>  {<br>    date: new Date(2024, 8, 20), // September 20, 2024<br>    numSlots: 3,<br>    timings: [&quot;09:00 AM&quot;, &quot;02:00 PM&quot;, &quot;06:00 PM&quot;],<br>  },<br>  {<br>    date: new Date(2024, 8, 21), // September 21, 2024<br>    numSlots: 2,<br>    timings: [&quot;10:00 AM&quot;, &quot;03:00 PM&quot;],<br>  },<br>  {<br>    date: new Date(2024, 8, 23), // September 23, 2024<br>    numSlots: 4,<br>    timings: [&quot;08:00 AM&quot;, &quot;11:00 AM&quot;, &quot;02:00 PM&quot;, &quot;05:00 PM&quot;],<br>  },<br>];<br><br><br>export const sampleFormFields: FormData[] = [<br>  {<br>    name: &quot;fullName&quot;,<br>    labelName: &quot;Full name&quot;,<br>    placeholder: &quot;Enter your full name&quot;,<br>  },<br>  {<br>    name: &quot;email&quot;,<br>    labelName: &quot;Email Address&quot;,<br>    placeholder: &quot;Enter your email address&quot;,<br>  },<br>  {<br>    name: &quot;organization&quot;,<br>    labelName: &quot;Organization&quot;,<br>    placeholder: &quot;Enter your organization name&quot;,<br>  },<br>];</pre><p>Implementing the component itself</p><pre>import React from &#39;react&#39;;<br>import { SimpleReservationCalendar } from &#39;gott-calendar-ui&#39;;<br>import { sampleReservationDates, sampleFormFields } from &#39;./sampleData&#39;;<br><br>function App() {<br>  const validateDate = (date) =&gt; {<br>    // Custom date validation logic<br>    const today = new Date();<br>    return date &gt;= today &amp;&amp; date &lt;= new Date(today.getFullYear(), today.getMonth() + 3, today.getDate());<br>  };<br><br>  const handleDateSelect = (date, timing) =&gt; {<br>    console.log(&#39;Reservation selected for:&#39;, date, &#39;at&#39;, timing);<br>  };<br><br>  const handleError = (errorMessage) =&gt; {<br>    // Display error in your preferred UI component<br>    alert(errorMessage);<br>  };<br><br>  const handleFormSubmit = (formData) =&gt; {<br>    console.log(&#39;Form submitted with data:&#39;, formData);<br>    // Process the form data (e.g., send to backend)<br>  };<br><br>  const customProceed = () =&gt; {<br>    console.log(&#39;Custom proceed action triggered&#39;);<br>    // Implement your custom logic here<br>  };<br><br>  return (<br>    &lt;SimpleReservationCalendar<br>      validateDateFunction={validateDate}<br>      onDateSelect={handleDateSelect}<br>      handleError={handleError}<br>      errorMessage=&quot;Selected date is not available or out of range.&quot;<br>      darkMode={false}<br>      reservationDates={sampleReservationDates}<br>      formFillData={sampleFormFields}<br>      onFormFillAction={handleFormSubmit}<br>      customProceedFunction={customProceed}<br>    /&gt;<br>  );<br>}<br><br>export default App;</pre><p>For Reference, these are the interfaces used by the component:</p><pre>export interface ReservationDate {<br>  date: Date;<br>  numSlots: number;<br>  timings?: string[];<br>}<br><br>export interface FormData {<br>  name: string;<br>  labelName: string;<br>  placeholder: string;<br>}<br><br>interface SimpleReservationCalendarProps {<br>  validateDateFunction: (date: Date) =&gt; boolean;<br>  errorMessage: string;<br>  handleError: (msg: string) =&gt; void;<br>  darkMode?: boolean;<br>  onDateSelect: (date: Date, timing?: string) =&gt; void;<br>  reservationDates?: ReservationDate[];<br><br>  // Function to execute when user has decided to<br>  // make their custom function to proceed<br>  customProceedFunction?: () =&gt; void;<br>  // If no custom function is to be called, take in the<br>  // form data from the user to display the form<br>  formFillData?: FormData[];<br>  // Function after the form is filled and needs to be executes<br>  // The object should be of the format { formName: value }<br>  onFormFillAction?: (formData: { [key: string]: string }) =&gt; {};<br>}</pre><p>You can leave out the timings key in ReservationDate, when you do so, the timings section of the calendar won’t appear. Similarly, if you don’t want the user to fill a form, or implement a function on your own, you can implement the customProceedFunction, in which case you can implement your own logic after the user has picked out the date and time.</p><p>Implement the onFormFillAction function for actions you want to be accomplished upon submission of the reservation request.</p><p>In real scenarios, you would maybe get reservations from the database, and then pass on the data to this component.</p><h3>A Simple Date Range Picker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByxEhEIPy3CrGIIvy-9Ejw.png" /></figure><p>The SimpleRangePicker component can be used when date ranges are to be picked. The implementation is quite straightforward:</p><pre>import SimpleRangePicker from &quot;./SimpleRangePicker&quot;;<br><br>const handleRangeSelection = (startDate, endDate) =&gt; {<br>  console.log(`Selected range: ${startDate} to ${endDate}`);<br>};<br><br>const handleError = (msg) =&gt; {<br>  console.error(msg);<br>};<br><br>const App = () =&gt; (<br>  &lt;SimpleRangePicker<br>    validateDateFunction={(date) =&gt; date &gt;= new Date()}<br>    errorMessage=&quot;Selected date is in the past.&quot;<br>    handleError={handleError}<br>    validateRange={(startDate, endDate) =&gt; {<br>      return true;<br>    }}<br>    rangeSelected={handleRangeSelection}<br>    handleRangeInvalidError={(msg) =&gt; alert(msg)}<br>    rangeInvalidErrorMessage=&quot;The selected range is too long.&quot;<br>    darkMode={false}<br>  /&gt;<br>);</pre><p>Implement the validateDateFunction and validateRange function to validate the selected date and selected date range respectively. Handle additional functionality with the rangeSelected function.</p><h3>Finally, a Simple Calendar</h3><p>The Simple Calendar component is all a simple calendar should be for React. It renders a calendar from which dates can be picked. Its implementation too, is quite straightforward.</p><pre>const handleDateError = (msg: string) =&gt; {<br>  console.error(msg);<br>};<br><br>const handleDateSelect = (date: Date) =&gt; {<br>  console.log(&quot;Selected date:&quot;, date);<br>};<br><br>const App = () =&gt; (<br>  &lt;SimpleCalendar<br>    validateDateFunction={(date) =&gt; date &gt;= new Date()}<br>    errorMessage=&quot;Selected date is in the past.&quot;<br>    handleError={handleDateError}<br>    handleDateSelect={handleDateSelect}<br>    darkMode={true}<br>  /&gt;<br>);</pre><h3>Ending Notes</h3><p>Gott Calendar UI is evolving to be a complete UI library for calendars for reservation systems, contributions are always welcome! The next step to this library is to build a functional website for documentation since one README is getting quite cluttered. Stay tuned for more updates!</p><p>For contributions:<br><a href="https://github.com/Atul-Ranjan12/calendar-ui">https://github.com/Atul-Ranjan12/calendar-ui</a></p><p>If you like my work, or want to learn more, visit:<br><a href="https://gottdata.com/blogs">gottdata.com/blogs</a></p><p>Finally, drop me a line on:<br><a href="https://www.linkedin.com/in/atul-ranjan-gott-data/">https://www.linkedin.com/in/atul-ranjan-gott-data/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cce6dceee05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Data to Intelligence: Harness Data in your organization]]></title>
            <link>https://medium.com/@atulranjan975/from-data-to-intelligence-harness-data-in-your-organization-44691476fef9?source=rss-f37e22283ec6------2</link>
            <guid isPermaLink="false">https://medium.com/p/44691476fef9</guid>
            <category><![CDATA[data-driven-decisions]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-driven-marketing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Atul Ranjan]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 17:28:15 GMT</pubDate>
            <atom:updated>2024-08-04T17:28:15.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CKbzcFCek1Ud4t8k.png" /></figure><h3>Introduction</h3><p>In today’s digital age, data is often referred to as the “new oil.” Organizations across the globe are increasingly recognizing the value of data as a critical asset that can drive innovation, efficiency, and competitive advantage. According to a recent study, companies that leverage data-driven insights are 23 times more likely to acquire customers, six times as likely to retain them, and 19 times as likely to be profitable. This blog aims to guide you through the transformative journey from raw data to actionable intelligence, highlighting key stages and best practices to harness the full potential of data within your organization.</p><p>Data is ubiquitous in any organization, flowing in from various sources such as customer interactions, sales transactions, social media, and operational processes. However, raw data in its unprocessed form is of little to no use; it is merely a collection of numbers and facts that lacks context and meaning. To transform this raw data into valuable insights, raw data has to go through several transformative phases. In this blog, we also discover these phases.</p><p>A little bit about myself before we start, I am Atul Ranjan, a software engineer at Gott Data where I work with SMEs to help them elevate their business with data and software solutions. Learn more about us at:</p><p><a href="https://gottdata.com/">Gott Data</a></p><h3>Understanding Raw Data</h3><p>Raw data, also commonly known as primary data is the unprocessed information collected from various sources. Each functional organization collects large amounts of raw data from various sources, and data in this form, while being able to provide some intuition into operations, can skip many things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LXCAVcz1WkpFVevF.jpg" /></figure><p>Raw data comes in different forms:</p><ol><li><strong>Unstructured Data: </strong>Unorganized data that doesn’t fit into traditional databases, such as emails, videos, social media posts, and sensor data. Most data in this world is unstructured, and while being difficult to analyze, unstructured data can provide tremendous insights into an organization, that one would usually miss.</li><li><strong>Structured Data: </strong>Structured data is data with structure, this type of data fits in traditional databases, can be recorded in sheets, physical or digital, and can be worked with easily. Structured data while not being in volumes as much as unstructured data, has much more capabilities for analysis. Hence, a company needs to build strong data foundations.</li><li><strong>Semistructured data: </strong>It can be argued that this falls under the category of structured data, but it doesn’t fit entirely in it. Such data has some structure, but not enough to be represented in tables effortlessly. This includes JSON files and XML files.</li></ol><p>Raw data has to be collected and integrated through many sources. These sources include:</p><ol><li><strong>Internal Databases: </strong>The organization’s database is one of the main sources of structured data</li><li><strong>Web Logs: </strong>Logs from websites can be analyzed.</li><li><strong>Analytics Platforms: </strong>Data can be collected from analytics platforms, such as Google Analytics and others to analyze the customer base</li><li><strong>Transaction Logs: </strong>The organization’s transactions play an important role in understanding the organization’s users, and the users ultimately make the organization</li><li><strong>External Devices: </strong>IOT devices can be excellent data collectors depending on your use case.</li><li><strong>Physical Methods to Store Data: </strong>Even at present in this digital world, data might exist in physical records in many places, while difficult to process, these physical forms of data can be eliminated by transforming operations digitally, and building strong data foundations along the way.</li></ol><h3>Data Collection and Integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kIps30dA0gmxrk7a.png" /></figure><p><strong>Data collection</strong> refers to collecting new data from users in various ways as per one’s preference. <strong>Data integration </strong>refers to integrating various existing sources of data in one place, mostly called as the <strong>Data Warehouse.</strong></p><p>Traditional data collection methods include storing data as records. As with the transition of the world into the digital era, excel sheets became the most common way of collecting structured and semi-structured data by organizations. While proving to be sufficient, it is no longer enough for an organization to survive in this rapidly evolving world that is backed by data. I can argue the challenges and limitations of storing data in Excel sheets.</p><p>Storing data in Excel sheets can present several challenges and limitations that can significantly impact efficiency, accuracy, and scalability. Here are some key issues that highlight why custom data collection software is often a far superior alternative:</p><ol><li><strong>Scalability: </strong>Excel struggles with large datasets. As the volume of data increases, performance can degrade, leading to slow loading times and potential crashes. Custom software can handle vast amounts of data more effectively, designed specifically to scale with organizational needs</li><li><strong>Data Integrity and Accuracy: </strong>Excel is prone to human error, whether through accidental deletions, incorrect formulas, or inconsistent data entry. These mistakes can lead to unreliable analyses and conclusions. Custom data collection software can implement validation rules and automated checks to ensure data integrity and accuracy.</li><li><strong>Version Control: </strong>Excel sheets can get messy and unorganized, and hard to keep track of.</li></ol><p>Data integration is the process of combining data from different sources to provide a unified view and facilitate analysis, reporting, and decision-making. This process is essential for organizations that deal with diverse data sets from various systems, applications, and formats, enabling them to derive meaningful insights and foster informed strategies.</p><p>The data integration process typically involves several key steps:</p><ol><li><strong>Data Extraction: </strong>This is the initial phase where data is collected from various sources. These sources can include:</li><li><strong>Databases: </strong>Relational databases like MySQL, Oracle, and PostgreSQL, as well as NoSQL databases like MongoDB and Cassandra.</li><li><strong>Flat Files: </strong>CSV, Excel, and XML files, which often contain structured data.</li><li><strong>Cloud Storage: </strong>Data residing in cloud platforms such as AWS, Azure, or Google Cloud can also be accessed for integration</li><li><strong>Data Transformation: </strong>Once extracted, the data often requires cleansing and formatting to ensure consistency and compatibility. This can involve removing duplicates, converting data types, and applying business rules to align the data with organizational standards.</li><li><strong>Data Loading: </strong>After transformation, the cleaned data is loaded into a target system, such as a data warehouse or a data lake, where it can be stored and accessed for further analysis</li><li><strong>Data Monitoring and Maintenance: </strong>Continuous monitoring is essential to ensure the integrity and accuracy of the integrated data. This includes regular updates and adjustments to the integration processes as new data sources are added or existing ones change.</li></ol><p>After integration, data is effectively stored in warehouses, ready for analysis tasks.</p><h3>Data Storage and Management</h3><p>Once data is collected, it needs to be stored in a way that makes it accessible and secure. At the same time, the methods of storing data should be as such that it makes further analysis of it easy. While storing data, it is essential to establish production and analysis pipelines, which is tested for new incoming data, as well as data that that is flowing out. During this process, it is important to maintain the integrity of the data.</p><p>Data can be stored by organizations in different sources, collectively can be called a warehouse, or a data lake. Here, it consists of the organizations all present structured and unstructured data stored, and ready to be used for production and analysis pipelines.</p><p>Effective data management ensures that data remains accurate, accessible, and secure throughout its lifecycle, it includes:</p><ul><li><strong>Data Governance:</strong> Establishing policies and procedures for data quality, privacy, and compliance.</li><li><strong>Data Security:</strong> Implementing measures to protect data from unauthorized access and breaches, including encryption and access controls.</li><li><strong>Data Compliance:</strong> Adhering to legal and regulatory requirements, such as GDPR and CCPA.</li></ul><h3>Data Processing and Transformation</h3><p>With the above steps and infrastructure, we will have built a strong data foundation from which we can proceed into analysis, generate valuable insights, and enforce a culture of data-driven decision-making in an organization. Data processing and transformation is carried out so as to make the data transformation computationally efficient, more efficient meaning less time, less time means less cost, and also meaning decision-making capabilities in real-time.</p><p>Steps to data processing and transformation include:</p><p><strong>Data Cleaning</strong></p><p>Before data can be analyzed, it must be cleaned to ensure accuracy and reliability:</p><ul><li><strong>Removing Duplicates:</strong> Identifying and eliminating duplicate records to prevent skewed analysis.</li><li><strong>Handling Missing Values:</strong> Addressing gaps in data by filling in missing values or discarding incomplete records.</li><li><strong>Standardizing Data:</strong> Ensuring consistency in data formats and units across different datasets.</li></ul><p><strong>Data Transformation</strong></p><p>Transforming data into a suitable format for analysis involves several steps:</p><ul><li><strong>Normalization:</strong> Organizing data to reduce redundancy and improve integrity.</li><li><strong>Aggregation:</strong> Summarizing data to provide a higher-level overview, such as total sales per month.</li><li><strong>Encoding:</strong> Converting categorical data into numerical formats for machine learning algorithms.</li></ul><p><strong>ETL Pipelines</strong></p><p>ETL (Extract, Transform, Load) pipelines automate the process of moving and transforming data:</p><ul><li><strong>Extract:</strong> Retrieving data from various sources.</li><li><strong>Transform:</strong> Cleaning and transforming data into the desired format.</li><li><strong>Load:</strong> Loading the processed data into storage solutions like data warehouses or lakes.</li></ul><p>With the establishment of data processing and transformation pipelines, data can be extracted, processed, and transformed for analysis in real-time. With this, data can be prepared for suitable algorithms, and dashboards, that can be built in later stages.</p><h3>Data Visualization and Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YxbpHxoVnn1yJo-O.jpg" /></figure><p>Data visualization is the graphical representation of information and data. By using visual elements like charts, graphs, and maps, data visualization tools provide an accessible way to see and understand trends, outliers, and patterns in data. The importance of data visuals lies in their ability to transform complex datasets into clear and intuitive representations, making it easier for stakeholders to grasp insights and make informed decisions.</p><p>Displaying these visuals through dashboards is crucial as dashboards aggregate various data visualizations into a single interface, allowing users to monitor key performance indicators (KPIs) and metrics in real time. This consolidated view enhances comprehension, enabling users to spot trends and anomalies quickly. Dashboards can be tailored to specific audiences, ensuring that decision-makers have immediate access to the information most relevant to their roles.</p><p>Custom dashboards displaying Key Performance Indicators (KPIs) are instrumental in data-driven decision making as they provide a clear, visual representation of vital metrics that influence business performance. By synthesizing complex data into easily understandable formats, these dashboards allow decision-makers to quickly grasp the current state of the organization. This immediacy enables them to identify trends, pinpoint areas needing attention, and assess the effectiveness of strategies in real time.</p><p>The importance of data-driven decision-making lies in its ability to minimize uncertainty and bias in the decision-making process. Relying on empirical data, rather than intuition or anecdotal evidence, organizations can make informed choices that enhance operational efficiency, improve customer satisfaction, and drive growth. This approach fosters a culture of accountability, as decisions are backed by measurable outcomes, leading to better resource allocation and strategic planning.</p><p>Dashboards can serve many purposes, some of them include:</p><ol><li><strong>Executive Dashboards: </strong>These are high-level dashboards designed for senior management. They offer an overview of an organization’s performance, integrating strategic metrics that help executives make informed decisions quickly. They focus on critical data points and trends, allowing for agile responses to business challenges.</li><li><strong>Sales Dashboards: </strong>Tailored for sales teams, these dashboards track sales performance, pipeline metrics, and customer acquisition efforts. They visualize data related to revenue, sales targets, lead conversions, and team performance, enabling sales managers to optimize strategies and drive growth.</li><li><strong>Reporting Dashboards: </strong>These dashboards provide detailed reports on various operational activities, these are used primarily for reporting purposes.</li><li><strong>Analysis Dashboards: </strong>These dashboards focus on data analysis and visualization, enabling users to dive deep into specific metrics and trends. They often include advanced analytical tools and features such as predictive modeling and data mining.</li></ol><h3>Analysis with Machine Learning Algorithms</h3><p>With strong data foundations built, means to visualize data, and get insights quickly from visualized data, we can now take the next step with such data by automating insights and decisions. Machine learning is the process of using algorithms to analyze data patterns, enabling systems to learn from data inputs and improve their performance over time without explicit programming. This capability allows organizations to predict future trends, optimize operations, and enhance decision-making processes.</p><p>According to the availability of data, two types of machine learning algorithms can be empowered in an organization, they are:</p><p><strong>a. Supervised Learning</strong></p><p>This includes data that is labeled. For supervised machine learning, transactional data can be used, and various other tabulated data that benefit from a prediction can be used.</p><ol><li><strong>Predictive Modeling: </strong>Predictive modeling can be used to analyze trends and then predict wanted variables on the basis of those trends</li><li><strong>Recommender Systems: </strong>Though may be supervised or unsupervised techniques, data can be used to train powerful recommender systems increasing your churn.</li><li><strong>Automate various tedious business areas: </strong>This includes automating defaulting, churn prediction, etc which would usually require a person physically present.</li></ol><p><strong>b. Unsupervised Learning</strong></p><p>Unsupervised learning is a machine learning technique that can be used to discover trends and patterns in data. This can be extremely useful for an organization to gain additional insights into its operations, its users or its products. It can be used for:</p><ol><li><strong>Customer Segmentation: </strong>Separate customers into categories, according to their buying, and browsing habits, for better insights into customers, leading to a better conversion rate.</li><li><strong>Portfolio Optimization: </strong>View the performance of your products to better organize the portfolio to expect better conversions.</li><li><strong>Clustering and Segmentation: </strong>View different categories of your data for better insights</li></ol><p>These algorithms can also be embedded directly into the website, while these machine learning algorithms have a complete life cycle in themselves, that is a topic for another blog, and will not be covered here.</p><h3>In Conclusion</h3><p>Transforming raw data into actionable intelligence is a journey that requires a strategic approach, robust infrastructure, and continuous efforts. By understanding and collecting raw data, effectively storing and managing it, processing and transforming it into meaningful formats, and finally, visualizing and analyzing it, organizations can unlock the true potential of their data.</p><p>Data-driven strategies lead to informed decision-making, improved customer satisfaction, and optimized business processes. By embracing the power of data, organizations can innovate, grow, and thrive in today’s data-centric world.</p><p>Harnessing data is not just a technical endeavor but a cultural shift towards valuing insights and intelligence derived from data. As you embark on this journey, remember that the key to success lies in building strong data foundations, fostering a culture of continuous improvement, and staying agile in the face of ever-evolving data landscapes.</p><p>If you like this blog and want to read similar blogs to keep yourself updated, visit:</p><p><a href="https://gottdata.com/blogs">Gott Data</a></p><p>Follow us on LinkedIn:</p><p><a href="https://www.linkedin.com/company/gott-data/">Gott Data | LinkedIn</a></p><p><em>Note: I could write this blog in less than 30 minutes, with all pictures and media thanks to our Generative AI backed Content Management System </em><strong><em>Hugin</em></strong><em>. learn more about Hugin at:</em></p><p><a href="https://gottdata.com/products/hugin">Gott Data</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44691476fef9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insights into Recommender Systems]]></title>
            <link>https://medium.com/@atulranjan975/insights-into-recommender-systems-9c0241dfc95a?source=rss-f37e22283ec6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c0241dfc95a</guid>
            <dc:creator><![CDATA[Atul Ranjan]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 19:53:35 GMT</pubDate>
            <atom:updated>2024-06-12T19:53:35.917Z</atom:updated>
            <content:encoded><![CDATA[<h4>Points to consider before building and while implementing recommendation systems</h4><p>Big data analytics, machine learning algorithms, and data mining techniques have driven numerous innovations. Yet, recommender systems, despite being pivotal, often go underappreciated. Their widespread integration has made them almost invisible in this field, but their critical role in how we use web or mobile applications cannot be understated.</p><p>Recommender systems while being extremely important for a company, can be difficult to get right. In this article, I am sharing some of my experiences with recommenders and points to consider to get the most out of them for your business.</p><p>A brief introduction: I’m Atul Ranjan, a software engineer at Gott Data specializing in crafting AI and Machine Learning solutions that empower businesses to scale. Here I will be providing some valuable insights about recommender systems as follows or in the next couple of minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JgKPuv2ATMIKgqGckxEHw.png" /></figure><h3>Introduction to Recommender Systems</h3><p>A recommendation system is an algorithm tailored to discern a user’s preferences and suggest products based on those inclinations. A good recommender can be of tremendous value to any product and can be a pivotal investment your sales and growth team needs!</p><blockquote>In popular surveys conducted by Salesforce, it has been found that 54% of retailers claim that product recommendations act as the key driver of the AOV (Average Order Value). Research also show that shoppers that clicked on recommendations are 4.5 times more likely to add these items to the cart and 4.5 times more likely to complete the purchase. It is also seen that shoppers that clicked a product recommendation are nearly 2 times more likely to come back.</blockquote><p>A successful data model isn’t necessarily one that answers all existing questions, but one that sparks new ones. Recommendation systems are similar to any other data model. Building one for your business can provide tremendous new insights into your customer base and urge you to look into different perspectives.</p><p>Let’s now move towards considerations while building one!</p><h3>Customizing algorithms to meet business needs</h3><p>When constructing a recommendation system, it’s essential to balance algorithmic focus with a keen understanding of the business needs. A good recommendation system is not the most accurate algorithm on paper, but one that can perfectly fit the business.</p><p>It is therefore crucial to grasp the business objectives, profit models, target audience, and customer segmentation. A company might aim to promote a specific product, tailor recommendations by region, or find that the most frequently suggested item isn’t the most profitable. For some businesses, recommending similar products might not resonate while for others, it might work really well. A good algorithm should be able to capture all of these business needs along with the learnings from a thorough analysis of the provided data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7bSQdGNpvKitpm6HU2XuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVURHozdgWZaSKoiOY7KMA.png" /><figcaption>Different types of recommendations demonstrated through data by Kaggle, H&amp;M recommendations</figcaption></figure><h3>Selecting an algorithm</h3><p>Recommendation systems can be approached using a variety of algorithms, with the choice largely dependent on consistency, accuracy, speed, and, most crucially, the specific needs of the business. A brief overview of some prevalent recommender algorithms includes:</p><ol><li><strong>Item-Item Similarity: </strong>This method suggests products by gauging the similarity of other items to a chosen item.</li><li><strong>User-User Similarity: </strong>Unlike the item-based approach, this method recommends products by comparing the purchasing patterns of similar users to the active user.</li><li><strong>Association Rule Mining: </strong>This type of algorithm recommends items that are most often associated with the selected item</li><li><strong>Clustering-based Approaches: </strong>This method segments the user base into distinct clusters based on purchasing behavior, suggesting products under the premise that users within the same cluster have similar preferences.</li><li><strong>Popularity-Based Recommenders: </strong>A straightforward approach that suggests items based on their popularity. It’s often used in conjunction with other algorithms for enhanced results.</li><li><strong>Autoencoders and Deep Learning-based Recommenders: </strong>Tailored for unstructured data such as images, videos, and clips, these algorithms can be particularly precise in product recommendations.</li></ol><p>The ideal recommendation system often isn’t a standalone algorithm but a fusion of several. Nevertheless, the choice of algorithm should be tailored to the business’s specific needs.</p><p>Association Rule-Based Recommendations excel in enhancing the average sale per customer. For instance, when someone purchases a phone, this system might suggest complementary items like cases or chargers — products often bought together with phones. This not only introduces users to new product ideas but also adds a layer of convenience to their shopping experience.</p><p>For businesses where purchasing decisions are intricately tied to user characteristics or behaviors, Clustering-Based Approaches prove invaluable. Clustering involves segmenting users into distinct groups where members share similar profiles or habits. For sectors like insurance, where the type of policy a customer selects hinges heavily on their personal attributes, such systems are particularly effective.</p><p>Item-item similarity recommendations offer users a comparative perspective, allowing them to weigh products against one another, making it especially beneficial for e-commerce platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riTCDmSBOes1X05U5fx-jQ.png" /></figure><p>On the other hand, User-User Similarity recommenders provide broad-based suggestions. Although conceptually akin to clustering, their implementation often diverges.</p><p>These recommendation systems mentioned above use approaches like content-based filtering, collaborative filtering, clustering, classification, etc. to implement which are out of the scope of this article.</p><p>In summary, while all the mentioned algorithms can serve as robust general recommendation systems, aligning the right algorithm with business goals can exponentially amplify its impact to a considerable degree.</p><h3>Working with the data</h3><p>It’s needless to stress to a data scientist the importance of having accurate, comprehensive, and clean data when developing any machine learning algorithm. This principle is particularly, if not more, pertinent to recommendation systems. A well-executed recommender offers immense value, while a poorly implemented one can be costly for a business.</p><p>For recommendation systems, you’d typically focus on transactional data, user attribute information, item descriptions, and reviews. Supplemental data pertaining to these categories can also be instrumental.</p><p>When working with transactional data, it is essential to check the recency of the data. Taking historical data that is very old, may not be very fruitful as buying trends and patterns tend to change over time. In theory, you would consider the past year or two, but it depends on each business and the volume of data available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmoKYxM54h5spXeXGtguxA.png" /><figcaption>Order analysis sample</figcaption></figure><p>Due to these shifting patterns and customer behaviors, a comprehensive portfolio analysis, customer segmentation, and trend assessment are imperative before initiating the development of the recommendation system. The findings from such rigorous analyses can shed light on pivotal considerations for the system’s creation. They also offer a deeper insight into the business’s operational framework and revenue strategy. Furthermore, these analyses can pinpoint actionable insights and directions for the business even before the recommender’s development begins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fVvtrZCPoFsaqDv6ikR9Jg.png" /></figure><h3>Testing the algorithm</h3><p>During the development of machine learning algorithms, it’s vital to separate the data into training and test sets before diving into algorithm creation. The construction of an appropriate test set is a preliminary and necessary step, differing based on the dataset in question.</p><p>Evaluating the performance of recommendation systems is crucial to ensure that users receive appropriate and relevant recommendations. These are various metrics to evaluate the different aspects of recommendation systems.</p><ol><li><strong>Accuracy Metrics: </strong>These gauge the correctness of the recommendation outputs. Examples include Mean Absolute Error (MAE), RMSE, Precision, Recall, and AUC.</li><li><strong>Coverage Metrics: </strong>These reflect the reach and comprehensiveness of the recommendations. They encompass Catalog Coverage (percentage of items from the catalog that get recommended), User Coverage (percentage of users who receive recommendations), and Item Coverage (percentage of items that get recommended at least once). Not only do these metrics shed light on the system’s performance, but they also offer insights into the business’s offerings.</li><li><strong>Diversity and Novelty Metrics: </strong>These metrics evaluate the variety and freshness of the recommendations. They indicate how different and unexpected the suggestions are to users.</li></ol><p>Apart from these quantitative metrics, a qualitative evaluation of the system is essential. This ensures the system aligns well with the stakeholder needs. Additionally, it’s imperative to assess the system’s computational speed and efficiency.</p><h3>Deploying the System</h3><p>Taking the right steps while deploying a recommendation system is crucial in ensuring its effectiveness and enhancing the user experience. One critical aspect to consider during deployment is speed. The system should be able to provide recommendations quickly without compromising performance.</p><p>To achieve this, the recommendation system can be integrated into the application’s codebase as a module. This approach allows for faster response times since it eliminates the need for API calls. However, this method may not be feasible for all scenarios, and in such cases, using an API endpoint is more practical.</p><p>When utilizing an API endpoint, it’s essential to consider the computational cost of the algorithm and the speed of delivery. To address these concerns, precomputing recommendations and storing them in a database can help reduce the computational load. For instance, instead of calculating similar items on the fly, which requires a similarity search operation using metrics like cosine similarity or Jaccard index, you can precompute and store similar items in advance. Additionally, user segmentation can also be done ahead of time based on attributes, making it easier to retrieve relevant data from the database when needed.</p><p>In summary, when deploying a recommendation system, it’s vital to carefully evaluate the trade-offs between computational complexity and speed to ensure optimal performance and a seamless user experience.</p><h3>Final points</h3><p>Recommendation systems can be transformative for a business, often leading directly to increased sales. Beyond this immediate impact, the creation of such systems can be enlightening. This developmental journey can uncover deep insights into a business and pave the way for its evolution into a data-centric entity. In conclusion, stakeholders are equipped to make decisions rooted in data, thanks to the new data platforms and analytical tools that have been established.</p><p>I hope this article provided some insights about recommender systems. For a hands-on experience with a recommendation system and to explore its implementation using leading algorithms, please check out and experiment with the demo below. This experiment leverages data provided by H&amp;M to Kaggle with additional data preprocessing to implement these algorithms.</p><p><a href="https://recommendation-engine.streamlit.app/">Home</a></p><p>To further your business’s data evolution and craft a powerful recommendation system, or to initiate analytics and other AI-driven solutions or data endeavors, swing by our site and get in touch with us:</p><p><a href="https://gottdata.com/">Gott Data</a></p><p>Connect with me on LinkedIn:</p><p><a href="https://www.linkedin.com/in/atul-ranjan-83025622a/">https://www.linkedin.com/in/atul-ranjan-83025622a/</a></p><p>or reach out to me at:</p><p>atul@gottdata.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c0241dfc95a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Captioning with an End-to-End Transformer Network]]></title>
            <link>https://python.plainenglish.io/image-captioning-with-an-end-to-end-transformer-network-8f39e1438cd4?source=rss-f37e22283ec6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f39e1438cd4</guid>
            <category><![CDATA[image-captioning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Atul Ranjan]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 07:30:14 GMT</pubDate>
            <atom:updated>2022-06-13T01:49:12.030Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Elaborating on the attention mechanism and the Transformer Network to solve sequence-to-sequence problems through Image captioning with Transformer Networks.</em></h4><p>Transformer Networks are deep learning models that learn context and meaning in sequential data by tracking the relationships between the sequences. Since the introduction of Transformer Networks in 2017 by Google Brain in their revolutionary paper “<em>Attention is all you need</em>”, transformers have been outperforming conventional neural networks in various problem domains, like Neural Machine Translation, Text Summarization, Language Understanding, and other Natural Language Processing tasks. Along with this, they have also proved to be quite effective in Computer Vision tasks like Image Classification with Vision Transformers and Generative Networks as well.</p><p>In this article, I will be trying to elaborate on my understanding of the attention mechanism through vision transformers and on sequence to sequence tasks through Transformer Networks.</p><h3>Image Captioning as a Sequence to Sequence Problem</h3><p>For problems in the Image Domain, like Image Classification and feature extraction from Images, Deep Convolutional Neural Network architectures like ResNet and Inception are used. These Neural Networks extract features from a series of Convolution operations. Convolution layers in a Neural Network extract feature maps from images to classify and recognize them. Instead of using a CNN architecture, we can treat image problems like we do while dealing with text in NLP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*_7OaCZ05rRBmW3lsc7YZ3Q.png" /><figcaption>Visualizing the Learned features of a Convolutional Layer demonstrated at <a href="https://poloclub.github.io/cnn-explainer/">https://poloclub.github.io/cnn-explainer/</a></figcaption></figure><p>In Natural Language processing, we represent natural language as a sequence of tokens and try to learn the relationship between them. Each token has its representation as an n-dimensional vector also known as an embedding and these embeddings can be learned for language understanding. Similarly, we can represent an image as a sequence of patches, encode them with positional encodings to add information about their relative positions, and then represent each patch as an n-dimensional embedding. This will make the images ready as sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*ut1GVlMKcj7v-v8FYIDtuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*I__z7_LW46DfT3ArBQcRgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*SoXHGxDPUqFQHFbJKYoVLg.png" /><figcaption>Image representation as a series of patches and their embeddings</figcaption></figure><pre>from tensorflow import keras<br>from tensorflow.keras import layers<br></pre><pre>class Patches(layers.Layer):<br>    def __init__(self, patch_size):<br>        super(Patches, self).__init__()<br>        self.patch_size = patch_size</pre><pre>def call(self, images):<br>        batch_size = tf.shape(images)[0]<br>        patches = tf.image.extract_patches(<br>            images=images,<br>            sizes=[1, self.patch_size, self.patch_size, 1],<br>            strides=[1, self.patch_size, self.patch_size, 1],<br>            rates=[1, 1, 1, 1],<br>            padding=&quot;VALID&quot;,<br>        )<br>        patch_dims = patches.shape[-1]<br>        patches = tf.reshape(patches, [batch_size, -1, patch_dims])<br>        return patches</pre><pre>## Patch Encoder Layer <br>class PatchEncoder(layers.Layer):<br>    def __init__(self, num_patches, projection_dim):<br>        super(PatchEncoder, self).__init__()<br>        self.num_patches = num_patches<br>        self.projection = layers.Dense(units=projection_dim)<br>        self.position_embedding = layers.Embedding(<br>            input_dim=num_patches, output_dim=projection_dim<br>        )</pre><pre>def call(self, patch):<br>        positions = tf.range(start=0, limit=self.num_patches, delta=1)<br>        encoded = self.projection(patch) + self.position_embedding(positions)<br>        return encoded</pre><p>The Patches class breaks down the image into patches and the Patch Encoder Layer encodes the patches with Positional Encodings. The shapes of the patches with the following hyperparameters can be checked:</p><pre>## HYPER-PARAMETERS:<br>LEARNING_RATE = 0.001<br>WEIGHT_DECAY = 0.0001<br>BATCH_SIZE = 64<br>NUM_EPOCHS = 100<br>IMAGE_SIZE = 128<br>PATCH_SIZE = 16<br>NUM_PATCHES = (IMAGE_SIZE//PATCH_SIZE) ** 2<br>PROJECTION_DIM = 512<br>NUM_HEADS = 4<br>PERCEPTRON_UNITS = [2*PROJECTION_DIM, PROJECTION_DIM]<br></pre><pre>resized_image = tf.image.resize(<br>    tf.convert_to_tensor([try_img]), size=(IMAGE_SIZE, IMAGE_SIZE)<br>)<br>patches = Patches(PATCH_SIZE)(resized_image)<br></pre><pre>## Checking the shapes<br>print(f&quot;Shape of the resized image {resized_image.shape}&quot;)<br>print(f&quot;Shape of the patches: {patches.shape}&quot;)<br>encoded_patches = PatchEncoder(NUM_PATCHES, PROJECTION_DIM)(patches)<br>print(f&quot;Shape of the Encoded patches: {encoded_patches.shape}&quot;)</pre><p>Output:</p><pre>Shape of the resized image (1, 128, 128, 3)<br>Shape of the patches: (1, 64, 768)<br>Shape of the Encoded patches: (1, 64, 512)</pre><h3>The Transformer Network</h3><p>The Transformer Network learns context and thus meaning in a sequence through the attention mechanism, meaning they can extract information even from a variable length of sequences. Below is a step-by-step walkthrough of the Transformer network.</p><h4>Why Transformers?</h4><p>Before transformers, sequence-to-sequence problems were carried out with an Encoder-Decoder architecture with RNN cells, where LSTMs (Long Short Term Memory) units were a popular choice, as they could retain information for comparatively longer sequences than traditional RNN cells. But even LSTM networks suffered from the vanishing gradient problem for long sequences. LSTMs typically lose information with sequences over the length of 100. Another issue with LSTM cells was that it was difficult to parallelize the computations carried out in an LSTM network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*n3F8EFCZueEb4z0X.png" /><figcaption>The Vanishing Gradient Problem (mc.ai)</figcaption></figure><p>Transformers tackle this issue by looking at the entire sequence and assigning them <em>attention</em> weights that intuitively, signify the importance of one part of a sequence. With Transformers, the vanishing gradient problem is also solved and the computations can be carried out in parallel.</p><h4>Transformer Network Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3ze0JiQNPsLTN8tDFKfaQ.png" /><figcaption>The Transformer Network Architecture</figcaption></figure><p>The Transformer Network is an Encoder-Decoder architecture but unlike other Sequence-to-Sequence architectures, Transformers rely on attention mechanism instead of RNN cells to understand the relationship between sequences. The Encoder takes in the Input Embeddings and outputs a vector representation with the shape (batch size, sequence length, model dimensions). The Decoder takes in the target sequence as its input and, first attends to itself for language understanding and then, tries to compute its relationship with the encoder outputs. At a high level, it tries to figure out which part of the Input is the relevant information for the corresponding target. The Decoder then represents this information as a vector and finally gives output probabilities</p><h4>The Attention Mechanism</h4><p>Transformers learn the inter-relationship between sequences through the attention mechanism. Intuitively, attention is a weight on how important a token (or patch) is in the sequence considering our problem domain. Considering our problem of Image captioning, at the encoder, attention weights are assigned to each patch of the image. These weights signify what part of the image the model should attend to while performing a task. These weights are learned and updated over time as the model trains.</p><p>Below, the attention weights are visualized showing what part of the image each attention head is focusing on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/0*4rf60m_tYB8IQ5sI.jpg" /><figcaption>Visualization of Attention weights on an image.</figcaption></figure><h4>Scaled Dot Product Attention</h4><p>In the paper, the authors use Multi Headed Attention which implements the scaled dot product attention, a simple but powerful form of attention mechanism.</p><p><em>The Query, Key, and Value:</em></p><p><em>Query, key, and value are Transformer terminologies that have quite the literal meaning. Each Key vector is associated with a value vector and is queried by the query vector. In our problem domain consider the following:</em></p><p><em>Each patch of the image is the key K and each key K is associated with the value V. While computing the Multi-Head Attention in the Decoder, the patches are queried with tokens Q.</em></p><p>If the token to be queried is the word “frisbee”, the scaled dot product attention, assigns the highest weight to the key, (In our case patches of the image showing the frisbee)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h5jXWndoNLLXChem.png" /><figcaption>Attention plots for images taken from the paper “<strong><em>Show, Attend, and Tell Neural Image Caption Generation with Visual Attention”</em></strong></figcaption></figure><p>Mathematically, the scaled dot product attention is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*glkmu3PCc8oISSO43-lEdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*VkotNjWOdPGMSltDXYSa4g.png" /><figcaption>Calculation of the Scaled Dot Product Attention.</figcaption></figure><p>Here Q, K, and V are tensors, which are the results of the matrix multiplication between trained weights Wq, Wk, and Wv. As these three matrices of weights are learned during training, the query, key, and value vectors end up being different despite the identical input. This is why Multi-Head Attention discussed later makes sense.</p><p>In the expression for calculation of the dot product attention, Q and K are tensors. Closer Query and Key Vectors will have higher dot products. These dot products are scaled with dk which is the scaling factor for the operation referring to the dimensions of the Key tensor. Applying the softmax function will normalize the dot product to scores between 0 and 1. Finally, multiplying the softmax results with the value vectors will push the low-scoring Query and Key vectors close to zero.</p><p>Below is the implementation of the scaled dot product attention in code:</p><pre>def scaled_dot_product_attention(q, k, v, mask):<br>  &quot;&quot;&quot;Calculate the attention weights.<br>  q, k, v must have matching leading dimensions.<br>  k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.<br>  The mask has different shapes depending on its type(padding or look ahead)<br>  but it must be broadcastable for addition.</pre><pre>Args:<br>    q: query shape == (..., seq_len_q, depth)<br>    k: key shape == (..., seq_len_k, depth)<br>    v: value shape == (..., seq_len_v, depth_v)<br>    mask: Float tensor with shape broadcastable<br>          to (..., seq_len_q, seq_len_k). Defaults to None.</pre><pre>Returns:<br>    output, attention_weights<br>  &quot;&quot;&quot;</pre><pre>matmul_qk = tf.matmul(q, k, transpose_b=True)  # (..., seq_len_q, seq_len_k)</pre><pre># scale matmul_qk<br>  dk = tf.cast(tf.shape(k)[-1], tf.float32)<br>  scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)</pre><pre># add the mask to the scaled tensor.<br>  if mask is not None:<br>    scaled_attention_logits += (mask * -1e9)</pre><pre># softmax is normalized on the last axis (seq_len_k) so that the scores<br>  # add up to 1.<br>  attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1)  # (..., seq_len_q, seq_len_k)</pre><pre>output = tf.matmul(attention_weights, v)  # (..., seq_len_q, depth_v)</pre><pre>return output, attention_weights</pre><h4>Multi-Head Attention:</h4><p>In a Transformer Network, the Attention Module described earlier repeats its computations multiple times in parallel. Each of these computations is called an Attention Head. Each of these calculations is later combined to produce a final attention score.</p><p>As discussed earlier, for each Attention Head, Queries Q, Keys K, and Values V are calculated as results from learnable weight matrices Wq, Wk, and Wv. These weight matrices are different for each head, hence, for n number of heads n different weight matrices Wq, Wk and Wv are learned. Scaled dot product attention is carried out in each of the heads and finally, the results are concatenated together to form a rich representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*8eSEx9nmvL9YsI8tTd0V2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2cy5Jzl9JZM6HWOE6vffg.png" /><figcaption>Representation o multi Head attention from “Attention is all you need”, <a href="https://towardsdatascience.com/transformers-explained-visually-part-3-multi-head-attention-deep-dive-1c1ff1024853">https://towardsdatascience.com/transformers-explained-visually-part-3-multi-head-attention-deep-dive-1c1ff1024853</a></figcaption></figure><p>As for each head, different weight matrices are learned, this allows the Transformer to encode multiple relationships and nuances for each element in the sequence. With Multi-Head Attention, in our problem domain, each head can have a different representation for a patch in the Encoder, and each word can have multiple relationships and nuances in the Decoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cguDZE1qODb03z-KmxTwAQ.png" /><figcaption>Mathematical representation of the multi-head Attention</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6EbgPor0k7bcEt_P6kA9A.png" /><figcaption>Attention Plots for the same image with different attention heads.</figcaption></figure><p>Tensorflow implementation of Multi-Head Attention:</p><pre>class MultiHeadAttention(tf.keras.layers.Layer):<br>  def __init__(self,*, d_model, num_heads):<br>    super(MultiHeadAttention, self).__init__()<br>    self.num_heads = num_heads<br>    self.d_model = d_model</pre><pre>assert d_model % self.num_heads == 0</pre><pre>self.depth = d_model // self.num_heads</pre><pre>self.wq = tf.keras.layers.Dense(d_model)<br>    self.wk = tf.keras.layers.Dense(d_model)<br>    self.wv = tf.keras.layers.Dense(d_model)</pre><pre>self.dense = tf.keras.layers.Dense(d_model)</pre><pre>def split_heads(self, x, batch_size):<br>    &quot;&quot;&quot;Split the last dimension into (num_heads, depth).<br>    Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth)<br>    &quot;&quot;&quot;<br>    x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))<br>    return tf.transpose(x, perm=[0, 2, 1, 3])</pre><pre>def call(self, v, k, q, mask):<br>    batch_size = tf.shape(q)[0]</pre><pre>q = self.wq(q)  # (batch_size, seq_len, d_model)<br>    k = self.wk(k)  # (batch_size, seq_len, d_model)<br>    v = self.wv(v)  # (batch_size, seq_len, d_model)</pre><pre>q = self.split_heads(q, batch_size)  # (batch_size, num_heads, seq_len_q, depth)<br>    k = self.split_heads(k, batch_size)  # (batch_size, num_heads, seq_len_k, depth)<br>    v = self.split_heads(v, batch_size)  # (batch_size, num_heads, seq_len_v, depth)</pre><pre>#print(f&quot;Query shape: {q.shape}&quot;)<br>    #print(f&quot;Key shape: {k.shape}&quot;)<br>    #print(f&quot;value shape: {v.shape}&quot;)</pre><pre># scaled_attention.shape == (batch_size, num_heads, seq_len_q, depth)<br>    # attention_weights.shape == (batch_size, num_heads, seq_len_q, seq_len_k)<br>    scaled_attention, attention_weights = scaled_dot_product_attention(<br>        q, k, v, mask)</pre><pre>scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3])  # (batch_size, seq_len_q, num_heads, depth)</pre><pre>concat_attention = tf.reshape(scaled_attention,<br>                                  (batch_size, -1, self.d_model))  # (batch_size, seq_len_q, d_model)</pre><pre>output = self.dense(concat_attention)  # (batch_size, seq_len_q, d_model)</pre><pre>return output, attention_weights</pre><h3>Image Captioning with Transformers:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-TEUQ9jfIa5iW8I6ssPew.png" /><figcaption>The Architecture of the Image Captioning Model. Source: “CPTR: Full transformer network for Image Captioning”</figcaption></figure><p>The Transformer for Image captioning consists of an Encoder and a decoder with Encoder layers and Decoder Layers within them, below, the components of the transformer are elaborated:</p><h4>The Encoder</h4><p>The Encoder of the transformer takes in an image of dimensions (batch_size, image_size, image_size, num_channels) as input, breaks down the images into patches with the Patches class implemented in the above example, then positional embeddings are added to the patches as discussed above and passed on to the Encoder layer. The Encoder layer has a self-attention layer with residual connections which self attend to the patches. The attention layer outputs a context vector which is then passed to a point-wise feed foreword neural network. Finally, the Encoder outputs a tensor of shape (batch_size, seq_length, d_model)</p><p>However, as transformers have an extremely large set of learnable parameters and computation costs, though parallelized is quite significant, for this implementation, a pretrained vision transformer is used from the TensorFlow hub.</p><pre>from vit_keras import vit</pre><pre>vit_model = vit.vit_b32(<br>        image_size = IMAGE_SIZE,<br>        activation = &#39;softmax&#39;,<br>        pretrained = True,<br>        include_top = False,<br>        pretrained_top = False,<br>        )</pre><pre>new_input = vit_model.input<br>hidden_layer = vit_model.layers[-2].output<br>vision_transformer_model = tf.keras.Model(new_input, hidden_layer)</pre><pre>### The Encoder Class</pre><pre>class Encoder(tf.keras.layers.Layer):<br>  def __init__(self, d_model, vision_transformer):<br>    super(Encoder, self).__init__()<br>    self.vit = vision_transformer<br>    self.units = d_model<br>    self.dense = tf.keras.layers.Dense(self.units, activation=tf.nn.gelu)</pre><pre>def call(self, x, training, mask):<br>    ## x: (batch, image_size, image_size, 3)<br>    x = self.vit(x)<br>    x = self.dense(x)<br>    return x</pre><h4>The Decoder</h4><p>The Decoder takes in the target captions as the input positionally encodes it, and passes it through a masked self-attention layer. The self-attention layer is masked for the decoder to not see the outputs from the future. This allows the decoder to understand the context of the target captions. The target captions are then used as a query for the Multi-Head Attention layer with the encoder outputs as the keys and values. This allows the network to learn the relationships between the captions and the relevant parts of the images. During training, these attention weights are learned and backpropagated through the entire network, and the network learns over time. The Multi-Head Attention layer produces a context vector which is then passed through a softmax function to output a set of probabilities for prediction.</p><pre>def point_wise_feed_forward_network(d_model, dff):<br>  return tf.keras.Sequential([<br>      tf.keras.layers.Dense(dff, activation=&#39;relu&#39;),  # (batch_size, seq_len, dff)<br>      tf.keras.layers.Dense(d_model)  # (batch_size, seq_len, d_model)<br>  ])</pre><pre>### Decoder Layer:<br>class DecoderLayer(tf.keras.layers.Layer):<br>  def __init__(self,*, d_model, num_heads, dff, rate=0.1):<br>    super(DecoderLayer, self).__init__()</pre><pre>self.mha1 = MultiHeadAttention(d_model=d_model, num_heads=num_heads)<br>    self.mha2 = MultiHeadAttention(d_model=d_model, num_heads=num_heads)</pre><pre>self.ffn = point_wise_feed_forward_network(d_model, dff)</pre><pre>self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)<br>    self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)<br>    self.layernorm3 = tf.keras.layers.LayerNormalization(epsilon=1e-6)</pre><pre>self.dropout1 = tf.keras.layers.Dropout(rate)<br>    self.dropout2 = tf.keras.layers.Dropout(rate)<br>    self.dropout3 = tf.keras.layers.Dropout(rate)</pre><pre>def call(self, x, enc_output, training,<br>           look_ahead_mask, padding_mask):<br>    # enc_output.shape == (batch_size, input_seq_len, d_model)</pre><pre>#print(f&quot;Decoder Layer input x shape: {x.shape}&quot;)</pre><pre>attn1, attn_weights_block1 = self.mha1(x, x, x, look_ahead_mask)  # (batch_size, target_seq_len, d_model)<br>    attn1 = self.dropout1(attn1, training=training)<br>    #print(&quot;attn2 shape: &quot;, attn1.shape)<br>    #print(f&quot;x shape: {x.shape}&quot;)<br>    out1 = self.layernorm1(attn1 + x)</pre><pre>#print(f&quot;Encoder outpur (Value and key) shape: {enc_output.shape}&quot;)<br>    #print(f&quot;out1 (Query) shape: {out1.shape}&quot;)</pre><pre>attn2, attn_weights_block2 = self.mha2(<br>        enc_output, enc_output, out1, None)  # (batch_size, target_seq_len, d_model)<br>    attn2 = self.dropout2(attn2, training=training)<br>    out2 = self.layernorm2(attn2 + out1)  # (batch_size, target_seq_len, d_model)</pre><pre>ffn_output = self.ffn(out2)  # (batch_size, target_seq_len, d_model)<br>    ffn_output = self.dropout3(ffn_output, training=training)<br>    out3 = self.layernorm3(ffn_output + out2)  # (batch_size, target_seq_len, d_model)</pre><pre>return out3, attn_weights_block1, attn_weights_block2</pre><pre>class Decoder(tf.keras.layers.Layer):<br>  def __init__(self,*, num_layers, d_model, num_heads, dff, target_vocab_size, max_tokens,<br>               rate=0.1):<br>    super(Decoder, self).__init__()</pre><pre>self.d_model = d_model<br>    self.num_layers = num_layers<br>    self.max_tokens =  max_tokens</pre><pre>self.embedding = tf.keras.layers.Embedding(target_vocab_size, d_model)<br>    self.pos_encoding = positional_encoding(max_tokens, d_model)</pre><pre>self.dec_layers = [<br>        DecoderLayer(d_model=d_model, num_heads=num_heads, dff=dff, rate=rate)<br>        for _ in range(num_layers)]<br>    self.dropout = tf.keras.layers.Dropout(rate)</pre><pre>def call(self, x, enc_output, training,<br>           look_ahead_mask, padding_mask):</pre><pre>seq_len = tf.shape(x)[1]<br>    attention_weights = {}</pre><pre>x = self.embedding(x)  # (batch_size, target_seq_len, d_model)<br>    x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))<br>    x += self.pos_encoding[:, :seq_len, :]</pre><pre>x = self.dropout(x, training=training)</pre><pre>for i in range(self.num_layers):<br>      x, block1, block2 = self.dec_layers[i](x, enc_output, training,<br>                                             look_ahead_mask, padding_mask)</pre><pre>attention_weights[f&#39;decoder_layer{i+1}_block1&#39;] = block1<br>      attention_weights[f&#39;decoder_layer{i+1}_block2&#39;] = block2</pre><pre># x.shape == (batch_size, target_seq_len, d_model)<br>    return x, attention_weights</pre><p>For instance, if the caption says “cat”, the relevant parts of the picture showing the picture of a cat are learned by the network through backpropagation.</p><p>Combining the Encoder and decoder, the Transformer model can be created as a TensorFlow Keras Model, as shown below:</p><pre>class Transformer(tf.keras.Model):<br>  def __init__(self,*, num_layers, d_model, num_heads, dff,<br>               target_vocab_size, vision_transformer, max_tokens, rate=0.1):<br>    super().__init__()<br>    self.vision_transformer = vision_transformer<br>    self.encoder = Encoder(d_model,<br>                           self.vision_transformer)</pre><pre>self.decoder = Decoder(num_layers=num_layers, d_model=d_model,<br>                           num_heads=num_heads, dff=dff,<br>                           target_vocab_size=target_vocab_size, max_tokens=max_tokens, rate=rate)</pre><pre>self.final_layer = tf.keras.layers.Dense(target_vocab_size)</pre><pre>def call(self, inputs, training):<br>    # Keras models prefer if you pass all your inputs in the first argument<br>    #print(&quot;Transformer call function called&quot;)<br>    inp, tar = inputs<br>    #print(f&quot;inp: {inp.shape}.     tar: {tar.shape}&quot;)<br>    padding_mask, look_ahead_mask = self.create_masks(inp, tar)</pre><pre>#print(f&quot;Mask shapes: {padding_mask.shape}.    {look_ahead_mask.shape}&quot;)</pre><pre>enc_output = self.encoder(inp, training, None)  # (batch_size, inp_seq_len, d_model)<br>    #print(&quot;Encoder Works&quot;)<br>    # dec_output.shape == (batch_size, tar_seq_len, d_model)<br>    dec_output, attention_weights = self.decoder(<br>        tar, enc_output, training, look_ahead_mask, padding_mask)</pre><pre>final_output = self.final_layer(dec_output)  # (batch_size, tar_seq_len, target_vocab_size)</pre><pre>return final_output, attention_weights</pre><pre>def create_masks(self, inp, tar):<br>    # Encoder padding mask (Used in the 2nd attention block in the decoder too.)<br>    padding_mask = create_padding_mask(inp)</pre><pre># Used in the 1st attention block in the decoder.<br>    # It is used to pad and mask future tokens in the input received by<br>    # the decoder.<br>    look_ahead_mask = create_look_ahead_mask(tf.shape(tar)[1])<br>    dec_target_padding_mask = create_padding_mask(tar)<br>    look_ahead_mask = tf.maximum(dec_target_padding_mask, look_ahead_mask)</pre><pre>return padding_mask, look_ahead_mask</pre><h3>Training:</h3><p>The Transformer Module was trained with a custom Sparse Categorical Cross-Entropy Loss with a learning rate scheduler, Adam optimizer, and a batch size of 128 for about 2 epochs (due to training time and computational resources). For experimentation, the transformer had 256 dimensions and 8 layers in total with 4 heads for Multi-Head Attention. After 2 epochs, the transformer could make decent predictions on the image.</p><p><em>Detailed code can be found in the notebook provided at the end of the article.</em></p><h3>Results</h3><p>Qualitative analysis of the results shows that the transformer network could generate decent captions for the input images even with limited time and resources. Below are some captions generated by the transformer network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*-sMeRBg6AKW-wpxO-Bhhlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*4py_zs2SoERUt8syxs32lA.png" /></figure><p>More results are available in the notebook provided below. Better results could be obtained if the model was trained for more epochs and if the hyperparameters were tuned for a larger number of learnable parameters</p><h3>Further applications</h3><p>As the transformer model is able to quite fabulously understand the relationship between the images and the captions, intuitively, I can think of it having applications for captioning images in domains convolutional neural networks fail to generalize well, such as Medical images. As they are quite something at the sequence to sequence problems video captioning would also be an interesting application of this caption transformer model.</p><h3>Project on Github</h3><ul><li><a href="https://colab.research.google.com/drive/1rJ-iT6A5MYVI1ASifwqt7bdgsc0OEBKL#scrollTo=VLcZEaugRqh0">Google Colaboratory</a></li><li><a href="https://github.com/Atul-Ranjan12/Caption-Transformer-Model/blob/main/Caption_transformer.ipynb">Caption-Transformer-Model/Caption_transformer.ipynb at main · Atul-Ranjan12/Caption-Transformer-Model</a></li></ul><h3>Social Media Links</h3><p>Reach out to me for projects or queries on:</p><p>LinkedIn:</p><p><a href="https://www.linkedin.com/in/atul-ranjan-83025622a/">Atul Ranjan - Delhi Technological University (Formerly DCE) - Kathmandu, Bāgmatī, Nepal | LinkedIn</a></p><p>Or drop an email: atulranjan975@gmail.com</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.i</em></strong><em>o</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Check out our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Community Discord</em></strong></a><em> and join our </em><a href="https://inplainenglish.pallet.com/talent/welcome"><strong><em>Talent Collective</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f39e1438cd4" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/image-captioning-with-an-end-to-end-transformer-network-8f39e1438cd4">Image Captioning with an End-to-End Transformer Network</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cycle GANs: Generating Paintings of My Campus in Van Gogh’s Painting Style]]></title>
            <link>https://python.plainenglish.io/cycle-gans-generating-paintings-of-my-campus-in-van-goghs-style-9d578b11edf6?source=rss-f37e22283ec6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d578b11edf6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Atul Ranjan]]></dc:creator>
            <pubDate>Sun, 06 Mar 2022 20:10:04 GMT</pubDate>
            <atom:updated>2022-03-07T08:19:01.129Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Using Conditional Generative Adversarial Networks, specifically Cycle GANs, to generate paintings of my campus in Vincent Van Gogh’s style.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*mM8Y41fBIJblWAFV1XjrPQ.png" /></figure><p>Generative Adversarial Networks or GANs were first proposed in 2014 by Ian Goodfellow and others. Since then, they have been described as the most interesting development in AI in the last decade. GANs, as the name suggests, are generative networks, which means, now, one could not only classify content with deep learning but also generate them. In this article, I’ve described a Conditional GAN and its implementation in Keras TensorFlow.</p><h3>A Brief Introduction to GANs</h3><p>Generative networks are Deep Neural Nets capable of generating the content, specifically pictures. With deep learning developing at its highest pace ever, and with state-of-the-art algorithms, GANs have produced jaw-dropping results.</p><p>Believe it or not, the pictures of the people below are generated by one such GAN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHS0YU-i1vw4RfEnGpIqqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDD5iT9RBZU4Q25uxClK5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_OAmMj4HdMzCqezeATUMw.png" /></figure><p>You can view more such faces by visiting the website below:</p><p><a href="https://thispersondoesnotexist.com/">This Person Does Not Exist</a></p><h4>How GANs work:</h4><p>GANs are a system of two neural networks, one generator, and one discriminator. The generator is responsible for generating new images, and the discriminator is responsible for asserting if an image is real or fake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*zLcQHyFbQWCrYnV-uAS8BA.png" /><figcaption>General Architechture of A GAN</figcaption></figure><p>To understand a GAN, we can take the example of the shop owner and a counterfitter. The generator or the counterfitter tries to generate more and more realistic notes to fool the shop owner, the shop owner, or the discriminator, however, recognizes the counterfit money. Because of this, the counterfitter has to improve his skills and generate more and more realistic-looking money to trick the shopkeeper, and the shopkeeper has to learn to recognize every detail of the money to not get fooled. In this way, the generator and discriminator train together, so that the generator produces more and more realistic results.</p><h4>The Loss function and the training process of a GAN</h4><p>As there are two Neural Nets in a GAN, a GAN has two losses, a generator loss, and a discriminator loss. Since the discriminator has to predict if an image is real or fake, this is a binary classification problem, hence for binary classification, the discriminator uses a <em>binary cross-entropy loss, </em>given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3SUPJtpFaVafh7lXwAWgoQ.png" /><figcaption>Binary Cross-Entropy</figcaption></figure><p>For the generator, the loss function is a bit complicated. Firstly the generator generates an image that gets fed into the discriminator for classification. If we think of it this way, the generator is just a big neural network. During the training process, we freeze the discriminator so that only the generator weights get trained. This process has a twist though. While passing the labels to the discriminator we pass them in as ones instead of zeros, to encourage the generator training, and as the discriminator weights are frozen, only the generator will train. Hence the generator loss also becomes a binary cross-entropy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RU4jBfAR7fC8EoR-uUq-Zg.png" /><figcaption>The loss function of the generator</figcaption></figure><p>The input of the generator is just noise from a multi-variate standard normal. Over time, the generator will learn to map this noise to an image. For instance, we have a random vector z, which comes from a standard normal, and has a size of 100. This 100-dimensional space is called the latent space.</p><p>The latent space is essentially an imaginary space where the generator thinks about where the images live.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RUdGYoUYGe9cKHEw.png" /></figure><p>Training the GAN is just applying these gradients to minimize the loss function.</p><pre>for epoch in range(300):<br>  for idx, real in enumerate(tqdm(dataset)):<br>    batch_size = real.shape[0]<br>    random_latent_vectors = tf.random.normal(shape = (batch_size,                latent_dim))</pre><pre>fake = generator(random_latent_vectors)</pre><pre>if idx % 199 == 0:<br>      img = keras.preprocessing.image.array_to_img(fake[0])<br>      img.save(f&quot;/content/generated_images_model2/generated_img{epoch}_{idx}_.png&quot;)</pre><pre>### Train Discriminator: max log(D(x)) + log(1-D(G(z)))<br>    with tf.GradientTape() as disc_tape:<br>      loss_disc_real = loss_fn(tf.ones((batch_size, 1)), discriminator(real))<br>      loss_disc_fake = loss_fn(tf.zeros((batch_size, 1)), discriminator(fake))<br>      loss_disc = (loss_disc_real + loss_disc_fake)/2</pre><pre>grads = disc_tape.gradient(loss_disc, discriminator.trainable_weights)<br>    opt_disc.apply_gradients(<br>        zip(grads, discriminator.trainable_weights)<br>    )</pre><pre>### Train the Generator: min log(1 - D(G(z))) &lt;-&gt; max log(D(G(z)))<br>    with tf.GradientTape() as gen_tape:<br>      fake = generator(random_latent_vectors)<br>      output = discriminator(fake)<br>      loss_gen = loss_fn(tf.ones(batch_size, 1), output)</pre><pre>grads = gen_tape.gradient(loss_gen, generator.trainable_weights)<br>    opt_gen.apply_gradients(<br>        zip(grads, generator.trainable_weights)<br>    )</pre><h3>Cycle GANs</h3><p>In a typical GAN, the GAN generates images from the given domain. In such GANs, the relationship between the generated images and the latent space is hard to map. Battling this, Phillip Isola, Jun-Yan Zhu, Tinghui Zhou, Alexei A. Efros researched and came up with “PixToPix GAN” described in their research paper <em>“Image-to-Image Translation with Conditional Adversarial Networks”</em> in which the GAN could be conditioned with other image modalities. The PixToPix GAN could train with paired images, for instance, it could train on paired pictures of places day and night, and generate nighttime pictures.</p><p>However, it is not always possible to find paired datasets, and the same researchers came up with another generative network “<em>Cycle GAN” </em>described in their paper <em>“Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks” </em>This network could be trained on one image modality and could be mapped to another without pairing. The research papers on Cycle GAN and PixToPix are below:</p><ul><li><a href="https://paperswithcode.com/paper/unpaired-image-to-image-translation-using">Papers with Code - Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks</a></li><li><a href="https://paperswithcode.com/paper/image-to-image-translation-with-conditional">Papers with Code - Image-to-Image Translation with Conditional Adversarial Networks</a></li></ul><p>I’ve tried a simple implementation of Cycle GANs in TensorFlow Keras and described it in this article.</p><h4>Setting up the data</h4><p>To train the GAN, I used the TensorFlow dataset of Van Gogh paintings and pictures. The dataset contains images of Vincent Van Gogh’s paintings and normal photos.</p><pre>dataset, metadata = tfds.load(‘cycle_gan/vangogh2photo’,<br> with_info=True, as_supervised=True)</pre><pre>train_van_gogh, train_photo = dataset[‘trainA’], dataset[‘trainB’]<br>test_van_gogh, test_photo = dataset[‘testA’], dataset[‘testB’]</pre><p><em>Augmenting the data</em></p><p>As described in the paper on Cycle GANs, the model performed best when a random crop, jitter, and mirror was applied to the dataset. We can easily make these functions with TensorFlow and Matplotlib,</p><pre>### Initializing some important values<br>BUFFER_SIZE = 1000<br>BATCH_SIZE = 1<br>IMG_WIDTH = 256<br>IMG_HEIGHT = 256<br></pre><pre>### Randomly crop the image<br>def random_crop(image):<br>  cropped_image = tf.image.random_crop(<br>      image, size=[IMG_HEIGHT, IMG_WIDTH, 3])</pre><pre>return cropped_image<br></pre><pre>### Normalize the image<br># normalizing the images to [-1, 1]<br>def normalize(image):<br>  image = tf.cast(image, tf.float32)<br>  image = (image / 127.5) - 1<br>  return image<br></pre><pre>### Random jitter in the image according to the paper<br>def random_jitter(image):<br>  # resizing to 286 x 286 x 3<br>  image = tf.image.resize(image, [286, 286],<br>                          method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)</pre><pre># randomly cropping to 256 x 256 x 3<br>  image = random_crop(image)</pre><pre># random mirroring<br>  image = tf.image.random_flip_left_right(image)</pre><pre>return image<br></pre><pre>### Preprocessing the image<br>def preprocess_image_train(image, label):<br>  image = random_jitter(image)<br>  image = normalize(image)<br>  return image<br></pre><pre>def preprocess_image_test(image, label):<br>  image = normalize(image)<br>  return image</pre><p>Mapping these functions to the dataset:</p><pre>train_van_gogh = train_van_gogh.cache().map(<br>    preprocess_image_train, num_parallel_calls=AUTOTUNE).shuffle(<br>    BUFFER_SIZE).batch(BATCH_SIZE)</pre><pre>train_photo = train_photo.cache().map(<br>    preprocess_image_train, num_parallel_calls=AUTOTUNE).shuffle(<br>    BUFFER_SIZE).batch(BATCH_SIZE)</pre><pre>test_van_gogh = test_van_gogh.map(<br>    preprocess_image_test, num_parallel_calls=AUTOTUNE).cache().shuffle(<br>    BUFFER_SIZE).batch(BATCH_SIZE)</pre><pre>test_photo = test_photo.map(<br>    preprocess_image_test, num_parallel_calls=AUTOTUNE).cache().shuffle(<br>    BUFFER_SIZE).batch(BATCH_SIZE)</pre><h4>Visualizing the data</h4><pre>sample_van_gogh = next(iter(train_van_gogh))<br>sample_photo = next(iter(train_photo))</pre><pre>plt.figure()<br>plt.imshow(sample_van_gogh[0] * 0.5 + 0.5)<br>plt.axis(False)</pre><pre>plt.figure()<br>plt.imshow(sample_photo[0]*0.5 + 0.5)<br>plt.axis(False)</pre><h4>Building the Model: Generator Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ro1qdHu-UduJZiNMG5qPhw.png" /><figcaption>Generator Model Architechture (Save and view)</figcaption></figure><p>For the generators, the authors of the paper used a Resnet architecture with 6 or 9 residual blocks followed by 2 Conv2DTranspose layers. Although a U-Net architecture should work fine as well and is done by people, I used a resnet architecture for my generator model. Additionally, the authors used Instance Normalization instead of Batch Normalization.</p><p>This generator will generate noise from a multivariate standard normal and slowly map it across the given image modality when it trains.</p><pre>## Making the functions<br>def _get_norm_layer(norm):<br>  if norm == &quot;none&quot;:<br>    return lambda: lambda x: x<br>  elif norm == &quot;batch_norm&quot;:<br>    return keras.layers.BatchNormalization<br>  elif norm == &quot;instance_norm&quot;:<br>    return tfa.layers.InstanceNormalization<br>  elif norm == &quot;layer_norm&quot;:<br>    return keras.layers.LayerNormalization</pre><p>Making the Resnet generator:</p><pre>### Making the resnet block<br>def ResnetGenerator(input_shape=(256, 256, 3),<br>                    output_channels=3,<br>                    dim=64,<br>                    n_downsamplings=2,<br>                    n_blocks=9,<br>                    norm=&#39;instance_norm&#39;):<br>    Norm = _get_norm_layer(norm)</pre><pre>def _residual_block(x):<br>        dim = x.shape[-1]<br>        h = x</pre><pre>h = tf.pad(h, [[0, 0], [1, 1], [1, 1], [0, 0]], mode=&#39;REFLECT&#39;)<br>        h = keras.layers.Conv2D(dim, 3, padding=&#39;valid&#39;, use_bias=False)(h)<br>        h = Norm()(h)<br>        h = tf.nn.relu(h)</pre><pre>h = tf.pad(h, [[0, 0], [1, 1], [1, 1], [0, 0]], mode=&#39;REFLECT&#39;)<br>        h = keras.layers.Conv2D(dim, 3, padding=&#39;valid&#39;, use_bias=False)(h)<br>        h = Norm()(h)</pre><pre>return keras.layers.add([x, h])</pre><pre># 0<br>    h = inputs = keras.Input(shape=input_shape)</pre><pre># 1<br>    h = tf.pad(h, [[0, 0], [3, 3], [3, 3], [0, 0]], mode=&#39;REFLECT&#39;)<br>    h = keras.layers.Conv2D(dim, 7, padding=&#39;valid&#39;, use_bias=False)(h)<br>    h = Norm()(h)<br>    h = tf.nn.relu(h)</pre><pre># 2<br>    for _ in range(n_downsamplings):<br>        dim *= 2<br>        h = keras.layers.Conv2D(dim, 3, strides=2, padding=&#39;same&#39;, use_bias=False)(h)<br>        h = Norm()(h)<br>        h = tf.nn.relu(h)</pre><pre># 3<br>    for _ in range(n_blocks):<br>        h = _residual_block(h)</pre><pre># 4<br>    for _ in range(n_downsamplings):<br>        dim //= 2<br>        h = keras.layers.Conv2DTranspose(dim, 3, strides=2, padding=&#39;same&#39;, use_bias=False)(h)<br>        h = Norm()(h)<br>        h = tf.nn.relu(h)</pre><pre># 5<br>    h = tf.pad(h, [[0, 0], [3, 3], [3, 3], [0, 0]], mode=&#39;REFLECT&#39;)<br>    h = keras.layers.Conv2D(output_channels, 7, padding=&#39;valid&#39;)(h)<br>    h = tf.tanh(h)</pre><pre>return keras.Model(inputs=inputs, outputs=h)</pre><h4>Building the model: Discriminator architecture</h4><p>The discriminator model for Cycle GAN according to the paper is a Patch GAN. A typical classification net would output a 0 or 1 when it gets an image as an input. A patch GAN outputs a grid of values instead. For instance, a 3 by 3 grid could be output instead of a one by one. Each of these values is in the range [0, 1]. If we can see a single value in this grid, it corresponds to seeing a patch in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0jWw_vZo-xoO1h9SkX9kw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*U8OKoLl6umZ4-1duhg6L2w.png" /><figcaption>Discriminator architecture</figcaption></figure><pre>def ConvDiscriminator(input_shape=(256, 256, 3),<br>                      dim=64,<br>                      n_downsamplings=3,<br>                      norm=&#39;instance_norm&#39;):<br>    dim_ = dim<br>    Norm = _get_norm_layer(norm)</pre><pre># 0<br>    h = inputs = keras.Input(shape=input_shape)</pre><pre># 1<br>    h = keras.layers.Conv2D(dim, 4, strides=2, padding=&#39;same&#39;)(h)<br>    h = tf.nn.leaky_relu(h, alpha=0.2)</pre><pre>for _ in range(n_downsamplings - 1):<br>        dim = min(dim * 2, dim_ * 8)<br>        h = keras.layers.Conv2D(dim, 4, strides=2, padding=&#39;same&#39;, use_bias=False)(h)<br>        h = Norm()(h)<br>        h = tf.nn.leaky_relu(h, alpha=0.2)</pre><pre># 2<br>    dim = min(dim * 2, dim_ * 8)<br>    h = keras.layers.Conv2D(dim, 4, strides=1, padding=&#39;same&#39;, use_bias=False)(h)<br>    h = Norm()(h)<br>    h = tf.nn.leaky_relu(h, alpha=0.2)</pre><pre># 3<br>    h = keras.layers.Conv2D(1, 4, strides=1, padding=&#39;same&#39;)(h)</pre><pre>return keras.Model(inputs=inputs, outputs=h)</pre><p>Read more about the patch GAN:</p><p><a href="https://hubert0527.github.io/COCO-GAN/">COCO-GAN: Generation by Parts via Conditional Coordinating</a></p><h4>Initialize the models</h4><p>Cycle GAN has two generators and two discriminators. Generator g for instance takes in a Van Gogh painting as an input and outputs a photo. The generator f takes in a Van Gogh painting and generates a photo.</p><p>Similarly, there are two discriminators used in cycle GANs. Discriminator x takes a photo as input and outputs as real or fake and discriminator y takes a painting as an input and outputs as real or fake.</p><pre>## OUTPUT_CHANNELS = 3 ## Hardcoded in the functions</pre><pre>## Building the Resnet Generator as per the cycle gan paper<br>generator_g = ResnetGenerator()<br>generator_f = ResnetGenerator()</pre><pre>## Building the Discriminator as per the cucle gan paper<br>discriminator_x = ConvDiscriminator()<br>discriminator_y = ConvDiscriminator()</pre><h4>Trying out the generator and the discriminator for the initial generation</h4><pre>to_photo = generator_g(sample_van_gogh)<br>to_van_gogh = generator_f(sample_photo)</pre><pre>## Plot the sample <br>plt.figure(figsize = (8, 8))<br>contrast = 8</pre><pre>imgs = [sample_van_gogh, to_photo, sample_photo, to_van_gogh]<br>title = [&quot;Van Gogh&quot;, &quot;To Photo&quot;, &quot;Photo&quot;, &quot;To Van Gogh&quot;]</pre><pre>for i in range(len(imgs)):<br>  plt.subplot(2, 2, i+1)<br>  plt.title(title[i])<br>  if i % 2 == 0:<br>    plt.imshow(imgs[i][0] * 0.5 + 0.5)<br>  else:<br>    plt.imshow(imgs[i][0] * 0.5 * contrast + 0.5)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rn8nEgpziUMQ-VbY77ndA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6aooOLE28GVkxuu-8RM3g.png" /><figcaption>The generators initial noise map</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCjcIolD0H3BR1O1MxaNUg.png" /></figure><h4>The loss functions</h4><p><strong>Cycle consistency</strong></p><p>In cycle GANs, the generators are trained to reproduce the input image. The image is an input to generator A which outputs a van gogh painting. The painting is then fed into Generator B to reproduce the initial photo. It is similar for van gogh paintings to van gogh painting cycle. The first one might be considered as the foreword cycle consistency and the next the backward cycle consistency. And we can calculate the cycle consistency loss.</p><p><strong>Identity mapping</strong></p><p>In cycle GAN, another important aspect is the identity mapping. If we feed the generator to convert the photo to a van gogh painting, the generator must return the initial painting itself. This is known as identity mapping. As Residual blocks can learn the identity function well, cycle gans use residual blocks as their generator architechture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AN_Jtbp2ddRGMEIf.png" /></figure><p>When we compare the initial photo with the end output in one cycle we get the cycle consistency loss. Similarly, when we compare the initial input with the output in one identity cycle we get the identity loss. Therefore, we get four-loss functions to minimize while training.</p><p>We can write functions to calculate the cycle consistency loss and the identity loss.</p><pre>LAMBDA = 10<br>loss_obj = tf.keras.losses.BinaryCrossentropy(from_logits=True)</pre><pre><br>def discriminator_loss(real, generated):<br>  real_loss = loss_obj(tf.ones_like(real), real)</pre><pre>generated_loss = loss_obj(tf.zeros_like(generated), generated)</pre><pre>total_disc_loss = real_loss + generated_loss</pre><pre>return total_disc_loss * 0.5</pre><pre><br>def generator_loss(generated):<br>  return loss_obj(tf.ones_like(generated), generated)</pre><pre><br>def calc_cycle_loss(real_image, cycled_image):<br>  loss1 = tf.reduce_mean(tf.abs(real_image - cycled_image))</pre><pre>return LAMBDA * loss1</pre><pre><br>def identity_loss(real_image, same_image):<br>  loss = tf.reduce_mean(tf.abs(real_image - same_image))<br>  return LAMBDA * 0.5 * loss</pre><p>Initializing the optimizers:</p><pre>### Initializing the loss functions:<br>generator_g_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)<br>generator_f_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)</pre><pre>discriminator_x_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)<br>discriminator_y_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)</pre><p>The learning rates for the optimizers are as stated in the paper.</p><h4>Training:</h4><p>We can write a function to generate images while the GAN trains to monitor the results.</p><pre>def generate_images(model, test_input):<br>  prediction = model(test_input)</pre><pre>plt.figure(figsize=(12, 12))</pre><pre>display_list = [test_input[0], prediction[0]]<br>  title = [&#39;Input Image&#39;, &#39;Predicted Image&#39;]</pre><pre>for i in range(2):<br>    plt.subplot(1, 2, i+1)<br>    plt.title(title[i])<br>    # getting the pixel values between [0, 1] to plot it.<br>    plt.imshow(display_list[i] * 0.5 + 0.5)<br>    plt.axis(&#39;off&#39;)<br>  plt.show()</pre><p>Write a function for each training step.</p><pre><a href="http://twitter.com/tf">@tf</a>.function<br>def train_step(real_x, real_y):<br>  # persistent is set to True because the tape is used more than<br>  # once to calculate the gradients.<br>  with tf.GradientTape(persistent=True) as tape:<br>    # Generator G translates X -&gt; Y<br>    # Generator F translates Y -&gt; X.</pre><pre>fake_y = generator_g(real_x, training=True)<br>    cycled_x = generator_f(fake_y, training=True)</pre><pre>fake_x = generator_f(real_y, training=True)<br>    cycled_y = generator_g(fake_x, training=True)</pre><pre># same_x and same_y are used for identity loss.<br>    same_x = generator_f(real_x, training=True)<br>    same_y = generator_g(real_y, training=True)</pre><pre>disc_real_x = discriminator_x(real_x, training=True)<br>    disc_real_y = discriminator_y(real_y, training=True)</pre><pre>disc_fake_x = discriminator_x(fake_x, training=True)<br>    disc_fake_y = discriminator_y(fake_y, training=True)</pre><pre># calculate the loss<br>    gen_g_loss = generator_loss(disc_fake_y)<br>    gen_f_loss = generator_loss(disc_fake_x)</pre><pre>total_cycle_loss = calc_cycle_loss(real_x, cycled_x) + calc_cycle_loss(real_y, cycled_y)</pre><pre># Total generator loss = adversarial loss + cycle loss<br>    total_gen_g_loss = gen_g_loss + total_cycle_loss + identity_loss(real_y, same_y)<br>    total_gen_f_loss = gen_f_loss + total_cycle_loss + identity_loss(real_x, same_x)</pre><pre>disc_x_loss = discriminator_loss(disc_real_x, disc_fake_x)<br>    disc_y_loss = discriminator_loss(disc_real_y, disc_fake_y)</pre><pre># Calculate the gradients for generator and discriminator<br>  generator_g_gradients = tape.gradient(total_gen_g_loss, <br>                                        generator_g.trainable_variables)<br>  generator_f_gradients = tape.gradient(total_gen_f_loss, <br>                                        generator_f.trainable_variables)</pre><pre>discriminator_x_gradients = tape.gradient(disc_x_loss, <br>                                            discriminator_x.trainable_variables)<br>  discriminator_y_gradients = tape.gradient(disc_y_loss, <br>                                            discriminator_y.trainable_variables)</pre><pre># Apply the gradients to the optimizer<br>  generator_g_optimizer.apply_gradients(zip(generator_g_gradients, <br>                                            generator_g.trainable_variables))</pre><pre>generator_f_optimizer.apply_gradients(zip(generator_f_gradients, <br>                                            generator_f.trainable_variables))</pre><pre>discriminator_x_optimizer.apply_gradients(zip(discriminator_x_gradients,<br>                                                discriminator_x.trainable_variables))</pre><pre>discriminator_y_optimizer.apply_gradients(zip(discriminator_y_gradients,<br>                                                discriminator_y.trainable_variables))</pre><p>The training loop:</p><pre>for epoch in range(EPOCHS):<br>  start = time.time()</pre><pre>n = 0<br>  for image_x, image_y in tf.data.Dataset.zip((train_van_gogh, train_photo)):<br>    train_step(image_x, image_y)<br>    if n % 10 == 0:<br>      print (&#39;.&#39;, end=&#39;&#39;)<br>    n += 1</pre><pre>clear_output(wait=True)<br>  # Using a consistent image (sample_horse) so that the progress of the model<br>  # is clearly visible.<br>  generate_images(generator_g, sample_van_gogh)</pre><pre>if (epoch + 1) % 5 == 0:<br>    ckpt_save_path = ckpt_manager.save()<br>    print (&#39;Saving checkpoint for epoch {} at {}&#39;.format(epoch+1,<br>                                                         ckpt_save_path))</pre><pre>print (&#39;Time taken for epoch {} is {} sec\n&#39;.format(epoch + 1,<br>                                                      time.time()-start))</pre><h4>Results</h4><p>We can view the results by generating on the test dataset:</p><pre>for inp in test_photo.take(15):<br>  generate_images(generator_van_gogh, inp)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EEJHMhkTCmXKNtV3zOMUbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pi8fsKhsHGp6akWivogLog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hIlRumI5lUjUFuMYJRVbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2Rf1PwKTu2HgSrYJVa5vw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EffWajTqNF8DAs7iIbyyag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBqY37kA8YoUDspdrgGitw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJmPMlWowncckd4LVJGtSg.png" /><figcaption>Results on the test dataset.</figcaption></figure><p>From the results, it is seen that the GAN replicates patterns from Van Gogh’s art. The turbulence patterns from Van Gogh’s original arts are seen in the generated paintings.</p><p>I used the model to generate photos of my campus and any other custom image. In order to predict custom images, some preprocessing is required. The preprocessing functions are written down below:</p><pre>def preprocess_custom_image(image):<br>  image = tf.image.resize(image, [256, 256],<br>                          method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)<br>  return image</pre><p>This function resizes the image to the input dimension. (256, 256)</p><pre>def preprocess_and_predict_in_dir(model, dir_name):<br>  b = 0<br>  for a in os.listdir(dir_name):<br>    image_to_be_read = dir_name + &quot;/&quot; + a<br>    img = plt.imread(image_to_be_read)<br>    preprocessed_image = preprocess_custom_image(img)<br>    preprocessed_image = tf.cast(preprocessed_image, dtype = tf.float32)<br>    preprocessed_image = (preprocessed_image/127.5) - 1<br>    preprocessed_image = preprocessed_image[tf.newaxis, ...]<br>    prediction = model(preprocessed_image)<br>    generated_img = keras.preprocessing.image.array_to_img(prediction[0])<br>    generated_img.save(f&quot;/content/generated_dtu_images/g{a}.jpg&quot;)<br>    b = b + 1</pre><p>The function above further preprocesses the image and predicts it on the custom directory. The predictions are then saved into a directory “generated_dtu_images” in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*YzEZiJC1ejD9GiDnK9dA0w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*xd9cJviyuYgsnBZwOTVwBQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*4aCn3tsTErs92wf_5orNZA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*F5UJuI5utFDWAb-3Lmp6UA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*Aw-NUvlYSUAIrbYL4SyO7Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*ptLCXbE4pl7lgkSaWRgXeA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*IiB12F579BcBDvvL2Eg6Wg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*8txGgBi1dmM-zbENxS8WGw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*OR9CWrp_RjYsAQkacXfpJA.jpeg" /></figure><h3>Social Media Links:</h3><p>LinkedIn:</p><p><a href="https://www.linkedin.com/in/atul-ranjan-83025622a/">Atul Ranjan - Delhi Technological University (Formerly DCE) - Kathmandu, Bāgmatī, Nepal | LinkedIn</a></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on</em><strong><em> </em></strong><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d578b11edf6" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/cycle-gans-generating-paintings-of-my-campus-in-van-goghs-style-9d578b11edf6">Cycle GANs: Generating Paintings of My Campus in Van Gogh’s Painting Style</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning in Medicine: Identifying Pneumonia from a Chest-X-Ray]]></title>
            <link>https://python.plainenglish.io/deep-learning-in-medicine-identifying-pneumonia-from-a-chest-x-ray-6d1aabe68b01?source=rss-f37e22283ec6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d1aabe68b01</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-neural-net]]></category>
            <category><![CDATA[machine-leanring]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Atul Ranjan]]></dc:creator>
            <pubDate>Mon, 07 Feb 2022 20:49:31 GMT</pubDate>
            <atom:updated>2022-02-28T05:50:18.205Z</atom:updated>
            <content:encoded><![CDATA[<h4>How I used Deep Learning to identify Pneumonia from a chest X-Ray.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8W4Z5fU19ti1QcEz.png" /></figure><p>Along these years in the progress of Deep Learning and Artificial Intelligence, Deep Learning has found some interesting applications. One field of study, showing great potential in medicine and medical research, with Deep Learning systems in use in DNA analysis, interpretation of Medical Scans(X-Ray, CT-SCAN, MRI), analysis of Health Data and predicting diseases, etc.</p><p>The potential of Deep Neural Networks in Medicine is because of their excellence in recognizing patterns. In this article, I’ll be explaining how I used Deep Learning to identify Pneumonia from a chest X-Ray, using the pre-trained EfficientNetB1, and fine-tuning it.</p><h3>Preparing and Preprocessing the Data</h3><h4>Getting Data for the Model</h4><p>For this implementation, I used Kaggle’s dataset “<em>Chest X-Ray Images (Pneumonia)</em>”, to train the model. The Dataset contains 5,863 images in two categories: “<em>Normal</em>”, <em>and </em>“Pneumonia”.</p><p><a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">Chest X-Ray Images (Pneumonia)</a></p><h4>Splitting the Data into train, test, and validation sets</h4><p>Splitting the data to train, test, and validate sets is a very important part of Machine Learning. Our model cannot be evaluated on the same data, it has trained on, and hence, needs to be tested on data it has never seen before.</p><p><strong>Why is it important to evaluate the model on data it has never seen before?</strong></p><p>Evaluating the model, on data it has never seen before is crucial to identify <em>overfitting</em>. Sometimes, the deep learning model just recognizes the training data a bit too well and fails to generalize on new data. This is called <em>overfitting.</em></p><p>An interesting analogy to understand overfitting might be a school test. The contents for the test may be considered as training data. If you memorize the contents very well, without actually understanding it, you are overfitting. When you have learnt in such a way, you can only answer questions that are completely similar to the contents you have studied, and when asked any new questions, you will fail to answer them correctly. Instead, you want to <em>understand </em>the contents well so you can answer any similar question on the test. In Machine Learning terminology, this is called generalization.</p><p>In other words, you need your model to generalize well on new data.</p><h4>Inspecting the Data:</h4><p>Training a model is much easier if you know what data you are dealing with, therefore, it is very important to inspect the data, and visualize it. We can do this by writing a simple function in python to fetch a random image from the directory.</p><p>After downloading the data from Kaggle, we can specify the directories and store it in variables as follows:</p><pre>## Setting up the directories<br>train_dir = “/content/chest_xray/train/”<br>test_dir = “/content/chest_xray/test/”<br>validation_dir = “/content/chest_xray/val/”</pre><p>Setting up a function to take an image from the directory and plotting it:</p><pre>import matplotlib.pyplot as plt<br>import matplotlib.image as mpimg<br>import random<br>import os</pre><pre>def view_random_image(target_dir, target_class):<br>  # Setup target directory (we’ll view images from here)<br>  target_folder = target_dir+target_class</pre><pre>  # Get a random image path<br>  random_image = random.sample(os.listdir(target_folder), 1)</pre><pre>  # Read in the image and plot it using matplotlib<br>  img = mpimg.imread(target_folder + “/” + random_image[0])<br>  plt.imshow(img, cmap = “gray”)<br>  plt.title(target_class)<br>  plt.axis(“off”);<br>  print(f”Image shape: {img.shape}”) # show the shape of the image</pre><pre>  return img</pre><p>This function returns takes an image from the target directory of a targeted class and plots it. When called, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMusoGAUfFuA5o_VfunJfQ.png" /></figure><h4>How are images represented?</h4><p>Neural Networks are nothing but matrices of weights, which it learns over time. Therefore, for a Neural Net to learn, the data fed to it must be numbers, The data we feed into the network must be numerically encoded in some way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*eSj0uVZ_I8ySnMIz.png" /><figcaption>A basic mathematical process of Artificial Neural Networks</figcaption></figure><p>Images are represented as tensors with each pixel having one value of how bright it is, and in the case of colored pictures, a matrix dimension 1x3 for the color channel. We have to make sure our tensors are of the right shape for our model to train.</p><pre>Inspecting the image:<br>for images, labels in train_data.take(1):<br>  print(images, labels)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*4p_bXOQLILSuTi5kHQgMvQ.png" /><figcaption>Part of an Image Tensor</figcaption></figure><p>Labels similarly are matrices having value 0 or 1 for <em>“Normal” or “Pneumonia” </em>as this deep learning problem is a binary classification.</p><h4>Storing the data as TensorFlow Batch Datasets</h4><p>Now finally, we can store the data as TensorFlow batch datasets. Converting the data to batches (usually of size 32) is very helpful as it speeds up computation:</p><pre>## Setting up the data</pre><pre>## Set the image size<br>IMG_SIZE = (224, 224)</pre><pre>print(&quot;Training Images:&quot;)<br>train_data=tf.keras.preprocessing.image_dataset_from_directory(<br>directory = train_dir,<br>image_size = IMG_SIZE,<br>label_mode = &quot;binary&quot;,<br>color_mode = &quot;grayscale&quot;,<br>batch_size = 32)</pre><pre>print(&quot;Testing Images:&quot;)<br>test_data=tf.keras.preprocessing.image_dataset_from_directory(<br>direcory = test_dir,<br>image_size = IMG_SIZE,<br>label_mode = &quot;binary&quot;,<br>color_mode = &quot;grayscale&quot;,<br>batch_size = 32)</pre><pre>print(&quot;Validation Images:&quot;)<br>val_data=tf.keras.preprocessing.image_dataset_from_directory(<br>directory = validation_dir,<br>image_size = IMG_SIZE,<br>label_mode = &quot;binary&quot;,<br>color_mode = &quot;grayscale&quot;,<br>batch_size = 32)</pre><p>With this, we have successfully prepared and preprocessed our data for our model to train on.</p><h3>Choosing the right model and model architecture</h3><p>Choosing the right model for your problem is key to solving Deep Learning Problems. As this is an image classification problem, Convolutional Neural Networks was the first Deep Neural Nets that came to my mind.</p><p><strong>Why Convolutional Neural Nets might be the better choice?</strong></p><p>While identifying pneumonia in a patient’s X-Ray, doctors usually look for white spots in the lungs, called infiltrates. Convolutional Neural Networks work best for identifying features in an image. The layers closer to the inputs in a CNN may identify larger features while the layers closer to the output may identify more detailed features. They do this by sliding a filter matrix of weights (<em>learned across training</em>) through the image matrix and checking if the image has a certain filter. Hence, our Neural network may look for white spots or infiltrates in the lungs and identify them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5yrk9YhjdfP1PM3L" /></figure><h3>Building the Model</h3><h4>Setting up the Data Augmentation Layer</h4><p><strong>What is Data Augmentation?</strong></p><p>Data Augmentation is a technique in data science to create more data or more features to learn by modifying the features in the data. Changing the orientation of the image, rotating it, etc. can make it trickier for our model to learn resulting in our model generalizing to the data better. For example, you can solve harder questions while practicing for the test, which will make you better prepared for it.</p><p>A Data Augmentation Layer can be set up easily in TensorFlow with Keras Sequential Models.</p><pre>from tensorflow import keras<br>from tensorflow.keras import layers<br>from tensorflow.keras.layers.experimental import preprocessing</pre><pre># Create a data augmentation stage with horizontal flipping, rotations, zooms</pre><pre>data_augmentation = keras.Sequential([<br>preprocessing.RandomFlip(&quot;horizontal&quot;),<br>preprocessing.RandomRotation(0.2),<br>preprocessing.RandomZoom(0.2),<br>preprocessing.RandomHeight(0.2),<br>preprocessing.RandomWidth(0.2),<br>##preprocessing.Rescaling(1./255) # keep for ResNet50V2, remove for EfficientNetB0<br>], name =&quot;data_augmentation&quot;)</pre><h4>Setting up the Base Model</h4><p>Due to a very positive open-source culture in the deep learning community, there have been various pre-trained models available for our use in experiments. These models have been trained with a large number of data and the learned weights can be used to generalize our problem. This is known as <em>transfer learning. </em>For Image Classification, the most popular ones are ResNet, VGG, and EfficientNet.</p><p>Prior to coming up with my solution and best working model I experimented on all three of these pre-trained neural nets and found that EfficientNet performed the best. ResNet and VGG failed to generalize on the dataset. <em>i.e, even though they had a very high training accuracy, the validation accuracy was poor</em></p><p><strong>Why ResNet and VGG might have not worked as well.</strong></p><p>ResNet requires a large dataset to perform well, and as this dataset of 5,800 images is quite average on a deep learning scale, and hence, ResNet might not have worked. It is also possible that the data augmentation we carried out might not have been suitable for ResNet. There can be many more reasons for the poor performance of ResNet and VGG in this case.</p><p>As the other models did not work out too well I used EfficientNetB1 as the base model.</p><pre>## Using the model EfficientNetB1 for the first experiment with all the layers trainable</pre><pre>base_model = tf.keras.applications.EfficientNetB1(include_top = False)<br>base_model.trainable = True</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rimPKQIs610WcwnS.png" /><figcaption>Architecture of EfficientNet</figcaption></figure><p>In this case, we have set all the layers in the base model to trainable as we want it to adapt to our dataset, which is quite different from the dataset it has previously trained on (ImageNet)</p><h4>Creating and compiling the Model</h4><p>We can then create the model using the Keras Functional API and compile it.</p><pre>## Creating the model <br>inputs = tf.keras.layers.Input(shape = (224, 224, 1), name = &quot;Input_Layer&quot;)<br>#x = tf.keras.layers.experimental.preprocessing.Rescaling(1./255)(inputs)<br>x = data_augmentation(inputs)<br>x = tf.keras.layers.Conv2D(3,(3,3),padding=&#39;same&#39;)(x)<br>x = base_model(x)<br>x = tf.keras.layers.GlobalMaxPooling2D(name = &quot;global_max&quot;)(x)<br>outputs = tf.keras.layers.Dense(1, activation = &quot;sigmoid&quot;)(x)<br>model_0 = tf.keras.Model(inputs, outputs)</pre><pre>## Compiling the model<br>model_0.compile(loss=tf.keras.losses.BinaryCrossentropy(),<br>              optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),<br>              metrics=[&quot;accuracy&quot;])</pre><p>Notice that I have set the learning rate of the Adam optimizer to 0.0001 which is 10 times lower than the default. This is because we are using transfer learning and we generally want a lower learning rate. We will also be setting up callbacks which further reduces the learning rate for our model to converge better.</p><p>Also, note that I have used a convolution layer before the base model. This is because EfficientNet has been trained on colored images, and our data is in greyscale, meaning our image tensor has 1 channel instead of 3. The Convolution Layer makes sure that the tensors are of the right shape when it is fed into the EfficientNet model.</p><h4>Setting up Callbacks</h4><p>While training a Deep Learning Model we do not know how long the model is going to train for. It can go up to several hours, and sometimes even days. We can set up callbacks so that our model stops when the validation loss plateaus, or when our model has stopped learning. This callback is known as <em>early stopping. </em>We can also set up callbacks to adjust the learning_rate after epochs for our model to converge better.</p><pre>## Setting up callbacks<br># Setup EarlyStopping callback to stop training if model&#39;s val_loss doesn&#39;t improve for 3 epochs<br>early_stopping=tf.keras.callbacks.EarlyStopping(monitor=&quot;val_loss&quot;, <br>                                                patience=3) # if val loss decreases for 3 epochs in a row, stop training</pre><pre># Creating learning rate reduction callback<br>reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor=&quot;val_loss&quot;,  <br>                                                 factor=0.25, # multiply the learning rate by 0.2 (reduce by 4x)<br>                                                 patience=2,<br>                                                 verbose=1, # print out when learning rate goes down <br>                                                 min_lr=1e-7)</pre><h4>Fitting the Model</h4><p>Finally, we can fit the model to our train data and watch it train.</p><pre>history_0 = model_0.fit(train_data,<br>                        epochs = 100,<br>                        steps_per_epoch = len(train_data),<br>                        validation_data = test_data,<br>                        validation_steps = int(0.25*len(test_data)),<br>                        callbacks = [early_stopping, reduce_lr])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSw-xOkWm5PFvf8Z1n_Z5A.png" /></figure><h3>Evaluating the Model</h3><p>Now, that the model has been trained we can evaluate the model on the test data and the validation data.</p><pre>## Evaluating the model on 100% of the test data<br>model_0.evaluate(test_data)<br>model_0.evaluate(val_data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLX6nsMdIvo-j8HCVej6Iw.png" /></figure><p>We can further evaluate the model with various other metrics but I won’t be covering that in this article.</p><h3>Results</h3><p>With this, we get a training accuracy of 97 percent and a test accuracy of 86.5% which is decent. With this model, now we can feed it greyscale images of Chest-X-Rays and it can make a decent prediction of if the patient has pneumonia or not, although some preprocessing is required.</p><h3>Links and Social Media:</h3><p>Find the Python Notebook and the code in GitHub:</p><p><a href="https://github.com/Atul-Ranjan12/Kaggle-Chest_X-Ray-Pneumonia-Model/blob/main/Chest_X_Ray_final.ipynb">Kaggle-Chest_X-Ray-Pneumonia-Model/Chest_X_Ray_final.ipynb at main · Atul-Ranjan12/Kaggle-Chest_X-Ray-Pneumonia-Model</a></p><p>LinkedIn Profile:</p><p><a href="https://www.linkedin.com/in/atul-ranjan-83025622a/">Atul Ranjan - Delhi Technological University (Formerly DCE) - Kathmandu, Bāgmatī, Nepal | LinkedIn</a></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d1aabe68b01" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/deep-learning-in-medicine-identifying-pneumonia-from-a-chest-x-ray-6d1aabe68b01">Deep Learning in Medicine: Identifying Pneumonia from a Chest-X-Ray</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convolutional Neural Networks (CNNs) for Computer Vision - Image Classification]]></title>
            <link>https://python.plainenglish.io/convolutional-neural-networks-cnns-for-computer-vision-image-classification-412dc8f67a4?source=rss-f37e22283ec6------2</link>
            <guid isPermaLink="false">https://medium.com/p/412dc8f67a4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Atul Ranjan]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 21:01:23 GMT</pubDate>
            <atom:updated>2022-02-14T05:44:08.542Z</atom:updated>
            <content:encoded><![CDATA[<h4>A deep dive into Convolutional Neural Networks for Computer Vision</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEqmrCFhgpgyUQRDlZ9uZA.jpeg" /></figure><p>Artificial Intelligence, is without a doubt one of the most discussed and fastest-growing fields today. Knowingly or unknowingly almost everyone is using one application of AI on a day-to-day basis, as recommender systems in social media applications, Google’s search suggestions, a smartphone camera, etc. Although it might seem intimidating at first glance, the fundamentals that make AI at its core and how computers can learn on their own on levels a human brain cannot perceive is nothing short of fascinating.</p><p>An interesting area of Artificial Intelligence is Deep Learning and Computer Vision. <em>Deep Learning is a subset of AI and is based on Artificial Neural Networks that use multiple layers to progressively extract higher-level features from raw input. </em>Computer Vision is an application of Deep Learning where these neural networks extract features from images or videos. Although many algorithms have proved quite efficient for Computer Vision, Convolutional Neural Networks or CNNs have been one of the if not the most efficient approaches to the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*qK2F0QsBQb2CIfVYXrUefA.png" /><figcaption>Subsets of AI</figcaption></figure><h3>What are Convolutional Neural Networks (CNNs)?</h3><p>CNNs are Neural Networks that consist of Convolution Layers to extract features of an image or video data, layer by layer in order to make up more distinct features. In a CNN, the convolution layers closer to the inputs identify larger features, and the closer the layers get to the output, the more detailed features they capture.</p><p>For example in the image classification problem below, where a CNN is used to identify handwritten digits, the layers closer to the inputs may identify strokes and loops used while writing a digit, while the layers are closer to the output identify the various parts that make up a stroke or a loop. <em>However, it is to be noted that we do not specify what a neural network learns, the network figures it out by itself.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*t4zdXapy54_tqvM_UIBIgg.png" /><figcaption>The problem for handwritten digit classification.</figcaption></figure><h3>How Convolution Layers work</h3><p>A layer in a neural network consists of units called neurons, each layer can have any amount of desired neurons. These neurons consist of individual weights, a bias, and in most cases, an activation function that they randomly set and tune over time. The process of tuning these values is what is known as neural network learning. A convolution layer is a layer in a neural net that performs a convolution operation. These convolution operations help a neural net identify features in an image.</p><h4>What is a convolution operation?</h4><p>Suppose you have a 28x28 image of a handwritten digit. In this case, it isn’t necessary for every handwritten digit to be identical pixel-wise to another handwritten digit even if it is the same, and hence pixel-wise comparisons cannot be carried out.</p><p>CNNs use patches to rather compare the features of a section of an image to another section. They compare these by performing a convolution operation, where the patch matrix is element-wise multiplied to the filter matrix of learned weights, and then the matrix formed by the multiplication is added to produce an output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0MBAtDpA7sRBGa6L2erqQ.png" /><figcaption>The Convolution Operation</figcaption></figure><p>Here, the filter and the patch are matrices of dimensions 3x3. As they are completely identical, the convolution operation results in a 9 as the final output.</p><h3>Implementing a CNN to classify 101 different Food Items</h3><p>Now that, we have gone through what a CNN is, let us go through a simple implementation of a CNN to identify different food items. For this implementation, I used <em>TensorFlow Keras </em>api. TensorFlow Keras handles most of the computations and implementations for us very efficiently so we can only focus on the problem itself.</p><h4>Step 1: Preparing the Data</h4><p>The most important step for any Deep Learning Problem is preparing the data for our model to learn. By preparing the data, in this case, I mean turning our data into tensors. For this problem, I used the inbuilt food 101 data set in TensorFlow.</p><pre>## Get the tensorflow datasets<br>import tensorflow_datasets as tfds</pre><pre>datasets_list = tfds.list_builders() ## Get all the datasets in TFDS<br>print(&quot;food101&quot; in datasets_list) ## If the Food 101 is in the datasetslist</pre><pre>## Downloading the data</pre><pre>(train_data, test_data), ds_info = tfds.load(name = &quot;food101&quot;,split = [&quot;train&quot;, &quot;validation&quot;], ## Splits the data in train and test sets<br>shuffle_files = True, ## Shuffles the files when downloading<br>as_supervised = True, ## Data gets returned in tuple format (data, label)<br>with_info = True) ## Downloads the metadata as well</pre><p>Images here are represented as matrices of pixel values. These pixel values usually range from 0 to 255, 0 being the darkest. Although we can feed these to the neural network, neural networks perform better when the inputs they receive range from 0 to 1. The process of converting these values to the range of 0 to 1 is known as <em>normalization. </em>They can be done by taking a value and dividing it by the maximum value (255 in this case). So if the image is a tensor with values ranging from 0 to 255. A simple operation image/255. will normalize the input.</p><p>In this implementation, however, I am using a pre-trained neural network EfficientNetB7, which normalizes the image for us.</p><pre>## Take one sample of the trained Data</pre><pre>train_one_sample = train_data.take(1) ## Takes one sample from train_data ## They are in format (image_tensor, label)</pre><pre>for image, label in train_one_sample:<br>  print(f&quot;Image shape: {image.shape} Image dtype: {image.dtype} Target class from food 101: {label} class name: {class_names[label.numpy()]}&quot;)</pre><pre>## Plot the image from tensorflow datasets<br>plt.imshow(image)<br>plt.axis(False)<br>plt.title(class_names[label.numpy()])</pre><p>We can plot the image for visualization purposes by using the code as above:</p><p>The images are also separated into batches (commonly of size 32) for computational efficiency.</p><h4>Step 2: Preprocessing the image</h4><p>We can create a simple function to resize the image to the desired size, (224, 224) is common image size. We can also convert the data type to float for our model.</p><pre>## Creating a preprocessing function to feed it into the model</pre><pre>def preprocess_img(image, label, img_shape = 224):<br> “””<br> Converts the data type from uint8 to float32 and reshapes the image to [img_shape, img_shape, color_channels]<br> “””<br> image = tf.image.resize(image, [img_shape, img_shape]) ## reshapes to img_shape<br> return tf.cast(image, tf.float32), label ## Return the preprocessed image</pre><h4>Step 3: Creating Training and Validation sets</h4><p>The data is usually split into training and validation steps for proper evaluation of the model. This ensures the model validates on data it has never seen before, hence avoiding the problem of overfitting.</p><pre>## Batching and preprocessing the datasets to run fast</pre><pre>## Map preprocessing function to training data and paralellize <br>train_data = train_data.map(map_func = preprocess_img, num_parallel_calls = tf.data.AUTOTUNE) ## Autotune the number of processors the GPU use<br>## Shuffle the train_data and turn it into batches and prefetch it (load it faster)<br>train_data = train_data.shuffle(buffer_size = 1000).batch(batch_size = 32).prefetch(buffer_size = tf.data.AUTOTUNE)</pre><pre>## Map preprocessing funtion to the test_data<br>test_data = test_data.map(map_func = preprocess_img, num_parallel_calls = tf.data.AUTOTUNE)<br>## Turn test data to batches<br>test_data = test_data.batch(batch_size = 32).prefetch(buffer_size = tf.data.AUTOTUNE)</pre><h4>Step 4: Setting up Callbacks</h4><p>Callbacks are set to ensure to ease our experimentation process and for evaluation of our model. These callbacks run after every epoch and save the model data to the specified path.</p><pre>## Setting up the Model Checkpoint Callback <br>checkpoint_path = “model_checkpoint/cp.ckpt”<br>model_checkpoint = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, <br> monitor = “val_acc”, <br> save_weights_only = True, <br> verbose = 0)</pre><pre>## Setting up the early stopping callback <br>early_stopping = tf.keras.callbacks.EarlyStopping(monitor = &quot;val_loss&quot;, patience = 3)</pre><pre>checkpoint_path = &quot;fine_tune_checkpoints/&quot;<br>model_checkpoint = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,                                                      monitor=&quot;val_loss&quot;)</pre><pre>## Setting up the reduce on Plateu callback <br>reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor = &quot;val_loss&quot;,<br> factor = 0.2, ## Multiply the learning rate by 0.2<br> patience = 2, <br> verbose = 1,<br> min_lr = 1e-7)</pre><h4>Step 5: Building a model</h4><p>Finally, with all the data ready and preprocessed, the callbacks set, we are ready to build the model. I used the Keras functional API to make the model and used EfficientNetB7 as the base model to fine-tune on.</p><pre>## Building a feature extraction model <br>from tensorflow.keras import layers</pre><pre>## Setting up a base model <br>INPUT_SHAPE = (224, 224, 3)<br>base_model = tf.keras.applications.EfficientNetB7(include_top = False)<br>base_model.trainable = False</pre><pre>inputs = layers.Input(shape = INPUT_SHAPE, name = “input_layer”)<br>x = base_model(inputs, training = False)<br>x = layers.GlobalAveragePooling2D(name = “pooling_layer”)(x)<br>x = layers.Dense(len(class_names))(x)<br>outputs = layers.Activation(“softmax”, dtype = tf.float32)(x) ## Mixed Precision requires data types to be in float 32<br>model = tf.keras.Model(inputs, outputs)</pre><pre>## Compiling the model<br>model.compile(<br> loss = tf.keras.losses.SparseCategoricalCrossentropy(),<br> optimizer = tf.keras.optimizers.Adam(),<br> metrics = [“accuracy”]<br>)</pre><p>The code above is for a feature extraction model, it can be used to initially train and save the weights as checkpoints. The model can then be cloned and the weights can be loaded into the model. Then the trainable layers in the model can be set to the desired amount by simply looping over the model and setting the trainable parameter to true.</p><pre>## Clone the model for fine tuning <br>model_2 = tf.keras.models.clone_model(model)<br>## Load the weights to our cloned model<br>model_2.load_weights(checkpoint_path)</pre><pre>## Compile the model before going further since we used it again <br>model_2.compile(<br> loss = tf.keras.losses.SparseCategoricalCrossentropy(),<br> optimizer = tf.keras.optimizers.Adam(),<br> metrics = [“accuracy”]<br>)</pre><pre>## Set all the layers in the EfficientNet Base Model to trainable <br>for layer in model_2.layers[1].layers:<br> layer.trainable = True</pre><p>In this case, all the layers in the base model have been set to trainable. Now the model is ready to fit data.</p><h4>Step 6: Fitting Data</h4><p>Finally, we can fit the training and test data into our model and watch it train. The training process can be made efficient with TensorFlow’s mixed-precision training where it utilizes the multiple CPUs, I have not gone through those in this article.</p><pre>history= model_2.fit(train_data,<br> epochs=100, # fine-tune for a maximum of 100 epochs<br> steps_per_epoch=len(train_data),<br> validation_data=test_data,<br> validation_steps=int(0.15 * len(test_data)), # validation during training on 15% of test data<br> callbacks=[create_tensorboard_callback(“training_logs”, “efficientb0_101_classes_all_data_fine_tuning”), # track the model training logs<br> model_checkpoint, # save only the best model during training<br> early_stopping, # stop model after X epochs of no improvements<br> reduce_lr])</pre><p>The model will now fit and validate itself with the test dataset. There can be many ways to improve this model, I was able to achieve 99 percent training accuracy and about 83 percent validation accuracy with about 3 hours of training.</p><h4>Step 7: Predicting custom images</h4><p>Our model is now ready to make predictions on custom images when we feed them to the model. We can write a simple function to load and prepare the images and make predictions on them.</p><p>## Function to load and prepare images:</p><pre>def load_and_prepare_image(filename, img_shape = 224, scale = True):<br> “”””<br> Reads in an image from filename, turns it into a tensor and reshapes into a <br> specified shape <br> “””<br> ## Read the image <br> img = tf.io.read_file(filename)<br> <br> ## Decode image into tensor <br> img = tf.io.decode_image(img, channels = 3)</pre><pre>## Resize the image <br> img = tf.image.resize(img, [img_shape, img_shape])</pre><pre>## Scale the image <br> if scale:<br> ## Rescale the image <br> return img/255.<br> else:<br> return img ## Efficient models in tensorflow rescale the images already</pre><p>We can now plot images and make predictions on it:</p><pre>## Visualize the images and target Label <br>## Finding out wheere the model is right or wrong</pre><pre>import os <br>import random</pre><pre>plt.figure(figsize = (17, 10))<br>for i in range(3):<br> ## Choose a random image from a random class<br> class_name = random.choice(class_names)<br> filename = random.choice(os.listdir(test_dir + “/” + class_name))<br> filepath = test_dir + “/” + class_name + “/” + filename<br> <br> ## Load the mage and make prediction <br> img = load_and_prepare_image(filepath, scale = False)<br> pred_prob = model.predict(tf.expand_dims(img, axis = 0))<br> pred_class = class_names[pred_prob.argmax()]</pre><pre>## Plot the image <br> plt.subplot(1, 3, i+1)<br> plt.imshow(img/255.)<br> if (class_name == pred_class):<br> title_color = “g”<br> else: <br> title_color = “r”</pre><pre>plt.title(f”Actual: {class_name}, pred: {pred_class} prob: {pred_prob.max():.2f}”, c = title_color)<br> plt.axis(False)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IL0y9_fChb3KvMNp_L1gsw.png" /><figcaption>Predictions of food items made by the model.</figcaption></figure><h4>Step 8: Further Evaluating the model</h4><p>We can further evaluate the model by making a confusion matrix or using other evaluation metrics to see where our model is making mistakes.</p><h3>External Links and resources</h3><p>Through this article, I briefly tried to explain CNNs and their implementation, for more resources please visit:</p><p><a href="https://poloclub.github.io/cnn-explainer/">CNN Explainer</a></p><h3>Social media:</h3><p>LinkedIn:</p><p><a href="https://www.linkedin.com/in/atul-ranjan-83025622a?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BGqkghVirTsqhZyDwFHL%2Frw%3D%3D">Atul Ranjan - Delhi Technological University (Formerly DCE) - Kathmandu, Bāgmatī, Nepal | LinkedIn</a></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=412dc8f67a4" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/convolutional-neural-networks-cnns-for-computer-vision-image-classification-412dc8f67a4">Convolutional Neural Networks (CNNs) for Computer Vision - Image Classification</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>