<?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 Prabhat M on Medium]]></title>
        <description><![CDATA[Stories by Prabhat M on Medium]]></description>
        <link>https://medium.com/@prabhatm27?source=rss-f0451664d8fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ovTSYn6naRhyayqTv6ilzw.jpeg</url>
            <title>Stories by Prabhat M on Medium</title>
            <link>https://medium.com/@prabhatm27?source=rss-f0451664d8fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:08:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prabhatm27/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 Physics of Failure: Measuring Drawdown & Recovery in Formula 1]]></title>
            <link>https://prabhatm27.medium.com/the-physics-of-failure-measuring-drawdown-recovery-in-formula-1-02a67c73ff13?source=rss-f0451664d8fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/02a67c73ff13</guid>
            <dc:creator><![CDATA[Prabhat M]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 16:30:21 GMT</pubDate>
            <atom:updated>2026-05-14T05:05:16.540Z</atom:updated>
            <content:encoded><![CDATA[<h3>#5 in the Quant × Sports Series — Where Markets Meet Motorsport</h3><p>This is part of the <strong>Quant × Sports Series</strong>.<br>Read Part 4→ The Alpha of a Driver: Separating Skill from Machinery in Formula 1</p><p>Beyond the Results Table (<a href="https://medium.com/@prabhatm27/the-alpha-of-a-driver-separating-skill-from-machinery-in-formula-1-ebe0f9c099dd">link</a>)</p><p>Speed wins headlines.<br>Efficiency wins races.</p><p>But championships are decided somewhere else entirely.</p><p>They’re decided in the laps <em>after something goes wrong</em>.</p><p>A lock-up.<br>A bad pit call.<br>Traffic at the wrong time.<br>A Safety Car that rewrites the race.</p><p>Every Formula 1 race contains failure. The difference between a race winner and a midfield finisher is rarely whether disruption occurs — it’s <strong>how performance behaves after it does</strong>.</p><p>This article is about measuring that behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4BlNjmsM4jPYu2GP" /><figcaption>Photo by <a href="https://unsplash.com/@ejavierph?utm_source=medium&amp;utm_medium=referral">Javier Ortiz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Average Performance Still Isn’t Enough</h3><p>So far in this series, we’ve measured:</p><ul><li><strong>Efficiency</strong> (Sharpe Ratio)</li><li><strong>Controlled aggression</strong> (Sortino Ratio)</li><li><strong>Execution style</strong> (execution profiles)</li><li><strong>Context dependence</strong> (track and regime sensitivity)</li></ul><p>Those metrics explain <em>how fast</em>, <em>how risky</em>, and <em>under what conditions</em> a driver performs well.</p><p>But they share a structural assumption:</p><blockquote><em>Performance is continuous.</em></blockquote><p>Formula 1 isn’t.</p><p>Performance <strong>breaks</strong>.<br>Plans <strong>fail</strong>.<br>Chaos <strong>intervenes</strong>.</p><p>So the real question becomes:</p><blockquote><strong><em>When performance breaks, how much damage occurs — and how fast does it stabilize?</em></strong></blockquote><p>That’s the domain of <strong>drawdown and recovery</strong>.</p><h3>The Quant Analogy: Failure Is Where Skill Becomes Visible</h3><p>In quantitative finance, no serious evaluation stops at returns.</p><p>Two portfolios can have identical averages:</p><ul><li>One suffers deep drawdowns and slow recoveries</li><li>The other absorbs shocks and stabilizes immediately</li></ul><p>Only one survives long-term.</p><p>Formula 1 works the same way.</p><p>A driver who is fast until something goes wrong is <strong>fragile</strong>.<br>A driver who absorbs disruption and re-establishes efficiency is <strong>resilient</strong>.</p><p>This module measures resilience as a structure.</p><h3>Step 1: From Lap Times to Execution Equity</h3><p>Raw lap times are noisy.<br>Lap deltas are better — but still incomplete.</p><p>So instead of analyzing laps in isolation, we convert each race into an <strong>Execution Equity Curve</strong>.</p><p>Think of it as a cumulative performance account.</p><h3>Construction</h3><p>For each driver, we compute a <strong>physics-adjusted expected lap time</strong>, based on:</p><ul><li>Tire compound</li><li>Stint progression</li><li>Fuel burn</li><li>Clear-air laps only</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cewtdcN1HoY9GLt_JW-14w.png" /></figure><p>For each lap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*4Rfd-COPTFTmZTaHGWW4ag.png" /></figure><p>We accumulate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*knPqd35J5QVC70AsXBQCHA.png" /></figure><ul><li>Faster-than-expected laps <strong>add equity</strong></li><li>Slower-than-expected laps <strong>remove equity</strong></li></ul><p>The result is a continuous value curve that rises during strong execution and falls during disruption.</p><p>This transforms failure from an anecdote into a measurable event.</p><h3>Step 2: Identifying Failure Without Storytelling</h3><p>Not every equity drop means the same thing.</p><p>Traffic loss ≠ driver error ≠ strategy shock.</p><p>So drawdowns are classified using telemetry structure:</p><ul><li><strong>Traffic erosion</strong> → gradual pace loss while following</li><li><strong>Operational shock</strong> → pit stops, Safety Cars, strategy timing</li><li><strong>Incident-driven failure</strong> → sharp loss with telemetry anomaly</li></ul><p>This matters because <strong>recovery dynamics depend on failure type</strong>.</p><h3>Step 3: Measuring Drawdown — How Bad Did It Get?</h3><p>The first resilience metric is <strong>Maximum Drawdown (MDD)</strong>:</p><blockquote><em>The largest peak-to-trough loss in execution equity.</em></blockquote><ul><li>Shallow drawdowns → controlled failure</li><li>Deep drawdowns → brittle execution</li></ul><p>This measures <strong>damage containment</strong>, not speed.</p><h3>Step 4: Measuring Recovery — How Fast Does Efficiency Return?</h3><p>Damage alone doesn’t define resilience.</p><p><strong>Recovery does.</strong></p><p>So we measure <strong>Reset Velocity</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*GA2g9rNanqQmXKhfhyFLfQ.png" /></figure><p>Units: seconds of performance regained per lap.</p><ul><li>High reset velocity → rapid re-stabilization</li><li>Low reset velocity → lingering impairment</li></ul><p>This is the strongest single signal in the model — but it is <strong>not sufficient on its own</strong>.</p><p>That distinction matters.</p><h3>Step 5: Recovery Shape — How the Comeback Happens</h3><p>Two drivers can recover at similar speeds — but in different ways.</p><p>So we also classify <strong>recovery shape</strong>:</p><ul><li><strong>V-shape</strong> → sharp efficiency snap-back</li><li><strong>Linear</strong> → steady, controlled rebuild</li><li><strong>U-shape</strong> → slow confidence restoration</li></ul><p>This is not psychology.<br> It is an observable performance curvature.</p><p>Only ~20% of the grid exhibits a statistically confident V-shape recovery.</p><p>That trait is rare.</p><h3>Resilience Archetypes</h3><p>Using <strong>Maximum Drawdown</strong>, <strong>Reset Velocity</strong>, and <strong>Recovery Shape</strong>, drivers cluster into behavioral profiles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bkhJWAm8V_iFSjJWF1l1CA.png" /></figure><h4>Entropy Kings</h4><p><em>(High disruption tolerance, V-shape recovery)</em></p><ul><li>Verstappen</li><li>Norris</li><li>Piastri</li></ul><p>These drivers do not avoid chaos, they <strong>compress it</strong>.<br>Failure occurs, but efficiency reasserts itself quickly and decisively.</p><h4>Elastic Aggressors</h4><p><em>(Large drawdowns, fast snap-back)</em></p><ul><li>Russell</li><li>Albon</li></ul><p>High upside, higher variance.</p><h4>Steady Operators</h4><p><em>(Shallow drawdowns, moderate recovery)</em></p><ul><li>Leclerc</li><li>Alonso</li></ul><p>Controlled, stable execution — less explosive post-failure.</p><h4>Brittle Performers</h4><p><em>(Deep drawdowns, slow recovery)</em></p><ul><li>Ocon</li><li>Gasly</li><li>Colapinto</li></ul><p>Once performance breaks, it remains impaired.</p><h3>Resolving the Central Paradox: Norris vs Verstappen</h3><p>At first glance, the data creates a contradiction:</p><ul><li><strong>Verstappen Reset Velocity:</strong> 0.823</li><li><strong>Norris Reset Velocity:</strong> 0.592</li></ul><p>Verstappen recovers <strong>39% faster</strong>.</p><p>Yet Norris won the championship.</p><p>This is not a flaw in the model.</p><p>It’s the point.</p><h3>Why Reset Velocity Is Necessary — But Not Sufficient</h3><p>Championship outcomes depend on <strong>three interacting layers</strong>:</p><ol><li><strong>Resilience</strong> (can performance recover?)</li><li><strong>Baseline efficiency</strong> (how fast is the car?)</li><li><strong>Failure frequency</strong> (how often recovery is required)</li></ol><p>Verstappen’s recovery is unmatched.<br>But Norris required <strong>fewer recoveries</strong>.</p><ul><li>Smaller cumulative drawdowns</li><li>Higher baseline efficiency from McLaren</li><li>Strategic containment of failure events</li></ul><p>In quant terms:</p><blockquote><em>Verstappen has the best recovery function.<br>Norris optimized the system so it was needed less often.</em></blockquote><p>The model explains ~91% of outcome variance.<br>The remaining ~9% comes from <strong>strategy, car advantage, and failure exposure</strong>.</p><h3>Norris vs Piastri Interpretation</h3><p>Both McLaren drivers are Entropy-class performers.</p><p>But the data shows:</p><ul><li><strong>Norris Reset Velocity:</strong> 0.592</li><li><strong>Piastri Reset Velocity:</strong> 0.580</li></ul><p>Norris recovers ~2% faster.</p><p>The difference is subtle.</p><p>Piastri’s execution equity swings are <strong>not deeper</strong>; they are <strong>similar</strong>, with marginally slower stabilization.</p><p>This aligns with outcomes without overstating causation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7s89N-zg5uK4s_rNhSKyg.png" /></figure><h3>What This Metric Is and Isn’t</h3><p>This does <strong>not</strong> measure:</p><ul><li>Raw talent</li><li>Strategy decisions</li><li>Car ceiling</li></ul><p>It <strong>does</strong> measure:</p><ul><li>Damage containment</li><li>Post-failure stabilization</li><li>Repeatable resilience traits</li></ul><p>It explains <em>how</em> drivers survive chaos, not why every race is won.</p><h3>Why This Matters</h3><p>Races are not won in perfect conditions.<br> Championships are not built on flawless weekends.</p><p>They’re built on:</p><ul><li>Limiting failure depth</li><li>Recovering efficiency quickly</li><li>Preventing disruption from compounding</li></ul><p>That is not narrative.</p><p>That is the process.</p><h3>Closing Thought</h3><p>In finance, returns attract attention.<br>Drawdowns determine survival.</p><p>Formula 1 is no different.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02a67c73ff13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Alpha of a Driver: Separating Skill from Machinery in Formula 1]]></title>
            <link>https://prabhatm27.medium.com/the-alpha-of-a-driver-separating-skill-from-machinery-in-formula-1-ebe0f9c099dd?source=rss-f0451664d8fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebe0f9c099dd</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[formula-1]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Prabhat M]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 20:18:03 GMT</pubDate>
            <atom:updated>2026-01-26T20:18:03.582Z</atom:updated>
            <content:encoded><![CDATA[<h4>#4 in the Quant × Sports — Where Markets Meet Motorsport</h4><p>This is part of the <strong>Quant × Sports Series</strong>.<br>Read Part 3→ The Execution Profile of a Driver: Measuring Performance Beyond the Results Table (<a href="https://prabhatm27.medium.com/the-execution-profile-of-a-driver-measuring-performance-beyond-the-results-table-aeda8202f423">link</a>)</p><p>Its always easier to look at the simple numbers in F1 and come to a conclusion about the skill of drivers and how teams are actually performing.</p><p>Who won?<br>Who scored points?<br>Who’s leading the championship?</p><p>But those answers hide an inconvenient truth:</p><p><strong>Formula 1 does not measure drivers — it measures cars.</strong></p><p>A flawless drive in a backmarker looks like P15.<br>A mediocre drive in a dominant car looks like P2.</p><p>So when we say a driver had a “great race,” what are we actually talking about?</p><p>And more importantly:</p><blockquote><strong><em>Can we mathematically separate driver execution from car performance?</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fWwUY0CCdkGDEXb7" /><figcaption>Photo by <a href="https://unsplash.com/@stefanbc?utm_source=medium&amp;utm_medium=referral">Stefan Cosma</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Quant Analogy: Alpha vs. Beta</h3><p>In quantitative finance, no serious analyst evaluates performance using raw returns.</p><p>If a portfolio returns 10%, that doesn’t inherently mean the manager is skilled.<br>Maybe the entire market returned 12%.</p><p>So quants decompose performance into:</p><ul><li><strong>Beta</strong> → what you earned because the market moved</li><li><strong>Alpha</strong> → what you earned because <em>you</em> made good decisions</li></ul><p>Formula 1 has the same structure:</p><ul><li><strong>The car is the market</strong></li><li><strong>The driver is the strategy</strong></li></ul><p>Yet F1 analysis still judges drivers by finishing position — the equivalent of ranking hedge funds by headline returns.</p><p>This project asks a different question:</p><blockquote><strong><em>Can we use quantitative finance techniques to isolate driver execution quality relative to identical machinery and comparable conditions?</em></strong></blockquote><p>That’s not “pure talent.”<br>It’s something more measurable, and more useful.</p><h3>The Core Philosophy</h3><p>The immediate goal is not to predict race results.</p><p>The goal is to <strong>understand how a driver performs</strong>, independent of:</p><ul><li>fuel load</li><li>tire compound</li><li>tire age</li><li>track evolution</li><li>car baseline</li></ul><p>In other words:</p><blockquote><strong><em>What does a driver’s race look like once we take away the predictable physics?</em></strong></blockquote><p>Smooth and controlled?<br>Aggressive and volatile?<br>Efficient or wasteful?</p><h3>The Methodology: A Bias-Free Pipeline</h3><p>Instead of starting with results, I built a four-stage pipeline that runs without human judgment or narrative bias.</p><h3>1️⃣ Regime Classification: Defining the Environment</h3><p>Raw lap times are misleading.</p><p>A 1:20 lap at the start of a stint on hards is not the same as a 1:20 lap at the end on softs.</p><p>So the first step is context.</p><p>An algorithm scans telemetry and classifies race environments into <strong>regimes</strong>, based on measurable properties like:</p><ul><li>tire degradation intensity</li><li>fuel sensitivity</li><li>volatility and disruption</li><li>pace stability</li></ul><p>This produces labels such as:</p><ul><li><em>High Degradation</em></li><li><em>Stable Downforce</em></li><li><em>Chaotic / Disrupted</em></li></ul><h3>2️⃣ Conditional Performance: Measuring Efficiency, Not Speed</h3><p>Once regimes are defined, drivers are evaluated <strong>within each regime</strong>, not across the entire race.</p><p>For every driver and every regime, we compute a <strong>Sharpe-style efficiency metric</strong>:</p><ul><li>pace advantage relative to expectation</li><li>normalized for volatility</li><li>adjusted for fuel and tire evolution</li></ul><p>This answers a precise question:</p><blockquote><strong><em>How efficiently does a driver convert pace into repeatable performance when conditions are comparable?</em></strong></blockquote><p>Not who was fastest.<br>Who was <em>efficient</em>?</p><h3>3️⃣ Skill Isolation — The Teammate as the Benchmark</h3><p>In finance, alpha is always measured relative to a benchmark.</p><p>In Formula 1, the cleanest benchmark is:</p><blockquote><strong><em>Your teammate.</em></strong></blockquote><p>Same car.<br>Same upgrades.<br>Same development curve.</p><p>For each regime, we compute <strong>Teammate Delta</strong>:</p><ul><li>positive → outperforming identical machinery</li><li>negative → underperforming identical machinery</li></ul><p>This step removes:</p><ul><li>brand mythology</li><li>car hype</li><li>championship narratives</li></ul><p>What remains is <strong>relative execution quality</strong>, not results.</p><p>This assumes broadly similar strategic constraints, an approximation, but this seemed like the cleanest available benchmark.</p><h3>4️⃣ Clustering: Discovering Driver Phenotypes</h3><p>Rather than ranking drivers, the system groups them by <strong>similarity of behavior</strong>.</p><p>Using unsupervised clustering, drivers naturally separate into phenotypes:</p><ul><li>team leaders vs passengers</li><li>generalists vs specialists</li><li>overachievers vs inefficient assets</li></ul><p>The patterns emerge from the data.</p><h3>Visual 1: Man vs. Machine — Skill Isolation Quadrant</h3><p>This scatter plot separates <strong>driver contribution</strong> from <strong>car strength</strong>.</p><p><strong>X-axis:</strong> Machine performance<br> (Team Mean Sharpe Ratio — how efficient the car is overall)</p><p><strong>Y-axis:</strong> Driver alpha<br> (Driver Sharpe minus Team Mean — value added relative to teammate)</p><p>The four quadrants tell a brutal story:</p><ul><li><strong>Top Right:</strong> Elite driver in elite machinery</li><li><strong>Top Left:</strong> Overachiever — extracting value from a slow car</li><li><strong>Bottom Right:</strong> Underperformer — wasting strong machinery</li><li><strong>Bottom Left:</strong> Struggling with poor equipment</li></ul><p>This answers a simple but uncomfortable question:</p><blockquote><strong><em>Who is carrying the car — and who is being carried by it?</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLS_UiX4cj3sDy15_RYM-A.png" /></figure><h3>Visual 2: Driver DNA — Regime-Based Radar Profiles</h3><p>Each driver has a performance “shape.”</p><p>This radar chart shows efficiency across five race regimes:</p><ul><li>High degradation</li><li>Extreme degradation</li><li>Chaotic races</li><li>Power tracks</li><li>Technical circuits</li></ul><p>How to read it:</p><ul><li><strong>Large, balanced shape → generalist</strong></li><li><strong>Spiky shape → specialist</strong></li></ul><p>This reframes driver debates entirely.</p><p>Not:</p><blockquote><em>“Who’s better?”</em></blockquote><p>But:</p><blockquote><strong><em>“Better at what?”</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TolRD0RfIK9qCsVXjdL-UQ.png" /></figure><h3>The Verdicts</h3><h4>The Red Bull Sweet Spot</h4><p>In the 2025 data:</p><ul><li>Verstappen Technical Track Sharpe ≈ 4.04</li><li>Verstappen Very High Deg Sharpe ≈ 0.21</li></ul><p>This is a design choice.</p><p>Red Bull built the RB21 to dominate technical, downforce-heavy circuits like Monaco and Hungary. The numbers prove it works: Max’s efficiency spikes nearly 4x on those tracks.</p><p>On high-degradation circuits, where tire management matters more than aero balance, the car is less optimized — not the driver.</p><p>This is the insight Moneyball gives you:</p><ul><li>Which car concepts suit which tracks</li><li>Where a team’s development investments are paying off</li></ul><p>Red Bull bet on aero. The data shows they were right.</p><h4>The Ferrari Paradox</h4><p>Leclerc Front Runner 2.01 (Very High Deg)<br>Hamilton Front Runner 1.37 (Very High Deg)</p><p>Both Ferrari drivers are classified as “Front Runner” — the model’s top performance tier.</p><p>The Raw Efficiency Numbers:</p><ul><li>Leclerc on Power Tracks: 1.71 Sharpe</li><li>Leclerc on High Deg: 1.69 Sharpe</li><li>Hamilton in Low Deg: 1.01 Sharpe</li><li>Team Average: ~1.2 Sharpe (among the highest on the grid)</li></ul><p>What this proves: The Ferrari was fast across all regime types — High Deg, Power, Technical.</p><p>If Ferrari underperformed in the championship, the bottleneck was not the car’s raw pace. It was:</p><ul><li>Strategy calls</li><li>Pit stop execution</li><li>Driver/team errors under pressure</li></ul><p>That’s the diagnosis.</p><h3>Why This Matters</h3><p>This framework doesn’t replace traditional F1 analysis.</p><p>It allows us to:</p><ul><li>separate execution from the equipment</li><li>identify hidden value</li><li>understand performance styles</li><li>evaluate drivers beyond results</li></ul><p>This isn’t about hot takes.</p><p>It’s about building a language of performance that survives regulation changes.</p><h3>What’s Next: Measuring Breakdown</h3><p>So far, we’ve measured:</p><ul><li><strong>Efficiency</strong> (Sharpe)</li><li><strong>Controlled aggression</strong> (Sortino)</li><li><strong>Behavioral execution</strong> (Execution Profiles)</li><li><strong>Contextual execution</strong> (Regimes)</li></ul><p>The next frontier is resilience.</p><p>In markets, the real test isn’t returns — it’s drawdowns.</p><p>Because in Formula 1 (as in finance)</p><blockquote><em>Speed gets attention.<br>Efficiency gets results.<br></em><strong><em>Resilience wins championships.</em></strong></blockquote><p><em>Note: This framework assumes teammates face broadly comparable strategic constraints. That assumption is imperfect — but it is the least biased benchmark available.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebe0f9c099dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Execution Profile of a Driver: Measuring Performance Beyond the Results Table]]></title>
            <link>https://prabhatm27.medium.com/the-execution-profile-of-a-driver-measuring-performance-beyond-the-results-table-aeda8202f423?source=rss-f0451664d8fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeda8202f423</guid>
            <category><![CDATA[formula-1]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Prabhat M]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 04:20:19 GMT</pubDate>
            <atom:updated>2026-01-13T04:43:58.883Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>#3 in the Quant × Sports Series — where markets meet motorsport</strong></p><p>This is part of the <strong>Quant × Sports Series</strong>.<br>Read Part 2 → The Sortino Ratio of a Driver: Measuring Controlled Aggression in F1 (<a href="https://prabhatm27.medium.com/the-sortino-ratio-of-a-driver-measuring-controlled-aggression-in-f1-b2ca4dd0029b">link</a>)</p><p>Only one number matters in Formula 1: <strong>P1</strong>.</p><p>And that makes sense. Championships are decided by points, not explanations.</p><p>But if you want to understand performance (not just the standings), the results table is brutally incomplete.</p><p>Two drivers can finish at the same position in different races:</p><ul><li>One could have been after a calm and perfectly managed race</li><li>The other could have been after a chaotic sequence of pushes, saves, and recoveries</li></ul><p>Same position. Completely different execution.</p><p>So the real question becomes:</p><blockquote><strong><em>How did a driver actually perform across the race (lap by lap) once we control for the physical environment they were operating in?</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M25wnrWYZeBitFDp" /><figcaption>Photo by <a href="https://unsplash.com/@ssarasframes?utm_source=medium&amp;utm_medium=referral">Sara Ruffoni</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Raw Lap Times Lie</h3><p>A lap time is never just a lap time.</p><p>A 1:20 lap:</p><ul><li>Early in the race</li><li>On hard tires</li><li>With a full fuel tank</li></ul><p>It is not comparable to a 1:20 lap:</p><ul><li>Late in the race</li><li>On soft tires</li><li>With an empty car</li></ul><p>Comparing raw lap times without adjusting for these factors is like comparing stock prices without accounting for market conditions.</p><p>Before we measure drivers, we need to normalize the <strong>physical environment</strong>.</p><h3>Step 1: Creating a Level Playing Field</h3><p>The foundation of this analysis is a <strong>dynamic benchmark,</strong> which is a fair expectation for every lap of the race, given the car’s physical state.</p><h3>Grouping by Comparable Context</h3><p>All clean, green-flag laps are grouped by:</p><ul><li>Tire compound</li><li>Stint number</li></ul><p>This creates comparable regimes such as:</p><ul><li>Stint 1 on Mediums</li><li>Stint 2 on Hards</li></ul><p>Each bucket represents similar physical constraints.</p><h3>Modeling Expected Pace</h3><p>Within each bucket, we fit a simple regression:</p><ul><li><strong>Lap time vs. lap number</strong></li></ul><p>This naturally captures:</p><ul><li>Fuel burn (cars get lighter and faster)</li><li>Tire degradation (pace gradually declines)</li></ul><p>The result is an <strong>expected lap time</strong> for every lap — adjusted for fuel load, tire choice, and race phase.</p><p>It answers a powerful question:</p><blockquote>What should a competent driver reasonably do in this exact moment of the race?</blockquote><h3>Step 2: Measuring Execution (The Delta)</h3><p>Now we measure each driver against that expectation.</p><p>For every lap:</p><p><strong>LapTimeDelta = Actual Lap Time − Expected Lap Time</strong></p><ul><li>Negative delta → faster than expected</li><li>Positive delta → slower than expected</li></ul><p>This delta is the <strong>core signal</strong>.</p><p>It normalizes for:</p><ul><li>Fuel load</li><li>Tire compound</li><li>Stint phase</li></ul><p>What remains is <strong>execution under race-imposed constraints</strong>.</p><p>Importantly, this does <em>not</em> remove:</p><ul><li>Traffic</li><li>Strategy exposure</li><li>Race position effects</li></ul><p>Those are deliberately retained — because they are part of the real execution environment.</p><h3>Step 3: Describing How a Driver Executed Their Race</h3><p>Once we have a time series of LapTimeDelta, we can describe <em>how</em> the race was executed and not just how fast it was.</p><h3>Execution Smoothness</h3><p>We compute the standard deviation of LapTimeDelta across the race.</p><ul><li>Low variation → smooth, controlled execution</li><li>High variation → turbulent, erratic execution</li></ul><p>To make interpretation intuitive:</p><p><strong>Execution Smoothness = − (Std Dev of LapTimeDelta)</strong></p><p>Higher (less negative) values indicate calmer, more stable execution.</p><p>This metric does <strong>not</strong> measure speed.<br>It measures <strong>how evenly performance was delivered</strong> under changing conditions.</p><h3>Pace Evolution (Race Direction)</h3><p>Next, we ask: did the driver grow into the race or fade?</p><p>The race is split into:</p><ul><li>Early</li><li>Middle</li><li>Late</li></ul><p>We compute the average delta in each segment and evaluate the trend over time.</p><ul><li>Improving trend → execution strengthens across the race</li><li>Declining trend → execution fades</li></ul><p>This captures the <em>shape</em> of the race, not just its average.</p><h3>Step 4: From Metrics to Execution Profiles</h3><p>By combining:</p><ul><li><strong>Execution Smoothness</strong></li><li><strong>Pace Evolution</strong></li></ul><p>We can classify each driver’s race into one of four execution profiles:</p><h3>🟢 Smooth Improver</h3><p>Consistent and getting faster<br>The ideal execution profile</p><h3>🟡 Smooth Fader</h3><p>Stable but losing pace<br>Often deliberate tire or race management</p><h3>🔵 Turbulent Improver</h3><p>Erratic early, strong recovery<br>Aggressive recovery drives</p><h3>🔴 Turbulent Fader</h3><p>Inconsistent and declining<br>Loss of grip, balance, or control</p><p>This transforms a finishing position into a <strong>behavioral fingerprint</strong>.</p><h3>Reading an Execution Profile in Practice</h3><p>To make this concrete, let’s look at how execution profiles appear in real race data and how they line up with what actually happened on track at the <strong>2025 Hungarian Grand Prix</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgh4k_IxNXrjcbi2pnIu_A.png" /></figure><p>Each driver’s race can be summarized by three quantities:</p><ul><li><strong>Adaptability Index</strong> — how turbulent or smooth the driver’s execution efficiency was across the race</li><li><strong>Pace Evolution</strong> — whether execution improved or faded from early to late race</li><li><strong>Consistency Evolution</strong> — whether lap-to-lap smoothness improved or deteriorated over time</li></ul><p>Taken together, these numbers describe the <em>shape</em> of a race, not its final position.</p><p>Consider <strong>Lance Stroll (STR)</strong> at Aston Martin. His Adaptability Index of <strong>−0.37</strong> is among the least negative values in the field, indicating a relatively smooth, low-turbulence race. However, his Pace Evolution of <strong>−0.25</strong> shows that this smoothness came at the cost of a gradual performance fade. This is the textbook <em>smooth fader</em> profile: calm delivery, limited volatility, but an inability to maintain pace as the race evolved. That aligns with Stroll’s quiet, non-eventful run outside the fight for top positions, implying that his race was stable but never threatening.</p><p>Now contrast that with <strong>Lando Norris (NOR)</strong>. Norris’s Adaptability Index (<strong>−0.43</strong>) indicates more turbulence than Stroll’s, reflecting a race that involved active pace management rather than linear execution. His Pace Evolution is essentially flat (<strong>+0.01</strong>), meaning his performance neither improved nor declined significantly over time. Combined with a slightly negative Consistency Evolution, this paints a picture of <em>controlled volatility</em>: deliberate modulation of pace in response to strategy and tire constraints, rather than instability. That profile aligns with the reality of Norris’s race, where he employed a one-stop strategy under pressure, absorbing pace swings without losing control, and ultimately converting execution into victory.</p><p>Next, consider <strong>Charles Leclerc (LEC)</strong>. His Adaptability Index (<strong>−0.84</strong>) is far more negative, signaling a highly turbulent race. At the same time, his Pace Evolution is strongly positive (<strong>+0.70</strong>). This is a classic <em>turbulent improver</em> profile: large swings in execution efficiency, but an overall recovery trend across the race. Leclerc led early from pole before Ferrari’s strategy and degradation issues caused a sharp mid-race drop in competitiveness. His late-race recovery improved the average execution trend, but the path there was uneven. The model doesn’t say Leclerc “drove poorly,” but instead it shows that his performance arrived in bursts rather than through smooth, repeatable delivery, which is consistent with how his race unfolded.</p><p>Finally, look at <strong>Lewis Hamilton (HAM)</strong>. With an Adaptability Index of <strong>−0.84</strong>, a sharply negative Pace Evolution (<strong>−0.48</strong>), and a strongly positive Consistency Evolution (<strong>+0.33</strong>), Hamilton’s execution shows an interesting split. His overall pace faded, but his lap-to-lap smoothness improved as the race progressed. This combination is typical of a driver backing off peak performance to regain control: sacrificing outright pace to stabilize execution. In race terms, this reflects a conscious trade-off between speed and manageability rather than a loss of composure.</p><h3>What This Reveals (That Results Don’t)</h3><p>This framework exposes truths the leaderboard hides:</p><ul><li>Some drivers finish high despite chaotic execution</li><li>Others deliver elite, composed races with modest results</li><li>Winning strategies can be smooth <em>or</em> deliberately volatile</li></ul><p>The key insight is simple:</p><blockquote><strong><em>Results tell you who succeeded. Execution tells you how repeatable that success is.</em></strong></blockquote><p>In finance, this is the difference between luck and skill.<br>In Formula 1, it’s the difference between a good Sunday and a championship profile.</p><h3>What This Metric Is — and Isn’t</h3><p>This is <strong>not</strong> a measure of:</p><ul><li>Driver talent in isolation</li><li>Strategic decision-making authority</li><li>Car performance</li></ul><p>It <em>is</em> a measure of:</p><ul><li>Driver execution under the regimes they were given</li></ul><p>It captures <strong>how performance was delivered</strong> — smoothly or violently — regardless of whether the regime was chosen by the driver or imposed by the team.</p><p>That distinction matters.<br>Acknowledging it makes the metric stronger, not weaker.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeda8202f423" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Sortino Ratio of a Driver: Measuring Controlled Aggression in F1]]></title>
            <link>https://prabhatm27.medium.com/the-sortino-ratio-of-a-driver-measuring-controlled-aggression-in-f1-b2ca4dd0029b?source=rss-f0451664d8fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2ca4dd0029b</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[performance-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[f1]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Prabhat M]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 21:11:16 GMT</pubDate>
            <atom:updated>2025-10-25T00:07:10.745Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>#2 in the Quant × Sports Series — where markets meet motorsport.</em></h4><p>This is part of the <strong>Quant × Sports Series</strong>. <br>Read Part 1 → The Sharpe Ratio of a Driver: What Quant Finance Can Teach Us About Formula 1 Performance (<a href="https://prabhatm27.medium.com/the-sharpe-ratio-of-a-driver-what-quant-finance-can-teach-us-about-formula-1-performance-3f99c1f32d8f">link</a>)</p><h3>The Art of Controlled Chaos</h3><p>In Formula 1, every lap is a calculation, a trade between <strong>speed and survival</strong>. <br>Push too hard into Turn 1, and you might be a tenth faster. Push too hard twice, and you might spin out.</p><p>The best drivers don’t just drive fast, but they drive <strong>on the edge</strong> of chaos without falling off it.<br>They know when to risk the tire, when to back off, and when to press an advantage.</p><p>That balance between aggression and control is one of the hardest things to quantify.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qkz_9RVjp8PAjUIE" /><figcaption>Photo by <a href="https://unsplash.com/@shotinmoment_?utm_source=medium&amp;utm_medium=referral">Roy Tsong</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>From the Sharpe Ratio to the Sortino Ratio</h3><p>In my previous article, I talked about the <strong>Driver Sharpe Ratio</strong>, which is a way to measure how efficiently an F1 driver converts pace into consistency.<br>It was inspired by quantitative finance, where the Sharpe Ratio measures the <em>return</em> an investor earns for each unit of <em>volatility</em> they incur.</p><p>But there’s one problem with the Sharpe Ratio.</p><p>It treats all volatility as bad.</p><p>A driver who pushes hard and delivers some moments of brilliance looks just as “risky” as one who’s erratic and slow.<br>But in F1, not all risk is bad. Some risk is <strong>productive; </strong>it’s the difference between bold and reckless, between winning and spinning out.</p><p>So this led to a refined approach:</p><blockquote><em>“Can we measure this </em>smart aggression<em>?”</em></blockquote><p>That’s where the <strong>Sortino Ratio</strong> comes in.</p><h3>The Finance Connection</h3><p>In finance, the <strong>Sortino Ratio</strong> refines the Sharpe Ratio by penalizing only <em>downside</em> volatility.<br>It doesn’t care if your portfolio is wildly successful on the upside; it only worries about the losing streaks.</p><p>The formula looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*g5go2dY8e-u2Q9SkTEvcoA.png" /></figure><p>Investors use it to identify funds that don’t just grow fast, but grow <em>smoothly</em>, with minimal drawdowns.<br>In other words, it rewards <strong>asymmetric efficiency,</strong> which is a high reward with a controlled downside.</p><p>That’s exactly what great F1 drivers do, and what separates them from good drivers.</p><h3>The Sortino Ratio of a Driver</h3><p>To translate this idea to motorsport, I adapted the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*xVxCMraWDcXthkPbnuNxWQ.png" /></figure><p>Where:</p><ul><li><strong>Mean Delta vs Expected Pace</strong> → The driver’s average pace advantage compared to their expected lap time, predicted by a regression model that accounts for <em>fuel load, tire wear, and track evolution.</em></li><li>Negative means faster than expected (good return).</li><li>Positive means slower than expected (bad return).</li><li><strong>Downside Deviation</strong> → The standard deviation of <em>only the laps that were slower than the driver’s own expected performance.</em><br> This isolates how much a driver’s <em>mistakes or degradation laps</em> hurt them.</li></ul><p>The negative sign ensures that faster drivers earn higher scores.</p><p>So a <strong>higher Sortino Ratio</strong> means better <em>risk-adjusted performance</em>.</p><h3>What It Measures</h3><p>The Driver Sortino Ratio tells us who’s <strong>aggressively consistent</strong>, about drivers who push hard but rarely make costly mistakes.</p><p>Sortino InterpretationMeaningAnalogy</p><p>🔵 <strong>High Positive (2.0+): </strong>Fast and controlled “Calculated aggression”<br>🟠 <strong>Moderate (0.5–1.5): </strong>Balanced, some risk-taking “Efficient but cautious”<br>🔴 <strong>Low or Negative (&lt;0): </strong>Slow or erratic “Reckless or inconsistent”</p><h3>Hungary 2025: Measuring Controlled Aggression</h3><p>I ran this model on the <strong>2025 Hungarian Grand Prix</strong>, using fuel- and stint-adjusted lap data for every driver.</p><p>The Sortino Ratio focused only on downside laps — those slower than each driver’s expected pace for the stint and tire compound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7txq_fQayvvMTsZMZSjtA.png" /></figure><p>🏁 <strong>Top Performers: </strong>Norris (3.24), Piastri (2.41)<br> ⚙️ <strong>Consistent Drivers: </strong>Russell (1.38), Hamilton (0.78)<br> 🔸 <strong>Fragile Aggression: </strong>Leclerc (0.35)<br> 🔺 <strong>Aggressive Volatility: </strong>Verstappen (0.13)<br> 🔻 <strong>Uncontrolled Downside</strong> : Ocon (−2.02), Bearman (−2.10)</p><h3>Interpreting the Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPUgEqOLvrwavzTrKQAu-Q.png" /></figure><h4>Norris &amp; Piastri: Efficient Aggression</h4><p>Both McLaren drivers are at the top of the chart, but for different reasons.</p><ul><li>Norris (3.24) delivered elite <em>downside control (</em>his slowest laps barely deviated from the trend). He took a one-stop strategy that was not recommended before the race, and had a strong race.</li><li>Piastri (2.41) was slightly less explosive but equally composed. He had a two-stop strategy and couldn&#39;t overtake Lando during the final laps of the race.</li></ul><blockquote><em>McLaren’s risk-adjusted performance profile is the quant version of “pushing without panic.”</em></blockquote><h4>Russell &amp; Hamilton: Stable but Not Untouchable</h4><ul><li>Russell (1.38) shows steady control with occasional slow-lap drift — efficient, but not perfect. This is very impressive considering he finished 3rd, starting from 18th place on the grid.</li><li>Hamilton (0.78) suffered higher downside volatility, suggesting a tire or setup imbalance that amplified slower laps. He had a solid driver despite the issues they had.</li></ul><blockquote><em>They’re both consistent but under heavy degradation, the system shows cracks.</em></blockquote><h4>Leclerc: Fragile Aggression</h4><ul><li>Leclerc’s raw pace (-0.38s delta) was quick, but his downside deviation (0.73s) affected his score. That aligns perfectly with his self-described “chassis problem” mid-race, where his performance curve fell off sharply.</li></ul><blockquote><em>The Sortino Ratio reveals that his </em>mistakes were costly enough to negate his speed.</blockquote><h4>Verstappen: Aggressive Volatility</h4><p>Verstappen (0.13) appears unusually low here because his race featured <em>large pace swings</em> during traffic and recovery phases.<br>The Sortino penalizes that — it doesn’t care about heroic charges; it rewards efficiency. He also mentioned that there was a consistent lack of grip and balance in the car that prevented him from making progress.</p><blockquote><em>This is just a quant reminder that even elite aggression has a volatility cost.</em></blockquote><h4>The Tail End: Uncontrolled Downside</h4><p>Drivers like Ocon (-2.02) and Bearman (-2.10) sit deep in the red.<br>Their slow laps were significantly off-trend, suggesting tire degradation, defensive fighting, or car instability.</p><ul><li>Esteban Ocon had a one-stop strategy, while initially promising, ultimately proved less effective than the two-stop strategies used by many competitors who were on fresher tires at the end of the race.</li><li>Oliver Bearman retired from the 2025 Hungarian Grand Prix on lap 48 due to rear floor damage.</li></ul><p>They not only lost pace but also lost control of their “volatility.”</p><blockquote><em>In market terms, these are </em>drawdown-heavy portfolios<em>: too much risk for too little return.</em></blockquote><h3>Visualizing the Efficient Frontier of Aggression</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQbBE64h4qxfs-gp5N3xow.png" /></figure><ul><li>The <strong>frontier</strong> defines the <em>limit of smart aggression</em> in F1.</li><li>Drivers above or on it are “statistical benchmarks”, i.e., their aggression is efficiently translated into lap performance.</li></ul><p>Teams can use this to:</p><ul><li>Identify where their drivers are losing efficiency.</li><li>Train toward the <em>frontier zone</em> to have an aggressive yet stable performance.</li></ul><h3>What the Sortino Ratio Teaches Us</h3><p>The Sharpe Ratio tells us <em>how efficient</em> a driver is.<br>The Sortino Ratio tells us <em>how intelligently they take risks.</em></p><p>It rewards drivers who:</p><ul><li>Push their limits but avoid collapse.</li><li>Deliver fast laps without chaos.</li><li>Manage degradation with precision.</li></ul><p>It punishes drivers who:</p><ul><li>Lose control under pressure.</li><li>Have volatile slow-lap behavior.</li><li>Fail to recover stability across stints.</li></ul><h3>Beyond Racing: The Philosophy of Asymmetry</h3><p>In both markets and motorsport, <strong>you don’t have to be flawless;</strong> it&#39;s almost impossible to pull that off. You just have to make sure your worst moments don’t take you out of contention.</p><p>To summarize the whole point about Sortino Ratio:</p><blockquote><em>“Excellence isn’t avoiding mistakes it’s minimizing the cost when you make them.”</em></blockquote><p>That’s what differentiates the fast from the great, and the aggressive from the <strong>controlled.</strong></p><h3>What’s Next</h3><p>If the <strong>Sharpe Ratio</strong> measured <em>efficiency</em> and the <strong>Sortino Ratio</strong> captured <em>controlled aggression</em>, the next question becomes:</p><blockquote><em>How do drivers adapt when conditions change — safety cars, rain, tire degradation, chaos?</em></blockquote><h3>Closing Thought</h3><p>In finance, investors chase alpha.<br>In racing, drivers chase perfection.<br>But both succeed by managing their <strong>downside</strong> better than anyone else.</p><p>The <em>Driver Sortino Ratio</em> isn’t about playing safe. It’s about knowing when risk is worth taking.</p><p>Because in Formula 1, as in markets</p><blockquote><strong><em>Speed wins races, but control wins seasons.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2ca4dd0029b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Sharpe Ratio of a Driver: What Quant Finance Can Teach Us About Formula 1 Performance]]></title>
            <link>https://prabhatm27.medium.com/the-sharpe-ratio-of-a-driver-what-quant-finance-can-teach-us-about-formula-1-performance-3f99c1f32d8f?source=rss-f0451664d8fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f99c1f32d8f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[quant-finance]]></category>
            <category><![CDATA[formula-1]]></category>
            <dc:creator><![CDATA[Prabhat M]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 21:50:14 GMT</pubDate>
            <atom:updated>2025-10-25T00:05:33.099Z</atom:updated>
            <content:encoded><![CDATA[<p><em>#1 Quant × Sports Series where markets meet motorsport</em></p><p>Who is going to win the F1 season 2025?</p><p>It&#39;s something I&#39;ve been thinking about, and the more I thought about it, there are a couple of things I realized.</p><p>Every Formula 1 season is a probability curve — full of volatility, noise, and sudden shocks. The question isn’t just who’s fastest; it’s who’s most efficient under pressure.</p><p>The more I watched this season, the more it started to look like another game I was looking at: quantitative finance.<br>Both worlds live and die by data. Both chase optimization under chaos. Both reward those who can turn risk into repeatable performance.</p><p>In finance, investors seek the highest return for every unit of volatility.<br>In racing, drivers chase the most pace for the amount of risk they dare to take.</p><p>In every lap, every trade, the same dilemma repeats: aggression versus control.<br>Talent helps, but systems decide outcomes, whether it’s the car and team in F1, or the market and model in finance.<br>Both dance on moving ground, adapting to shifting regimes — macro trends or track temperatures, beta or rubber.</p><p>In the end, it all comes down to one thing:<br><strong>How much performance can you extract without losing control?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sPNSHjZUdW85yPwv" /><figcaption>Photo by <a href="https://unsplash.com/@peti223?utm_source=medium&amp;utm_medium=referral">Péter Török</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why do this?</h3><p>Every race ends with a winner, a podium, and a spray of champagne. <br>But when you look further, there’s a deeper story, one that doesn&#39;t stop on Sunday but goes on.</p><p>Formula 1 doesn’t start fresh each season. It compounds.</p><p>Every lap is a data point. <br>Every stint, a simulation. <br>Every failure, a calibration.</p><p>The telemetry from this weekend becomes the blueprint for next year’s car.<br>The mistakes a driver makes in Turn 3 today turn into muscle memory by next March.</p><p>Winning the moment matters. But mastering the process, that’s how eras are created and dynasties are built.</p><p>Just like in investing, it’s not the return that defines greatness <br>It’s <em>how</em> that return was earned.</p><h3>From Markets to Motorsports</h3><p>This idea led to a question:</p><blockquote><em>Could we measure how efficiently a driver converts speed into consistency or, in quant terms, the “return” per unit of “risk” they take on track?</em></blockquote><p>The <strong>Driver Sharpe Ratio</strong> is a racing adaptation of one of finance’s most famous metrics for risk-adjusted performance.</p><p>In finance, the Sharpe Ratio tells you how much return you’re earning for every unit of volatility (risk) you take. It doesn’t just reward big gains — it rewards <em>efficient gains.</em> The kind that are consistent, repeatable, and achieved without excessive swings.</p><p>In racing, we can think about the same principle in terms of <em>pace vs. volatility.</em></p><ul><li>A driver with blistering lap times but wild inconsistency might look impressive in moments, but across a full race, they’re “high-beta”: fast but unstable.</li><li>Another driver might never set the absolute fastest lap, but deliver near-identical times for 60 laps straight. They’re “low-volatility alpha”: efficient, composed, and consistent under pressure.</li></ul><p>So, the <strong>Driver Sharpe Ratio</strong> isn’t about who was fastest, it’s about who was <em>most efficient</em>: who extracted the most performance per unit of chaos.</p><h3>The Formula</h3><p>In finance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*mxunrsGnpSFDHXQeSQlEeg.png" /><figcaption>Sharpe Ratio= (Return−Risk-Free Rate) / Volatility</figcaption></figure><p>In racing (fuel-adjusted version):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*6xsRTb_iMSY9uLxwcaHUtw.png" /></figure><p><strong>Where:</strong></p><ul><li><strong>Pace Advantage (Return):</strong> The driver’s average time difference from their <em>expected lap time</em>, predicted by a regression trendline that approximates how lap times evolve across fuel load, tire wear, and track evolution.</li><li>Negative = faster than expected (better return)</li><li>Positive = slower than expected (worse return)</li><li><strong>Inconsistency (Risk):</strong> The standard deviation of those deltas — how much a driver’s lap times fluctuate around their expected trend.</li></ul><p><strong>Why the negative sign?</strong><br>Because a faster lap means a negative delta (for example, −0.2 s compared to the benchmark).<br>We flip the sign so that faster drivers earn higher scores — ensuring that a <strong>higher Sharpe Ratio always means better risk-adjusted performance.</strong></p><p><strong>What this means: </strong><br>A high (positive) Sharpe Ratio indicates that the driver was consistently faster than expected, yielding strong and stable performance.<br>A low or negative Sharpe Ratio means they were slower, inconsistent, or both.</p><h3>The limitation of the first insight</h3><p>At first, I computed a <strong>raw Driver Sharpe Ratio</strong> across the entire race — one elegant number to capture who was fast <em>and</em> consistent.</p><p>It worked… up to a point.</p><p>For example, Charles Leclerc (the pole sitter) had the <em>highest</em> Sharpe Ratio in the 2025 Hungarian GP but ended up finishing 4th in the race, which isn&#39;t the strongest performance. Charles Leclerc, himself, described it by saying that they had a problem with the chassis around Lap 40, and they lost the race pace.</p><p>But he still had the highest Sharpe ratio. Why is that?<br>Because <strong>lap times aren’t static assets.</strong></p><p>They change dynamically due to:</p><ul><li><strong>Tire wear</strong> → grip drops lap by lap</li><li><strong>Fuel load</strong> → cars lighten and speed up</li><li><strong>Track evolution</strong> → rubber builds up, grip improves</li><li><strong>Strategy &amp; weather</strong> → compounds, pit windows, and conditions shift constantly</li></ul><p>That’s like evaluating a portfolio without adjusting for changing market regimes.</p><p>A single Sharpe Ratio across an evolving race is <strong>statistically elegant but contextually blind</strong> — it misses how performance changes across different “market conditions.”</p><h3>The updated version: fuel-adjusted, stint-normalized driver Sharpe ratio</h3><p>So I built a better model: the <strong>Fuel-Adjusted, Stint-Normalized Driver Sharpe Ratio.</strong></p><p>Here’s how it works:<br> 1️⃣ Split each driver’s race into tire stints (soft, medium, hard).<br> 2️⃣ Fit a regression trendline within each stint to model how lap times evolve by accounting for <strong>fuel burn and tire degradation. </strong><br> 3️⃣ Compare each lap to its <em>expected</em> lap time from that trendline.<br> 4️⃣ Compute a Sharpe Ratio within each stint using these residuals (pace advantage ÷ inconsistency).<br> 5️⃣ . Weight each stint by its length (laps driven) to get a final race-level score.</p><p>This removes systemic effects like fuel and tire wear and isolates <strong>pure driver efficiency</strong> under given conditions.</p><p>It’s the racing equivalent of adjusting a financial model for different <strong>volatility regimes by </strong>measuring <em>alpha</em> (skill) after neutralizing <em>beta</em> (the car and environment).</p><h3>Results</h3><p>For this analysis, I&#39;m going to run this model on the Hungarian Grand Prix 2025 to understand the impact of this.</p><p>The actual results of the race:</p><ol><li>Lando Norris</li><li>Oscar Piastri</li><li>George Russell</li><li>Charles Leclerc</li><li>Fernando Alonso</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYP8r0CAoH5Kxd_k3hjf8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXTPEJnMpNDI0G6YX_ZtbA.png" /></figure><p><strong>What this shows:</strong></p><ul><li><strong>Efficiency ≠ Victory<br></strong>Leclerc’s early pace was excellent, but his final-stint degradation tanked his efficiency curve. The fuel-adjusted model <em>reveals</em> (not causes) this collapse — showing why strong starts don’t always compound into efficient finishes.</li><li><strong>Piastri’s Quiet Mastery</strong><br>Piastri outperformed Norris on <em>risk-adjusted</em> metrics — slightly slower on raw pace but more consistent, showing remarkable control under shifting conditions.</li><li><strong>Aggressive Efficiency</strong><br>Lawson’s Sharpe premium highlights efficiency within limitations — extracting near-maximum performance from a midfield car.</li></ul><p>The idea behind the Sharpe Ratio isn&#39;t just about finding out who is the fastest; it&#39;s about finding who was the most efficient by balancing pace, consistency, and adaptability.</p><h3>The learning value</h3><p>Looking at the race through a quantitative finance perspective, it teaches three key lessons:<br> 1️⃣ <strong>Context matters.</strong> Raw speed means little without adjusting for the environment.<br> 2️⃣ <strong>Data ≠ Insight</strong> until normalized. The methodology shapes the interpretation.<br> 3️⃣ <strong>Efficiency translates.</strong> Whether managing a portfolio or a race car, the best performers optimize output per unit of chaos.</p><h3>Future ideas</h3><ul><li><em>Rolling Sharpe Trends:</em> Track “risk-adjusted momentum” across a season.</li><li><em>Team Risk Profiles:</em> Compare McLaren’s consistency curve vs. Ferrari’s volatility.</li><li><em>Season-Adjusted Sharpe:</em> Build a unified, long-term efficiency metric across tracks.</li></ul><p>Yes, on Sunday, the only number that matters is <strong>P1.</strong><br>However, if we zoom out, understanding <em>why</em> someone wins, <em>how</em> they manage risk, and <em>what patterns</em> persist over time, that’s where the real learning lies.</p><p>Investors might be able to make some money, and drivers might be able to win some races, but at the end of the day, only the efficient stay fast in the long run.</p><p>This is part of the <strong>Quant × Sports Series</strong>. <br>Read Part 2→ The Sortino Ratio of a Driver: Measuring Controlled Aggression in F1 (<a href="https://prabhatm27.medium.com/the-sortino-ratio-of-a-driver-measuring-controlled-aggression-in-f1-b2ca4dd0029b">link</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f99c1f32d8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adversarial attacks on neural networks]]></title>
            <link>https://medium.com/devsecops-ai/adversarial-attacks-on-neural-networks-460aaf8ddfb1?source=rss-f0451664d8fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/460aaf8ddfb1</guid>
            <category><![CDATA[ai-security]]></category>
            <category><![CDATA[adversarial-attack]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Prabhat M]]></dc:creator>
            <pubDate>Wed, 29 May 2024 18:09:08 GMT</pubDate>
            <atom:updated>2025-05-13T08:08:43.452Z</atom:updated>
            <content:encoded><![CDATA[<p>Companies coming together to pool data and leverage Artifical Intelligence (AI) models to drive advancements is crucial for the future of everything. As AI continues to evolve, the collaboration between different organizations and industries becomes increasingly vital. By sharing data and insights, companies can overcome reach unprecedented outcomes faster than they would on their own. While there are several directions in protecting the data being shared, protecting the AI model is also very important and interesting to look into.</p><p>This brings us to a critical aspect of AI development: adversarial attacks on neural networks (i.e making sure they are robust and secure). These attacks involve subtly manipulating input data to deceive AI models into making incorrect predictions, posing significant risks across various applications, from healthcare to autonomous driving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mGQVHFqt16R9jTyi" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Importance and widespread use of neural networks</h4><p>Neural networks have revolutionized the field of artificial intelligence, becoming a necessary tool in a great deal of applications. Their importance lies in their ability to learn and generalize from large datasets, making them good at tasks that involve pattern recognition, prediction, and classification. For example, in the healthcare sector, neural networks are employed to analyze medical images, predict patient outcomes, and even discover new drugs.</p><p>The ability of neural networks to handle diverse and complex data types, from text and images to audio and time-series data, enables them to solve problems that were previously impossible. This has led to significant advancements in technology and has opened up new possibilities for innovation and efficiency. As neural networks continue to evolve and improve, their impact on society is set to grow even further, making them a critical area of focus for researchers and practitioners alike. However, with their increasing adoption, it becomes essential to address the vulnerabilities they may possess, particularly the threat posed by adversarial attacks, to ensure their reliable and secure deployment.</p><h4>Introduction to adversarial attacks: definition and significance</h4><p>Adversarial attacks on neural networks are deliberate attempts to manipulate the input data of an AI model in such a way that it causes the model to make incorrect predictions or classifications. These attacks exploit the vulnerabilities within the model’s architecture, taking advantage of the way neural networks process and interpret data. By introducing small, often imperceptible perturbations to the input, adversarial attacks can deceive even the most sophisticated AI systems, leading to potentially catastrophic outcomes.</p><p>The significance of adversarial attacks lies in their ability to undermine the reliability and trustworthiness of AI models, which are increasingly being integrated into critical applications such as healthcare, autonomous driving, and financial services. For instance, an adversarial attack on a medical imaging system could result in a misdiagnosis, while an attack on an autonomous vehicle’s vision system could lead to incorrect navigation decisions, posing serious safety risks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WGYBR5jgyekTdH5g" /><figcaption>Photo by <a href="https://unsplash.com/@gieling?utm_source=medium&amp;utm_medium=referral">Remy Gieling</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background</h3><h4>History of adversarial attacks</h4><p>The history of adversarial attacks on neural networks is relatively recent, emerging alongside the rapid advancements in deep learning and AI. The concept of adversarial examples was first brought to light in the early 2010s, notably by researchers Christian Szegedy and Ian Goodfellow. In 2013, Szegedy and his colleagues published a seminal paper demonstrating that neural networks could be fooled by small, carefully crafted perturbations to input data. This discovery revealed a significant vulnerability in AI models, prompting further investigation into the phenomenon.</p><p>In 2014, Ian Goodfellow and his team introduced the Fast Gradient Sign Method (FGSM), a more efficient technique for generating adversarial examples. FGSM highlighted the ease with which adversarial perturbations could be created, leading to a surge in research focused on understanding and mitigating these attacks. Over the following years, the field expanded rapidly, with researchers exploring various attack strategies.</p><p>The increasing sophistication of adversarial attacks has paralleled the development of more advanced neural network architectures. As AI systems have become more powerful and widely used, the potential impact of adversarial attacks has grown. The evolution of these attacks has also spurred the development of numerous defense mechanisms, from adversarial training to more complex techniques like defensive distillation and input preprocessing.</p><p>Today, the study of adversarial attacks and defenses is a dynamic and crucial field within AI research. The ongoing arms race between attackers and defenders continues to drive innovation, highlighting the need for robust, secure AI systems. Understanding the historical context of adversarial attacks provides valuable insights into their development and the importance of continued vigilance and collaboration in the AI community.</p><h4>Evolution of neural networks and corresponding adversarial techniques</h4><p>The evolution of neural networks has been marked by significant advancements in architecture, training methods, and computational power. Early neural networks, such as perceptrons and simple multilayer perceptrons (MLPs), were limited in their capacity and application. However, the advent of deep learning in the mid-2000s, particularly with the development of convolutional neural networks (CNNs) by Yann LeCun and his team, revolutionized the field. CNNs enabled more effective processing of image data, leading to breakthroughs in computer vision tasks.</p><p>As neural networks grew deeper and more complex, new architectures emerged, including recurrent neural networks (RNNs) and their variants, such as long short-term memory (LSTM) networks, which excelled in sequential data processing. The introduction of generative adversarial networks (GANs) by Ian Goodfellow in 2014 further expanded the capabilities of neural networks, enabling the generation of realistic synthetic data. More recently, transformer models, like those used in language models such as BERT and GPT, have set new benchmarks in natural language processing.</p><p>Alongside these advancements, adversarial techniques have evolved to exploit the growing complexity of neural networks. Initially, simple gradient-based methods like the Fast Gradient Sign Method (FGSM) demonstrated the vulnerability of neural networks to small perturbations. As defenses against these attacks improved, adversarial techniques also became more sophisticated. Attack methods such as the Basic Iterative Method (BIM) and Projected Gradient Descent (PGD) introduced iterative approaches to refine adversarial perturbations.</p><p>Black-box attack methods, which do not require knowledge of the model’s internal parameters, are also advanced. Techniques like Zeroth Order Optimization (ZOO) and transfer-based attacks, where adversarial examples crafted on one model are used to attack another, highlighted the robustness of adversarial strategies. Furthermore, advancements in generative models have led to the creation of more subtle and effective adversarial examples, capable of bypassing many existing defenses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S8wQXQAh5G16xbD9" /><figcaption>Photo by <a href="https://unsplash.com/@jjying?utm_source=medium&amp;utm_medium=referral">JJ Ying</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Types of Adversarial Attacks</h3><h4>White-box attacks</h4><p>White-box attacks are a type of adversarial attack where the attacker has complete knowledge of the target neural network, including its architecture, parameters, and training data. This level of access allows the attacker to exploit the model’s vulnerabilities with precision, making these attacks highly effective. The key characteristic of white-box attacks is the ability to use detailed information about the model to generate adversarial examples that can fool the network into making incorrect predictions or classifications.</p><p>White-box attacks typically involve calculating the gradients of the loss function with respect to the input data. By understanding how changes in the input affect the model’s output, attackers can craft small perturbations that are imperceptible to humans but significantly impact the model’s performance. These attacks leverage optimization techniques to fine-tune these perturbations, ensuring they are as subtle as possible while still achieving the desired effect.</p><h4>Examples</h4><ol><li><strong>Fast Gradient Sign Method (FGSM)</strong></li></ol><ul><li>Generates adversarial examples by adding a perturbation in the direction of the gradient of the loss function.</li><li>Formula: 𝑥′=𝑥+𝜖⋅sign(∇𝑥𝐽(𝜃,𝑥,𝑦))</li></ul><p><strong>2. Projected Gradient Descent (PGD)</strong></p><ul><li>An iterative method that refines adversarial examples by repeatedly updating the input with gradient-based perturbations.</li><li>Formula: 𝑥tₒ+1=Proj𝑥+𝑆(𝑥𝑡+𝛼⋅sign(∇𝑥𝑡𝐽(𝜃,𝑥𝑡,𝑦)))</li></ul><p><strong>3. Basic Iterative Method (BIM)</strong></p><ul><li>An extension of FGSM that applies the attack multiple times with smaller step sizes.</li><li>Iteratively adjusts the input: 𝑥𝑡+1=Clip𝑥,𝜖(𝑥𝑡+𝛼⋅sign(∇𝑥𝑡𝐽(𝜃,𝑥𝑡,𝑦)))</li></ul><p><strong>4. Carlini &amp; Wagner (C&amp;W) Attack</strong></p><ul><li>Optimizes perturbations using a more complex objective function to produce imperceptible adversarial examples.</li><li>Solves a targeted optimization problem to minimize perturbation while ensuring misclassification.</li></ul><p><strong>5. DeepFool</strong></p><ul><li>Iteratively projects the input towards the decision boundary to find minimal perturbations that change the classification.</li><li>Provides a fine-grained approach to generating adversarial examples with minimal distortion.</li></ul><p><strong>6. Jacobian-based Saliency Map Attack (JSMA)</strong></p><ul><li>Uses the Jacobian matrix to identify the most influential pixels and perturb them selectively.</li><li>Focuses on crafting perturbations that target specific features important to the model’s decision-making.</li></ul><h4>Black-box attacks</h4><p>Black-box attacks are a type of adversarial attack where the attacker does not have direct access to the target neural network’s internal parameters, architecture, or training data. Instead, the attacker can only observe the inputs and outputs of the model. This scenario mimics real-world conditions where the inner workings of the model are often proprietary or inaccessible. Despite these limitations, black-box attacks can be highly effective by leveraging techniques such as query-based methods or transferability of adversarial examples.</p><p>Black-box attacks rely on creating adversarial examples by iteratively querying the target model and analyzing its responses. This can involve approximating the model’s gradients using numerical methods or exploiting patterns in the model’s output. Additionally, attackers can use transfer-based methods, where adversarial examples generated for one model (the surrogate model) are used to attack the target model, taking advantage of the similarity in decision boundaries across different models.</p><h4>Examples</h4><ol><li><strong>Zeroth Order Optimization (ZOO)</strong></li></ol><ul><li>ZOO is a gradient-free optimization method used for black-box attacks. It estimates the gradient of the loss function by querying the target model with slightly perturbed inputs.</li><li>The method iteratively refines the adversarial example by approximating the gradient through finite differences, allowing effective attacks without direct gradient access.</li></ul><p><strong>2. Transfer-based Attacks</strong></p><ul><li>These attacks leverage the transferability property of adversarial examples, where an adversarial example crafted for one model can also fool another model with similar architecture or trained on similar data.</li><li>Attackers generate adversarial examples using a surrogate model and then apply these examples to the target model, achieving high success rates even without direct access to the target.</li></ul><p><strong>3. Query-based Black-box Attacks</strong></p><ul><li>This method involves sending numerous queries to the target model and using the outputs to construct adversarial examples. Techniques like the Boundary Attack iteratively modify a benign input towards the adversarial example by only using model outputs.</li><li>Another example is the SimBA (Simple Black-box Attack), which perturbs random pixel groups and selects modifications that increase the loss, requiring fewer queries compared to other methods.</li></ul><p><strong>4. GenAttack</strong></p><ul><li>GenAttack uses genetic algorithms to evolve adversarial examples. It treats the adversarial example generation as an optimization problem, iteratively refining candidates through mutation and selection based on the model’s outputs.</li><li>This approach is highly effective for black-box scenarios as it does not rely on gradient information.</li></ul><h4>Targeted vs. Non-targeted Attacks</h4><p>Adversarial attacks on neural networks can be classified into two main categories: targeted and non-targeted attacks. The primary distinction between these types lies in the attacker’s objective regarding the model’s output.</p><p><strong>Targeted Attacks</strong></p><ul><li>In targeted attacks, the attacker aims to mislead the neural network into classifying an input as a specific, incorrect target class. The adversarial example is crafted to cause the model to produce a predetermined wrong output, regardless of the original input’s true label.</li><li>The goal is to make the model predict a specific class, such as changing a correctly classified image of a cat to be classified as a dog.</li><li>Targeted attacks are often more challenging to execute because they require the perturbations to steer the model’s output towards a specific incorrect label.</li></ul><p><strong>Non-targeted Attacks</strong></p><ul><li>In non-targeted attacks, the attacker’s objective is simply to cause the neural network to make any incorrect prediction. The adversarial example does not aim for a specific wrong class but seeks to push the model away from the correct output.</li><li>The goal is to ensure that the model’s prediction is wrong, such as changing a correctly classified image of a cat to be classified as anything but a cat.</li><li>Non-targeted attacks are generally easier to achieve since the perturbations only need to cause a misclassification without targeting a specific incorrect label.</li></ul><h4>Examples and Scenarios</h4><p><strong>Targeted Attack Examples:</strong></p><ol><li>Carlini &amp; Wagner (C&amp;W) Attack</li><li>Projected Gradient Descent (PGD)</li></ol><p><strong>Non-targeted Attack Examples:</strong></p><ol><li>Fast Gradient Sign Method (FGSM)</li><li>DeepFool</li></ol><h3>Mechanisms of Adversarial Attacks</h3><h4>Mathematical Foundations</h4><p>The mathematical foundations of adversarial attacks lie in the optimization and manipulation of input data to exploit the vulnerabilities of neural networks. At the core of these attacks is the idea of finding small perturbations that, when added to the input data, can cause a significant change in the output of the model. This process involves computing the gradient of the loss function with respect to the input and using this gradient to craft adversarial examples.</p><h4>Techniques and Algorithms Used</h4><ol><li><strong>Gradient-based Methods: </strong>These methods involve calculating the gradient of the loss function concerning the input data to identify the direction in which to perturb the input.</li></ol><ul><li><strong>Fast Gradient Sign Method (FGSM):</strong> Uses the sign of the gradient to generate perturbations</li><li><strong>Projected Gradient Descent (PGD):</strong> Iteratively applies FGSM and projects the perturbed input back to the allowed range</li></ul><p><strong>2. Optimization-based Methods: </strong>These methods frame the generation of adversarial examples as an optimization problem, aiming to minimize the perturbation while ensuring misclassification.</p><ul><li><strong>Carlini &amp; Wagner (C&amp;W) Attack:</strong> Optimizes a custom objective function to find the smallest possible perturbation that causes misclassification.</li></ul><p><strong>3. Black-box Methods: </strong>Without access to model internals, these methods rely on querying the model and using its outputs to approximate gradients or transfer adversarial examples from surrogate models.</p><ul><li><strong>Zeroth Order Optimization (ZOO): </strong>Estimates gradients using finite differences and optimizes perturbations accordingly.</li><li><strong>Transfer-based Attacks: </strong>Use adversarial examples generated on a surrogate model to attack the target model.</li></ul><h4>How Adversarial Perturbations are Generated</h4><p>Adversarial perturbations are generated by first calculating the gradient of the loss function with respect to the input data. This gradient indicates how changes to the input will affect the loss. Using this information, attackers apply small but strategically chosen perturbations to the input, with the objective of maximizing the model’s prediction error. Techniques like FGSM and PGD iteratively adjust the input in the direction that increases the loss, creating adversarial examples that are close to the original input but cause the model to produce incorrect outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cB3lgJdBsSY5Fgn8" /><figcaption>Photo by <a href="https://unsplash.com/@pyssling240?utm_source=medium&amp;utm_medium=referral">Thomas T</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Real-world Examples and Case Studies</h3><ol><li><strong>Autonomous Vehicles: </strong>Researchers have demonstrated that small perturbations in road signs, such as adding stickers or subtle graffiti, can cause neural networks in autonomous vehicles to misinterpret the signs, leading to dangerous situations. For example, a stop sign could be misclassified as a yield sign.</li><li><strong>Medical Imaging: </strong>In the healthcare domain, adversarial attacks on medical imaging systems have shown that slight modifications to medical scans can lead to misdiagnoses. For instance, adding small perturbations to a mammogram could cause a benign tumor to be classified as malignant, or vice versa.</li><li><strong>Financial Systems: </strong>Adversarial attacks on financial models used for fraud detection can manipulate transaction data to bypass detection systems. Attackers can subtly alter transaction details to make fraudulent transactions appear legitimate.</li></ol><h3>Impacts and Consequences</h3><h4>Impact on Model Performance</h4><p>Adversarial attacks have a profound impact on the performance of neural network models. By introducing carefully crafted perturbations, these attacks can significantly degrade the accuracy and reliability of AI systems. Even minor perturbations, often imperceptible to human observers, can cause models to make incorrect predictions with high confidence. This undermines the model’s utility, especially in critical applications where accuracy is paramount.</p><p>An important point to be noted is that adversarial inputs can affect the model in such a way that its function on normal inputs would get affected because:</p><ul><li>The model may start recognizing and responding to adversarial patterns, which can degrade its performance on legitimate inputs. It learns to react to patterns that do not generalize to real-world data.</li><li>Training or repeatedly exposing the model to adversarial inputs can cause it to misclassify normal inputs, reducing overall accuracy and reliability.</li><li>The model might become uncertain or inconsistent in its predictions, even with normal inputs, as it tries to differentiate between genuine and adversarial inputs.</li></ul><h4>Security Implications</h4><p>The security implications of adversarial attacks are far-reaching. These attacks expose inherent vulnerabilities in neural networks, making them susceptible to manipulation and exploitation. In security-sensitive environments, such as authentication systems, adversarial attacks can be used to bypass protective measures, leading to unauthorized access. The ability to subtly alter inputs to deceive AI models poses significant risks, highlighting the necessity for robust security protocols and defense mechanisms. As AI continues to integrate into critical infrastructure, the potential for adversarial attacks to cause disruption and harm becomes a pressing concern.</p><h3>Defense Mechanisms</h3><h4>Adversarial Training</h4><p>Adversarial training is one of the most widely used defense mechanisms against adversarial attacks. The process involves augmenting the training dataset with adversarial examples, allowing the neural network to learn to recognize and resist these perturbations. During training, the model is exposed to both clean and adversarially modified inputs, with the goal of minimizing the loss on both types of data. This method effectively enhances the model’s robustness by teaching it to correctly classify adversarial examples.</p><p><strong>Examples and Case Studies</strong></p><ul><li><strong>MNIST and CIFAR-10:</strong> Adversarial training has been successfully implemented on standard datasets like MNIST and CIFAR-10. For instance, training models on adversarial examples generated using FGSM and PGD have shown significant improvements in robustness against these attacks.</li><li><strong>Industrial Applications:</strong> In practical applications, adversarial training has been used to harden image recognition systems in autonomous vehicles and enhance the security of financial fraud detection models.</li></ul><h4>Defensive Distillation</h4><p>Defensive distillation is a technique designed to reduce the sensitivity of neural networks to adversarial perturbations. The process involves training a neural network at a high temperature to produce softer probability distributions for each class. A second network, the distilled model, is then trained on these softened labels. This training process smooths the decision boundaries of the model, making it more difficult for adversarial examples to cause misclassifications.</p><p><strong>Advantages:</strong></p><ul><li><strong>Robustness:</strong> Defensive distillation can significantly improve the robustness of neural networks against certain types of adversarial attacks.</li><li><strong>Implementation:</strong> It can be relatively straightforward to implement as it builds on the standard training process.</li></ul><p><strong>Limitations:</strong></p><ul><li><strong>Attack Specificity:</strong> Some advanced attacks can still circumvent defensive distillation, particularly if they exploit specific weaknesses in the model.</li><li><strong>Computational Overhead: </strong>The distillation process can be computationally intensive, requiring additional training time and resources.</li></ul><h4>Other Defense Techniques</h4><p><strong>Gradient Masking, Input Preprocessing, Model Ensembling</strong></p><ol><li><strong>Gradient Masking:</strong> Gradient masking involves obscuring the gradients used to generate adversarial examples, making it harder for attackers to find effective perturbations. While it can thwart some gradient-based attacks, it may not be effective against all attack types and can sometimes lead to a false sense of security.</li><li><strong>Input Preprocessing: </strong>This approach involves transforming the input data to remove potential adversarial perturbations before feeding it into the model. Common methods include image cropping, resizing, denoising, and applying transformations such as Gaussian blurring. Input preprocessing can reduce the success rate of adversarial attacks but may also affect the accuracy of the model on clean data.</li><li><strong>Model Ensembling: </strong>Ensembling involves using multiple models and combining their predictions to improve robustness. Different models may have different vulnerabilities, so an ensemble can mitigate individual weaknesses. Ensembling can enhance robustness and accuracy but increases computational requirements.</li></ol><h4>Comparative Analysis of Different Techniques</h4><p>Each defense mechanism offers unique advantages and faces specific challenges:</p><ul><li><strong>Adversarial Training: </strong>Provides robust defense by exposing the model to adversarial examples during training, but it can be computationally expensive and may not generalize well to unseen attack types.</li><li><strong>Defensive Distillation:</strong> Smooths decision boundaries and improves robustness against some attacks, but can be circumvented by sophisticated attacks and requires additional training steps.</li><li><strong>Gradient Masking: </strong>Obscures gradients to protect against gradient-based attacks, but may not be effective against black-box or optimization-based attacks.</li><li><strong>Input Preprocessing:</strong> Removes perturbations before inputting data into the model, effective for certain attacks but may degrade model performance on clean data.</li><li><strong>Model Ensembling:</strong> Combines multiple models to enhance robustness, effective but computationally intensive.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k0dOEM44C4dqE5Bt" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Current Research and Future Directions</h3><h4>Latest Advancements in Adversarial Attack Techniques</h4><p>Recent research in adversarial attacks has focused on developing more sophisticated and resilient methods to bypass existing defenses. Key advancements include:</p><ul><li><strong>Adaptive Attacks:</strong> These attacks dynamically adjust their strategies based on the defenses in place, making them more challenging to counter. They analyze the defense mechanisms and adapt their perturbations to maximize effectiveness.</li><li><strong>Universal Adversarial Perturbations:</strong> Researchers have developed perturbations that can fool a wide range of models and inputs. These universal perturbations highlight the broad vulnerability of neural networks across different tasks and datasets.</li><li><strong>Black-box Optimization Techniques: </strong>Advances in black-box attacks, such as Zeroth Order Optimization (ZOO) and evolutionary algorithms, have improved the efficiency and success rates of attacks without needing access to model internals.</li><li><strong>Physical-world Attacks:</strong> There has been significant progress in creating adversarial examples that work in the real world, such as perturbations that remain effective when printed on physical objects or captured in photographs.</li></ul><h4>Emerging Defense Strategies</h4><p>To counter the evolving threat landscape, new defense strategies are being developed:</p><ul><li><strong>Certified Defenses: </strong>These approaches provide mathematical guarantees on the robustness of models against certain types of adversarial perturbations. Techniques like randomized smoothing offer probabilistic robustness guarantees.</li><li><strong>Adversarial Example Detection: </strong>Developing methods to detect adversarial inputs before they reach the model. These include anomaly detection techniques and auxiliary networks trained to identify perturbations.</li><li><strong>Robust Optimization: </strong>Training models with robust optimization techniques that directly minimize the worst-case loss over a range of possible adversarial perturbations.</li><li><strong>Neural Architecture Search (NAS): </strong>Using automated search methods to design neural architectures that are inherently more robust to adversarial attacks.</li></ul><h4>Research Gaps and Challenges</h4><p>Despite significant progress, several challenges and gaps remain:</p><ul><li><strong>Scalability: </strong>Many defense mechanisms are computationally intensive and may not scale well to large, real-world datasets and models.</li><li><strong>Generalizability: </strong>Defenses often fail to generalize across different types of attacks and datasets. A defense robust to one attack may be vulnerable to another.</li><li><strong>Trade-offs: </strong>There is often a trade-off between robustness and model performance on clean data. Balancing security and accuracy remains a critical challenge.</li><li><strong>Evaluation Metrics: </strong>The lack of standardized metrics and benchmarks for evaluating adversarial robustness complicates the comparison of different defense strategies.</li></ul><h4>Future Trends</h4><p>Looking ahead, several trends and predictions shape the future of adversarial attacks and defenses:</p><ul><li><strong>Integration of AI Security in Development: </strong>As awareness of adversarial threats grows, security will become a more integral part of AI model development and deployment processes.</li><li><strong>Collaborative Research Efforts: </strong>Increased collaboration between academia, industry, and government organizations will drive the development of more robust and standardized defense mechanisms.</li><li><strong>Advances in Explainability: </strong>Improved explainability and interpretability of neural networks will help identify vulnerabilities and develop more effective defenses.</li><li><strong>Regulatory and Ethical Considerations:</strong> The development of regulatory frameworks and ethical guidelines for AI security will become increasingly important, ensuring that AI systems are both safe and trustworthy.</li><li><strong>Hybrid Defense Approaches: </strong>Combining multiple defense strategies to create more resilient AI systems will become the norm. This hybrid approach can address the limitations of individual methods and offer comprehensive protection.</li></ul><p>As the field of adversarial attacks and defenses continues to evolve, staying ahead of potential threats requires ongoing innovation, collaboration, and a proactive approach to AI security. By addressing current challenges and anticipating future trends, researchers and practitioners can enhance the robustness and reliability of neural networks in diverse applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*flqq98tK6i_a2DYU" /><figcaption>Photo by <a href="https://unsplash.com/@bendavisual?utm_source=medium&amp;utm_medium=referral">Benjamin Davies</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Practical Considerations</h3><ol><li><strong>Incorporate Adversarial Training:</strong> Regularly include adversarial examples in the training process to improve model robustness. This practice helps the model learn to recognize and resist perturbations.</li><li><strong>Implement Layered Defenses:</strong> Use a combination of defense mechanisms, such as adversarial training, input preprocessing, and model ensembling, to provide multiple layers of protection against different attack vectors.</li><li><strong>Regularly Update Models:</strong> Continuously monitor and update models to address new vulnerabilities and incorporate the latest defense strategies.</li><li><strong>Conduct Thorough Testing: </strong>Perform rigorous testing of models under various adversarial scenarios to evaluate and improve robustness. Include both known and novel attack methods in testing protocols.</li><li><strong>Promote Transparency: </strong>Maintain transparency in model development and deployment processes. Share information about the robustness measures in place and any vulnerabilities discovered to build trust and foster collaboration.</li></ol><p>By adopting these practical considerations, practitioners can enhance the robustness and security of their AI systems, ensuring they are prepared to defend against adversarial attacks.</p><h3>Conclusion</h3><h4>Summary of Key Points</h4><p>In this article, we have explored the multifaceted nature of adversarial attacks on neural networks, covering their definitions, mechanisms, and the various defense strategies employed to counter them. We began by discussing the importance of collaboration in advancing AI technology while highlighting the need to focus on both data sharing and model robustness. We delved into the different types of adversarial attacks, including white-box and black-box attacks, and provided examples and scenarios to illustrate their impact. We examined the mathematical foundations and techniques used in these attacks, along with real-world examples demonstrating their potential consequences in domains such as healthcare, autonomous driving, and finance. Defense mechanisms such as adversarial training, defensive distillation, and other techniques were discussed, highlighting their effectiveness and limitations. Finally, we considered the latest research advancements, emerging defense strategies, and the importance of ethical considerations in building secure AI systems.</p><h4>Importance of Ongoing Research and Vigilance</h4><p>The field of adversarial attacks and defenses is dynamic, with continuous advancements posing new challenges and opportunities. Ongoing research is crucial for staying ahead of adversarial threats and developing more robust and resilient AI systems. Vigilance in monitoring, updating, and testing AI models is essential to ensure their security and reliability. Collaborative efforts between academia, industry, and policymakers are necessary to establish standardized guidelines and best practices for AI security. By maintaining a proactive approach and fostering a culture of transparency and ethical responsibility, we can mitigate the risks associated with adversarial attacks and enhance the trustworthiness of AI technologies.</p><h4>Final Thoughts on the Balance Between Innovation and Security</h4><p>Balancing innovation and security is a critical challenge in the advancement of AI. While the development of new and powerful AI models drives progress and opens up new possibilities, it also introduces vulnerabilities that must be addressed. Ensuring the security of these models against adversarial attacks requires a concerted effort to integrate robust defense mechanisms without stifling innovation. By adopting best practices, leveraging advanced tools and libraries, and adhering to ethical guidelines, practitioners can create AI systems that are both cutting-edge and secure. The journey towards robust and trustworthy AI is ongoing, and it demands a careful balance between pushing the boundaries of what is possible and safeguarding against potential threats. Through continuous research, collaboration, and a commitment to responsible AI practices, we can achieve this balance and build a future where AI technologies benefit society while maintaining their integrity and security.</p><h3>References</h3><ol><li>Szegedy, C., Zaremba, W., Sutskever, I., Bruna, J., Erhan, D., Goodfellow, I., &amp; Fergus, R. (2013). Intriguing properties of neural networks. <a href="https://arxiv.org/abs/1312.6199">arXiv preprint arXiv:1312.6199</a>.</li><li>Goodfellow, I. J., Shlens, J., &amp; Szegedy, C. (2014). Explaining and harnessing adversarial examples. <a href="https://arxiv.org/abs/1412.6572">arXiv preprint arXiv:1412.6572</a>.</li><li>Kurakin, A., Goodfellow, I., &amp; Bengio, S. (2016). Adversarial examples in the physical world. <a href="https://arxiv.org/abs/1607.02533">arXiv preprint arXiv:1607.02533</a>.</li><li>Madry, A., Makelov, A., Schmidt, L., Tsipras, D., &amp; Vladu, A. (2017). Towards deep learning models resistant to adversarial attacks. <a href="https://arxiv.org/abs/1706.06083">arXiv preprint arXiv:1706.06083</a>.</li><li>Papernot, N., McDaniel, P., Goodfellow, I., Jha, S., Celik, Z. B., &amp; Swami, A. (2016). Practical black-box attacks against machine learning. Proceedings of the 2017 ACM on Asia Conference on Computer and Communications Security (pp. 506–519).</li><li>Carlini, N., &amp; Wagner, D. (2017). Towards evaluating the robustness of neural networks. <a href="https://ieeexplore.ieee.org/document/7958570">2017 IEEE Symposium on Security and Privacy (SP) (pp. 39–57)</a>.</li><li>Moosavi-Dezfooli, S.-M., Fawzi, A., &amp; Frossard, P. (2016). DeepFool: A simple and accurate method to fool deep neural networks. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR) (pp. 2574–2582).</li><li>Papernot, N., McDaniel, P., Wu, X., Jha, S., &amp; Swami, A. (2016). Distillation as a defense to adversarial perturbations against deep neural networks. <a href="https://ieeexplore.ieee.org/document/7546524">2016 IEEE Symposium on Security and Privacy (SP) (pp. 582–597)</a>.</li><li>Tramèr, F., Kurakin, A., Papernot, N., Goodfellow, I., Boneh, D., &amp; McDaniel, P. (2017). Ensemble adversarial training: Attacks and defenses. <a href="https://arxiv.org/abs/1705.07204">arXiv preprint arXiv:1705.07204</a>.</li><li>Athalye, A., Carlini, N., &amp; Wagner, D. (2018). Obfuscated gradients give a false sense of security: Circumventing defenses to adversarial examples. <a href="https://arxiv.org/abs/1802.00420">arXiv preprint arXiv:1802.00420</a>.</li><li>Su, J., Vargas, D. V., &amp; Sakurai, K. (2019). One pixel attack for fooling deep neural networks. <a href="https://ieeexplore.ieee.org/document/8418594">IEEE Transactions on Evolutionary Computation, 23(5), 828–841</a>.</li><li>Croce, F., &amp; Hein, M. (2020). Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks. <a href="https://arxiv.org/abs/2003.01690">arXiv preprint arXiv:2003.01690</a>.</li><li>Biggio, B., Corona, I., Maiorca, D., Nelson, B., Šrndić, N., Laskov, P., Giacinto, G., &amp; Roli, F. (2013). Evasion attacks against machine learning at test time. <a href="https://link.springer.com/chapter/10.1007/978-3-642-40994-3_25">In Joint European Conference on Machine Learning and Knowledge Discovery in Databases (pp. 387–402). Springer, Berlin, Heidelberg</a>.</li><li>Yan, Q., Zheng, Y., Ji, S., Zhang, H., Li, W., &amp; Deng, R. H. (2019). Deep Neural Networks on Mobile Devices: Towards Fast and Energy-Efficient Machine Learning for Mobile AI. <a href="https://ieeexplore.ieee.org/document/8736011">IEEE Transactions on Mobile Computing, 19(5), 1156–1174</a>.</li><li>Xu, W., Evans, D., &amp; Qi, Y. (2018). Feature squeezing: Detecting adversarial examples in deep neural networks. Proceedings of the Network and Distributed System Security Symposium (NDSS).</li><li>Kannan, H., Kurakin, A., &amp; Goodfellow, I. (2018). Adversarial logit pairing. <a href="https://arxiv.org/abs/1803.06373">arXiv preprint arXiv:1803.06373</a>.</li><li>Pang, T., Xu, K., Du, C., Chen, N., &amp; Zhu, J. (2018). Improving adversarial robustness via promoting ensemble diversity. <a href="https://arxiv.org/abs/1901.08846">arXiv preprint arXiv:1901.08846</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=460aaf8ddfb1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsecops-ai/adversarial-attacks-on-neural-networks-460aaf8ddfb1">Adversarial attacks on neural networks</a> was originally published in <a href="https://medium.com/devsecops-ai">DevSecOps &amp; AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Triage Management in Healthcare: Harnessing the Hybrid Approach of Neurosymbolic AI for…]]></title>
            <link>https://prabhatm27.medium.com/enhancing-triage-management-in-healthcare-harnessing-the-hybrid-approach-of-neurosymbolic-ai-for-efed9f8ae2d0?source=rss-f0451664d8fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/efed9f8ae2d0</guid>
            <category><![CDATA[neurosymbolic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[healthcare]]></category>
            <dc:creator><![CDATA[Prabhat M]]></dc:creator>
            <pubDate>Fri, 16 Jun 2023 19:04:15 GMT</pubDate>
            <atom:updated>2023-06-16T19:04:15.739Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enhancing Triage Management in Healthcare: Harnessing the Hybrid Approach of Neurosymbolic AI for Efficient Disease Classification</h3><h3><strong>Abstract</strong></h3><p>Accurate disease prediction and efficient triage management play a vital role in healthcare settings. This article introduces a hybrid approach that integrates neural networks and symbolic reasoning techniques to enhance disease classification and triage management. The neurosymbolic AI system harnesses the computational power of neural networks to extract patterns from data and analyze symptom severity while employing symbolic reasoning to leverage predefined rules and establish relationships between symptoms and diseases. By utilizing a knowledge graph constructed from disease-symptom relationships, the model provides comprehensive rule-based explanations for predictions and informed recommendations. The findings demonstrate the significant potential of this hybrid approach in significantly improving healthcare outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99NFU6r1p-fc_FnZQS1vOw.jpeg" /></figure><h3>Introduction</h3><p>In healthcare, disease prediction, and triage management are really important components for delivering timely and effective care to patients. However, accurately diagnosing and prioritizing patients can be challenging due to the complexity of diseases and the need for swift decision-making. Traditional methods often struggle to capture the intricate relationships between symptoms and diseases, resulting in suboptimal outcomes. Fortunately, neurosymbolic AI offers a promising solution by integrating the strengths of neural networks and symbolic reasoning. This fusion allows for improved disease classification and triage management, while also providing a transparent and interpretable framework. By combining neural networks’ ability to detect complex patterns in patient data with symbolic reasoning’s representation of medical knowledge, neurosymbolic AI enables healthcare professionals to understand the underlying rationale behind its predictions. This fosters trust, and collaboration, and ultimately leads to better patient outcomes as informed decisions can be made based on the explainable outputs of neurosymbolic AI.</p><h3>Inspiration &amp; Motivation</h3><p>The inspiration behind this project comes from the growing need for accurate disease prediction and efficient triage management in healthcare. Traditional approaches to disease classification and triage often face challenges in accurately capturing complex relationships between symptoms and diseases, leading to suboptimal outcomes. The rapid advancements in artificial intelligence (AI) and machine learning have provided new avenues for addressing these challenges. In particular, the emergence of neurosymbolic AI, which combines the strengths of neural networks and symbolic reasoning, presents a unique opportunity to overcome the limitations of traditional approaches. By integrating the computational power of neural networks with the interpretability and logical reasoning capabilities of symbolic reasoning, neurosymbolic AI offers a promising framework to enhance disease prediction accuracy and facilitate effective triage management, at the same time providing an interpretable and explainable framework to help the user and healthcare professionals understand the predictions. This project seeks to leverage the potential of neurosymbolic AI to revolutionize disease classification and triage, ultimately improving healthcare outcomes for individuals worldwide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8OIOPYbiaK-qk8ovfGcYw.jpeg" /></figure><h3>Brief Explanation of the System:</h3><p>The neurosymbolic AI system contains two main components: a neural part and a symbolic component.</p><p>In the system, neural networks are used to analyze large amounts of data and learn complex patterns, while symbolic reasoning relies on predefined rules and relationships between symptoms and diseases. By integrating these two approaches, the system aims to enhance the accuracy and interpretability of disease classification and triage decisions.</p><p>The hybrid model takes the patient symptoms as the input.</p><ul><li>The neural network component learns patterns from the training data and aanalyzes the severity of symptoms.</li><li>The symbolic reasoning layer uses a knowledge graph from disease-symptom relationships to infer the most likely disease.</li></ul><p>The model provides predictions for both disease classification and triage priority. It generates explanations (rule based and other explanations as well) based on the entered symptoms, helping both the users and the healthcare professionals understand the reasoning behind the predictions. The system also identifies the most important symptoms for the prediction and provides a neurosymbolic explanation of how the neural network and symbolic reasoning components contribute to the final prediction. The goal is to optimize patient care by accurately predicting diseases and prioritizing urgent cases for immediate attention, at the same time providing an explanation to explain how the disease is being predicted</p><h3>About the Dataset:</h3><p>To train the hybrid model, we will be using a comprehensive dataset consisting of disease-symptom relationships, symptom severity, disease description, symptom description, and disease precaution is collected. I have used the dataset from this website: <a href="https://www.kaggle.com/datasets/itachi9604/disease-symptom-description-dataset">https://www.kaggle.com/datasets/itachi9604/disease-symptom-description-dataset</a> and another private dataset that I generated which has the explanations of each symptom.</p><p>For any Artificial Intelligence system, the data is one of the most important parts, and it is vital that this data is properly processed and cleaned. Cleaning, normalization, and encoding techniques are applied to prepare the data for training. Challenges in data collection, such as missing or inconsistent information, are addressed through validation and imputation methods. These preprocessing steps ensure consistent formatting ensure that the data is clean, organized, and ready for further analysis and modeling tasks.</p><h3>Steps:</h3><ol><li><strong>Data Collection &amp; Preprocessing</strong></li><li><strong>Building the Hybrid Model</strong></li><li><strong>Obtaining Prediction, Explanation, Triage Priority, and Verdict</strong></li><li><strong>Displaying the output to the user</strong></li></ol><h3>Step 1: <strong>Data collection &amp; Preprocessing</strong></h3><p>To train the hybrid model, a comprehensive dataset consisting of disease-symptom relationships, symptom severity, disease description, symptom description, and disease precaution is collected. I have used the dataset from this website: <a href="https://www.kaggle.com/datasets/itachi9604/disease-symptom-description-dataset">https://www.kaggle.com/datasets/itachi9604/disease-symptom-description-dataset</a>z</p><h3>Code:</h3><h4>1. Installing &amp; importing the necessary libraries:</h4><p>The code imports several libraries to support the implementation of this neurosymbolic AI system.</p><pre># Input data files are available in the read-only &quot;../input/&quot; directory<br># For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory<br><br>import os<br>for dirname, _, filenames in os.walk(&#39;/kaggle/input&#39;):<br>    for filename in filenames:<br>        print(os.path.join(dirname, filename))<br><br>import pandas as pd<br>import numpy as np<br>import tensorflow as tf<br>from tensorflow import keras<br>from tensorflow.keras import layers, Model<br>import networkx as nx</pre><h4>2. Importing the data</h4><p>This code imports all the datasets available: <strong>symptom_severity_df, disease_symptom_df, disease_description_df , disease_precaution_df </strong>and<strong> symptom_explanation_df.</strong></p><pre># Load the datasets<br>symptom_severity_df = pd.read_csv(&#39;/kaggle/input/disease-symptom-description-dataset/Symptom-severity.csv&#39;)<br>disease_symptom_df = pd.read_csv(&#39;/kaggle/input/disease-symptom-description-dataset/dataset.csv&#39;)<br>disease_description_df = pd.read_csv(&#39;/kaggle/input/disease-symptom-description-dataset/symptom_Description.csv&#39;)<br>disease_precaution_df = pd.read_csv(&#39;/kaggle/input/disease-symptom-description-dataset/symptom_precaution.csv&#39;)<br>symptom_explanation_df = pd.read_csv(&#39;/kaggle/input/symptom-explanation/Symptom explanation.csv&#39;)</pre><ul><li><strong>Symptom severity.csv</strong>: contains information about the symptoms and their given severity rating, ranging from 1 to 7</li><li><strong>dataset.csv</strong>: contains diseases and their symptoms, there are over 500 diseases and their associated symptoms existing</li><li><strong>symptom_Description.csv</strong>: contains the description of each of the diseases</li><li><strong>symptom_precaution.csv</strong>: contains all the precautions for each of the diseases</li><li><strong>Symptom explanation.csv</strong>: contains the explanation of each symptom</li></ul><h4>3. Data Preprocessing</h4><p>These are the steps for processing and cleaning the data before converting it into input for the hybrid model.</p><pre># Incorporate symptom severity<br>symptom_severity_dict = dict(zip(symptom_severity_df[&#39;Symptom&#39;], symptom_severity_df[&#39;weight&#39;]))<br><br># Create a dictionary to map symptoms to their indices<br>symptom_to_index = {symptom: index for index, symptom in enumerate(symptom_severity_dict.keys())}<br><br># Remove leading and trailing spaces from disease names in the disease_symptom_df dataset<br>disease_symptom_df[&#39;Disease&#39;] = disease_symptom_df[&#39;Disease&#39;].str.strip()<br>disease_symptom_df = disease_symptom_df.applymap(lambda x: x.strip() if isinstance(x, str) else x)<br><br># Remove leading and trailing spaces from disease names in teh disease_precaution_df dataset<br>disease_precaution_df[&#39;Disease&#39;] = disease_precaution_df[&#39;Disease&#39;].str.strip()<br><br># Remove leading and trailing spaces from disease names in the disease_description_df dataset<br>disease_description_df[&#39;Disease&#39;] = disease_description_df[&#39;Disease&#39;].str.strip()<br><br>disease_symptom_dup = disease_symptom_df.drop_duplicates()<br><br># Function to capitalize words and remove underscores<br>capitalize_and_remove_underscore = lambda x: x.title().replace(&#39;_&#39;, &#39;&#39;)<br>disease_precaution_df = disease_precaution_df.fillna(&#39;&#39;)</pre><p><strong>Create a dictionary for symptom severity: </strong>Creates a dictionary called symptom_severity_dict using the symptom severity dataset which maps each symptom to its corresponding severity weight</p><p><strong>Create a dictionary for symptom indices:</strong> The code creates a dictionary called symptom_to_index to map each symptom to its index. It iterates over the keys of symptom_severity_dict and assigns each symptom to its corresponding index in the dictionary.</p><p><strong>Remove leading and trailing spaces from disease names: </strong>The code removes any leading and trailing spaces from the disease names in the disease_symptom_df dataset using the str.strip() function. The same operation is performed on all columns of the data frame using the applymap function and a lambda function. The next line removes leading and trailing spaces from the disease names in the disease_precaution_df dataset. The next line removes leading and trailing spaces from the disease names in the disease_description_df dataset.</p><p><strong>Remove duplicate entries from the disease-symptom dataset</strong>: The code removes duplicate rows from the disease_symptom_df data frame and assigns the result to disease_symptom_dup.</p><p><strong>Function for capitalizing words and removing underscores:</strong> The code defines a lambda function called capitalize_and_remove_underscore.This function capitalizes the words in a string and replaces underscores with spaces.</p><p><strong>Fill in missing values in the precaution dataset:</strong> The code fills in any missing values in the disease_precaution_df data frame with an empty string using fillna(&#39;&#39;).</p><h3>Step 2: Building the Hybrid Model</h3><h4>Neural Network Component:</h4><p>The neural network component forms a crucial part of the hybrid model. The architecture is designed to effectively learn patterns and relationships between symptoms and diseases. This includes selecting appropriate layers, activation functions, and regularization techniques. The model is trained using an optimizer and loss function customized to the specific requirements.</p><h4>Symbolic Reasoning Component:</h4><p>The symbolic reasoning layer uses a knowledge graph constructed from disease-symptom relationships. This component enables the model to reason about the relationships between symptoms and diseases using predefined rules (from the dataset). By leveraging this knowledge graph, the model can provide transparent and interpretable predictions and recommendations for triage management.</p><h4>Hybrid Model and Predictions:</h4><p>The hybrid model combines the outputs of both the neural network and symbolic reasoning components using a Multiply Layer to generate predictions and triage recommendations. The multiply layer is being used in this context to capture interactions and dependencies between the outputs of the neural network and symbolic reasoning components, allowing for a weighted combination that incorporates the strengths of both approaches in disease classification and prediction. Patient symptoms are inputted into the model, which produces a combined output that captures both the learned patterns from the neural network and the rule-based reasoning from the symbolic reasoning layer. The model’s predictions provide insights into the most likely disease and associated triage priority, enabling efficient resource allocation and patient care.</p><h3>Code:</h3><h4>1. Creating a Hybrid Model</h4><pre># Define symbolic rules<br>disease_symptom_dict = {}<br>symptom_disease_dict = {}<br><br># Normalize symptom names<br>normalize_symptom = lambda symptom: symptom.strip().lower()<br><br># Iterate over the rows of the dataset<br>for _, row in disease_symptom_dup.iterrows():<br>    disease = row[&#39;Disease&#39;]<br>    symptoms = [normalize_symptom(symptom) for symptom in row.drop(&#39;Disease&#39;).dropna().tolist()]<br><br>    disease_symptom_dict.setdefault(disease, []).extend(symptoms)<br><br>    for symptom in symptoms:<br>        symptom_disease_dict.setdefault(symptom, []).extend(disease)<br><br># Define symbolic rules using a knowledge graph<br>knowledge_graph = nx.DiGraph()<br><br># Add disease-symptom relationships to the knowledge graph<br>for _, row in disease_symptom_dup.iterrows():<br>    disease = row[&#39;Disease&#39;]<br>    symptoms = [normalize_symptom(symptom) for symptom in row.drop(&#39;Disease&#39;).dropna().tolist()]<br><br>    knowledge_graph.add_edges_from([(symptom, disease) for symptom in symptoms])<br><br># Custom layer for symbolic reasoning<br>class SymbolicReasoningLayer(layers.Layer):<br>    def __init__(self, knowledge_graph, num_diseases, **kwargs):<br>        super(SymbolicReasoningLayer, self).__init__(**kwargs)<br>        self.knowledge_graph = knowledge_graph<br>        self.num_diseases = num_diseases<br>        self.symbolic_reasoning_output = layers.Dense(self.num_diseases, activation=&#39;softmax&#39;)<br><br>    def call(self, inputs):<br>        inferred_diseases = []<br>        for symptoms in inputs:<br>            inferred_disease = set()<br>            for symptom in symptoms:<br>                if symptom in self.knowledge_graph:<br>                    related_diseases = nx.descendants(self.knowledge_graph, symptom)<br>                    inferred_disease.update(related_diseases)<br>            inferred_diseases.append(list(inferred_disease))<br>        return self.symbolic_reasoning_output(tf.convert_to_tensor(inferred_diseases))<br><br>    def explain_prediction(self, patient_symptoms):<br>        inferred_diseases = []<br>        for symptoms in patient_symptoms:<br>            inferred_disease = set()<br>            for symptom in symptoms:<br>                if symptom in self.knowledge_graph:<br>                    related_diseases = nx.descendants(self.knowledge_graph, symptom)<br>                    inferred_disease.update(related_diseases)<br>            inferred_diseases.append(list(inferred_disease))<br>        return inferred_diseases<br><br><br># Convert patient symptoms to a one-hot encoded vector<br>def encode_symptoms(symptoms):<br>    encoded_symptoms = np.zeros(len(symptom_severity_dict))<br>    for symptom in symptoms:<br>        if symptom in symptom_to_index:<br>            encoded_symptoms[symptom_to_index[symptom]] = 1<br>    return encoded_symptoms<br><br># Create the hybrid model<br>symptom_input = layers.Input(shape=(len(symptom_severity_dict),), name=&#39;symptom_input&#39;)<br><br># Neural network component with explainability<br>neural_network_output = layers.Dense(128, activation=&#39;relu&#39;)(symptom_input)<br>neural_network_output = layers.Dropout(0.5)(neural_network_output)<br>neural_network_output = layers.Dense(64, activation=&#39;relu&#39;)(neural_network_output)<br>neural_network_output = layers.Dropout(0.5)(neural_network_output)<br>neural_network_output = layers.Dense(len(disease_symptom_dict), activation=&#39;softmax&#39;, name=&#39;neural_network_output&#39;)(neural_network_output)<br><br># Symbolic reasoning component with explainability<br>symbolic_reasoning_output = SymbolicReasoningLayer(knowledge_graph, len(disease_symptom_dict))(symptom_input)<br><br># Combine neural network and symbolic reasoning outputs using a multiply layer<br>combined_output = layers.Multiply(name=&#39;combined_output&#39;)([neural_network_output, symbolic_reasoning_output])<br><br># Create the hybrid model<br>model = Model(inputs=[symptom_input], outputs=[combined_output])<br><br># Define optimizer with custom learning rate<br>learning_rate = 0.001<br>optimizer = keras.optimizers.Adam(learning_rate=learning_rate)<br><br># Compile the model with the new optimizer and loss function<br>model.compile(optimizer=optimizer, loss=&#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br># Convert disease-symptom dictionary to training data<br>X_train = []<br>y_train = []<br>for disease, symptoms in disease_symptom_dict.items():<br>    X_train.append(encode_symptoms(symptoms))<br>    y_train.append(np.array([1 if d == disease else 0 for d in disease_symptom_dict.keys()]))<br>X_train = np.array(X_train)<br>y_train = np.array(y_train)<br><br># Train the model<br>model.fit(X_train, y_train, epochs=300, batch_size=32)</pre><p>The code starts by defining empty dictionaries, disease_symptom_dict and symptom_disease_dict, which will store the relationships between diseases and symptoms.</p><p>The normalize_symptom function is defined to convert symptom names to lowercase and remove leading/trailing spaces.</p><p>The code iterates over the rows of the dataset (disease_symptom_dup) to populate the dictionaries. It extracts disease names and symptoms from each row, normalizes the symptoms, and adds them to the dictionaries. The disease_symptom_dict maps diseases to their associated symptoms, while symptom_disease_dict maps symptoms to the diseases they are related to.</p><p>A knowledge graph (knowledge_graph) is created using a directed graph (nx.DiGraph()) from the disease_symptom_dup dataset. The graph represents the relationships between symptoms and diseases. Then, the code defines a custom layer (SymbolicReasoningLayer) that performs symbolic reasoning based on the knowledge graph. It takes the knowledge graph and the number of diseases as inputs. The layer uses the knowledge graph to infer diseases based on patient symptoms and provides an explanation of the prediction.</p><p>The encode_symptoms function converts patient symptoms into a one-hot encoded vector.</p><p>The hybrid model is created using the functional API of Keras. It has an input layer (symptom_input) for the encoded symptoms.</p><p>The neural network component processes the input and generates predictions (neural_network_output). The neural component of the system utilizes a neural network to process patient symptoms and make predictions for disease classification. It consists of multiple dense layers (128, 64, and 41) with activation functions such as ReLU, followed by dropout layers for regularization.</p><p><strong>Dense layer:</strong> Dense layers, also known as fully connected layers, are a fundamental building block in neural networks. These layers establish connections between every neuron in the current layer and the previous layer, allowing for the learning of complex patterns and relationships within the data.</p><p><strong>Activation function (ReLu)</strong>: ReLu sets any negative input values to zero, while leaving positive values unchanged. ReLU introduces non-linearity to the network, allowing it to capture complex relationships and patterns in the data. Its simplicity and computational efficiency make it an attractive choice, enabling faster training and inference. The sparsity-inducing property of ReLU helps prevent overfitting and promotes a more efficient representation of the data. f(x) = max(0, x)</p><p><strong>Dropout Layer:</strong> A dropout layer is a regularization technique commonly used in neural networks during training to prevent overfitting. It randomly sets a fraction of input units to zero during each update, which helps prevent the network from relying too heavily on specific features or neurons.</p><p>The symbolic reasoning component (SymbolicReasoningLayer) performs reasoning based on the knowledge graph.</p><p><strong>Knowledge graph:</strong> A knowledge graph is a structured representation of knowledge that captures relationships between entities or concepts. It consists of nodes (representing entities) and edges (representing relationships) connecting these nodes. Knowledge graphs are used to organize and model complex information, allowing for efficient storage, retrieval, and reasoning over interconnected knowledge.</p><p>The outputs of both components are combined using a Multiply layer (combined_output).</p><p><strong>Multiply function: </strong>The multiply function refers to the element-wise multiplication operation performed by the multiply layer. The multiply layer takes the outputs of the neural network and symbolic reasoning components and performs element-wise multiplication between them.</p><p>The model is compiled with the Adam optimizer and categorical cross-entropy loss function. Adam adapts the learning rate for each parameter in the model based on the past gradients, allowing for faster convergence and better performance. It is well-suited for models with large datasets and complex architectures, making it a suitable choice for the hybrid model in this code. In this case, the model is trained to predict the probability distribution of diseases based on symptoms. Categorical cross-entropy encourages the model to assign high probabilities to the correct disease class and penalizes deviations from the true distribution. It is a suitable choice for training the hybrid model to accurately classify diseases based on symptoms.</p><p>The disease-symptom dictionary is converted to training data, where each disease’s associated symptoms are encoded as input (X_train) and the corresponding one-hot encoded disease labels are used as output (y_train). The model is trained using the training data (X_train and y_train) with 300 epochs and a batch size of 32. I experimented with a bunch of different epochs and batch sizes, and finally, I decided on these numbers as they provide the best output</p><h4>Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibtaYZ7-n4kaCmpxBUaMKA.png" /></figure><p>The output represents the training progress of the model over multiple epochs. Each epoch refers to a complete iteration of the training data during the training process.</p><ul><li>Epoch X/Y: It indicates the current epoch number out of the total number of epochs.</li><li>2/2: It shows the progress within the current epoch, where 2 refers to the number of batches processed in the epoch.</li><li>0s 7ms/step: It displays the time taken to process each step (batch) within an epoch. In this case, it shows that each step took an average of 7 milliseconds to complete.</li><li>loss: The loss value computed by the model during training for the current epoch. It quantifies the difference between the predicted output and the true output. A lower loss indicates better model performance.</li><li>accuracy: The accuracy of the model on the training data for the current epoch. It represents the proportion of correctly predicted disease classifications compared to the total number of training samples. A higher accuracy value indicates better performance.</li></ul><p>Looking at the specific values in the output, the loss decreases over epochs, while the accuracy generally improves. This indicates that the model is gradually learning to make more accurate predictions as the training progresses. In the last epoch (Epoch 300/300), the loss is 0.3214, and the accuracy is 100%.</p><h3>Step 3: Obtaining Prediction, Explanation, Triage Priority, and Verdict</h3><h4>Explanations and Interpretability</h4><p>The hybrid model generates explanations for its predictions and triage recommendations. These explanations provide insights into the reasoning behind the model’s decisions, which helps both users and healthcare professionals in understanding the factors influencing the outcomes. Feature analysis highlights critical symptoms and their importance in disease prediction and triage management, enhancing interpretability and trust in the model’s output.</p><h3>Code:</h3><h4>1. Functions of Prediction, Explanation, Triage Priority, and Verdict</h4><pre># Function to get feature importance based on model weights<br>def get_feature_importance(model, user_symptoms):<br>    feature_names = list(symptom_severity_dict.keys())<br>    user_symptom_indices = np.array([symptom_to_index[symptom] for symptom in user_symptoms if symptom in symptom_to_index])<br>    feature_importance = np.abs(model.get_weights()[0]).sum(axis=1)<br>    user_symptom_importance = feature_importance[user_symptom_indices]<br>    sorted_indices = np.argsort(user_symptom_importance)[::-1]<br>    sorted_features = [feature_names[i] for i in user_symptom_indices[sorted_indices]]<br>    sorted_importance = user_symptom_importance[sorted_indices]<br>    return sorted_features, sorted_importance<br><br><br># Function to predict disease based on symptoms using the trained model<br>def predict_disease(symptoms):<br>    encoded_symptoms = encode_symptoms(symptoms)<br>    predicted = model.predict(np.array([encoded_symptoms]))<br>    disease_index = np.argmax(predicted)<br>    predicted_disease = list(disease_symptom_dict.keys())[disease_index]<br><br>    # Add explanation within the prediction process<br>    print(&quot;The model predicted the disease based on the following symptoms:&quot;)<br>    for symptom in symptoms:<br>        print(&quot;- &quot; + symptom)<br>    print(&quot;The predicted disease is: &quot; + predicted_disease)<br><br>    return predicted_disease<br><br><br>def explain_decision(symptoms, user_symptoms):<br>    encoded_symptoms = encode_symptoms(symptoms)<br>    predicted = model.predict(np.array([encoded_symptoms]))<br>    disease_index = np.argmax(predicted)<br>    predicted_disease = list(disease_symptom_dict.keys())[disease_index]<br>    top_diseases_indices = np.argsort(predicted)[0][-3:][::-1]<br>    top_diseases = [list(disease_symptom_dict.keys())[index] for index in top_diseases_indices]<br>    <br>    # Get disease description and precautions<br>    disease_description = get_disease_description(predicted_disease)<br>    disease_precautions = get_disease_precautions(predicted_disease)<br>    <br>    # Check for other diseases with the same symptoms<br>    potential_diseases = []<br>    for disease, symptoms in disease_symptom_dict.items():<br>        if set(user_symptoms).issubset(set(symptoms)):<br>            potential_diseases.append(disease)<br>    potential_diseases = set(potential_diseases)<br>    potential_diseases = list(potential_diseases)<br>    print(&quot;POTENTIAL&quot;, potential_diseases)<br>    <br>    diseases_same = []<br>    for disease in potential_diseases:<br>        dsymptoms = disease_symptom_dict[disease]<br>        check = all(item in dsymptoms for item in user_symptoms)<br>        if check is True:<br>            print()<br>            diseases_same.append(disease)<br>            print()<br>    <br>    print(&quot;TOP&quot;, top_diseases)<br>    for i in top_diseases:<br>        diseases_same.append(i)<br>    <br>    diseases_same = set(diseases_same)<br>    diseases_same = list(diseases_same)<br>    count = len(diseases_same)<br>    <br>    print()<br>    print(&quot;The predicted disease according to the model is &quot;, predicted_disease)<br>    print(f&quot;However based on your entered symptoms, there are {count-1} other diseases that can be checked, do you want to check them?&quot;)<br>    print(&quot;These are the diseases:&quot;)<br>    for i in diseases_same:<br>        print(i)<br>    print()<br>    <br>    check = input(&quot;Enter yes to check or else proceed with prediction&quot;)<br>    if check == &#39;yes&#39;:<br>        if(len(potential_diseases)&gt;0):<br>            for i in potential_diseases:<br>                print(&quot;Checking for disease&quot;, i)<br>                dsd = set(disease_symptom_dict[i])<br>                us = set(user_symptoms)<br>                uncommon_symptoms = list(dsd.difference(us))<br>                for j in uncommon_symptoms[:2]:<br>                    print(&quot;What about this?&quot;, j)<br>                    ans = input(&quot;do u have this? (yes or no)&quot;)<br>                    if ans == &#39;yes&#39;:<br>                        user_symptoms.append(j)<br>    else:<br>        print(&quot;Okay, proceeding with models prediction without any additional symptoms&quot;)<br>        <br>    encoded_symptoms = encode_symptoms(user_symptoms)<br>    predicted = model.predict(np.array([encoded_symptoms]))<br>    disease_index = np.argmax(predicted)<br>    predicted_disease = list(disease_symptom_dict.keys())[disease_index]<br><br>    # Get disease description and precautions<br>    disease_description = get_disease_description(predicted_disease)<br>    disease_precautions = get_disease_precautions(predicted_disease)<br>    <br>    # Generate detailed explanation<br>    explanation = f&quot;Based on the given symptoms, the model predicts the disease as &#39;{predicted_disease}&#39;.\n\n&quot;<br><br>    # Feature Importance<br>    explanation += &quot;Feature Importance:\n&quot;<br>    features, importance = get_feature_importance(model, user_symptoms)<br>    explanation += &quot;The most important symptoms for the prediction are:\n&quot;<br>    for feature, score in zip(features, importance):<br>        explanation += f&quot;- {feature}: Importance {score}\n&quot;<br>    explanation += &quot;\n&quot;<br><br>    # Neurosymbolic Explanation<br>    explanation += &quot;Neurosymbolic Explanation:\n&quot;<br>    explanation += &quot;The model combines neural network predictions and symbolic reasoning to arrive at the disease prediction. &quot;<br>    explanation += &quot;The neural network analyzes the severity of symptoms and learns patterns from the training data. &quot;<br>    explanation += &quot;The symbolic reasoning component uses predefined rules and relationships between symptoms and diseases to infer the most likely disease.\n\n&quot;<br><br>    # Symptom Analysis<br>    explanation += &quot;Symptom Analysis:\n&quot;<br>    explanation += &quot;The model considers the following symptoms and their severities:\n&quot;<br>    for symptom, severity in symptom_severity_dict.items():<br>        if symptom in user_symptoms:<br>            symptom_description = symptom_dict.get(symptom, &quot;Description not available&quot;)<br>            explanation += f&quot;- {symptom}: {symptom_description}. Severity: {severity}\n&quot;<br>    explanation += &quot;\n&quot;<br><br>    # Disease-Symptom Information<br>    explanation += &quot;Disease-Symptom Information:\n&quot;<br>    explanation += &quot;The model incorporates information about diseases and their associated symptoms from the dataset.\n&quot;<br>    explanation += &quot;It learns the relationships between symptoms and diseases through the training process.\n&quot;<br>    explanation += &quot;\n&quot;<br>    disease_symptoms = disease_symptom_dict[predicted_disease]<br><br><br>    # Disease Description<br>    explanation += &quot;Description:\n&quot;<br>    explanation += f&quot;The predicted disease, &#39;{predicted_disease}&#39;, is described as follows:\n&quot;<br>    explanation += f&quot;{disease_description}\n\n&quot;<br><br>    # Precautions<br>    explanation += &quot;Precautions:\n&quot;<br>    for i, precaution in enumerate(disease_precautions):<br>        if (precaution!=&quot;&quot;):<br>            explanation += f&quot;{i + 1}. {precaution}\n&quot;<br><br>    return explanation<br><br>def get_disease_description(disease):<br>    description = disease_description_df.loc[disease_description_df[&#39;Disease&#39;] == disease, &#39;Description&#39;].values[0]<br>    return description<br><br># Function to get disease precautions<br>def get_disease_precautions(disease):<br>    precautions = disease_precaution_df.loc[disease_precaution_df[&#39;Disease&#39;] == disease].drop(&#39;Disease&#39;, axis=1).values[0]<br>    # Apply the function to the numpy array<br>    precautions = np.vectorize(capitalize_and_remove_underscore)(precautions)<br>    <br>    return precautions<br><br># Function to provide rule-based explanations<br>def get_explanations(symptoms):<br>    explanations = []<br>    for disease, symptoms_list in disease_symptom_dict.items():<br>        symptoms_list = set(symptoms_list)<br>        if set(symptoms).issubset(symptoms_list):<br>            explanations.append(f&quot;If {&#39;, &#39;.join(symptoms_list)}, then {disease}&quot;)<br>    return explanations<br><br># Triage Categories and their weight ranges<br>NON_URGENT_CARE = (1, 20)<br>ROUTINE_CARE = (21, 40)<br>PRIORITY_CARE = (41, 60)<br>URGENT_CARE = (61, 80)<br>IMMEDIATE_ATTENTION = (81, float(&#39;inf&#39;))<br><br>def calculate_triage_priority(symptoms):<br>    total_weight = sum(symptom_severity_dict[symptom] for symptom in symptoms)<br>    if IMMEDIATE_ATTENTION[0] &lt;= total_weight &lt;= IMMEDIATE_ATTENTION[1]:<br>        return &quot;Immediate Attention&quot;<br>    elif URGENT_CARE[0] &lt;= total_weight &lt;= URGENT_CARE[1]:<br>        return &quot;Urgent Care&quot;<br>    elif PRIORITY_CARE[0] &lt;= total_weight &lt;= PRIORITY_CARE[1]:<br>        return &quot;Priority Care&quot;<br>    elif ROUTINE_CARE[0] &lt;= total_weight &lt;= ROUTINE_CARE[1]:<br>        return &quot;Routine Care&quot;<br>    elif total_weight &gt;= NON_URGENT_CARE[0]:<br>        return &quot;Non-Urgent Care&quot;<br>    else:<br>        return &quot;Unknown Triage Priority&quot;<br>    <br>urgent_care_diseases = [<br>    &#39;Paralysis (brain hemorrhage)&#39;, &#39;Heart attack&#39;, &#39;Tuberculosis&#39;, &#39;Pneumonia&#39;, &#39;Malaria&#39;, &#39;Dengue&#39;, &#39;Typhoid&#39;, &#39;Hepatitis E&#39;<br>]<br><br>prompt_medical_attention_diseases = [<br>    &#39;Chronic cholestasis&#39;, &#39;Peptic ulcer disease&#39;, &#39;Jaundice&#39;, &#39;Alcoholic hepatitis&#39;, &#39;Common cold&#39;, &#39;Hypothyroidism&#39;,<br>    &#39;Hyperthyroidism&#39;, &#39;Hypoglycemia&#39;, &#39;Urinary tract infection&#39;<br>]<br><br>non_urgent_care_diseases = [<br>    &#39;Fungal infection&#39;, &#39;Allergy&#39;, &#39;GERD&#39;, &#39;Drug Reaction&#39;, &#39;Gastroenteritis&#39;, &#39;Bronchial Asthma&#39;, &#39;Migraine&#39;, <br>    &#39;Cervical spondylosis&#39;, &#39;Varicose veins&#39;, &#39;Osteoarthristis&#39;, &#39;Arthritis&#39;, &#39;(vertigo) Paroymsal  Positional Vertigo&#39;, <br>    &#39;Acne&#39;, &#39;Psoriasis&#39;, &#39;Impetigo&#39;<br>]<br><br>def classify_disease(disease):<br>    if disease in urgent_care_diseases:<br>        return &#39;Urgent Care&#39;<br>    elif disease in prompt_medical_attention_diseases:<br>        return &#39;Prompt Medical Attention&#39;<br>    elif disease in non_urgent_care_diseases:<br>        return &#39;Non-Urgent Care&#39;<br>    else:<br>        return &#39;Unclassified&#39;<br>    <br>def provide_verdict(symptoms,predicted_disease):<br>    triage_priority = calculate_triage_priority(symptoms)<br>    disease_classification = classify_disease(predicted_disease)<br><br>    if triage_priority == &quot;Immediate Attention&quot; or disease_classification == &quot;Urgent Care&quot;:<br>        importance = &quot;High Importance&quot;<br>    elif triage_priority == &quot;Urgent Care&quot; or disease_classification == &quot;Prompt Medical Attention&quot;:<br>        importance = &quot;Medium Importance&quot;<br>    elif triage_priority == &quot;Priority Care&quot; or disease_classification == &quot;Non-Urgent Care&quot;:<br>        importance = &quot;Low Importance&quot;<br>    else:<br>        importance = &quot;Unknown Importance&quot;<br><br>    return f&quot;Verdict: Triage Priority - {triage_priority}, Disease Classification - {disease_classification}, Importance - {importance}&quot;</pre><p>1.get_feature_importance(model, user_symptoms):</p><p>This function calculates the feature importance based on the model weights.</p><ul><li>model: The trained model used for prediction.</li><li>user_symptoms: A list of symptoms provided by the user.</li></ul><p>It first retrieves the list of feature names (symptoms) from the symptom_severity_dict.Next, it maps the user symptoms to their corresponding indices in the feature list. The feature importance is obtained by summing the absolute weights of the model’s first layer. It extracts the feature importance values for the user symptoms and sorts them in descending order. Finally, it returns the sorted features (symptoms) and their corresponding importance values.</p><p>2.predict_disease(symptoms):</p><p>This function predicts the disease based on the given symptoms using the trained model.</p><ul><li>symptoms: A list of symptoms for which the disease is to be predicted.</li></ul><p>It encodes the symptoms using the encode_symptoms function (not shown in the provided code). The encoded symptoms are passed to the trained model for prediction using model.predict. The index of the disease with the highest predicted probability is determined using np.argmax.The predicted disease name is obtained by mapping the disease index to the corresponding key in the disease_symptom_dict. The function then prints the given symptoms and the predicted disease. Finally, it returns the predicted disease.</p><p>3. explain_decision(symptoms, user_symptoms):</p><p>This function provides a detailed explanation for the predicted disease and additional information based on the given symptoms.</p><ul><li>symptoms: A list of symptoms used for prediction.</li><li>user_symptoms: A list of symptoms provided by the user.</li></ul><p>It performs similar operations to the predict_disease function to obtain the predicted disease. It identifies the top three diseases with the highest probabilities based on the model’s predictions. Next, it retrieves the description and precautions for the predicted disease using the respective functions (get_disease_description, get_disease_precautions). It checks for other diseases that have the same symptoms as the user’s input and stores them in the potential_diseases list. It then checks for diseases where all user symptoms are present and adds them to the diseases_same list. The function prints the predicted disease, the count of other potential diseases, and the list of potential and top diseases.</p><p>It prompts the user to enter whether they want to check the potential diseases or proceed with the prediction. Based on the user’s input, it may ask the user about additional symptoms related to potential diseases.</p><p>Finally, it encodes the user’s symptoms, predicts the disease again, and stores the description and precautions. It generates a detailed explanation by combining various information such as feature importance, neurosymbolic explanation, symptom analysis, disease-symptom information, description, and precautions. The explanation is returned as a string.</p><p>4.get_disease_description(disease):</p><p>This function retrieves the description of a given disease from the disease_description_df DataFrame.</p><ul><li>disease: The name of the disease for which the description is required.</li></ul><p>It locates the row in the DataFrame where the disease name matches and extracts the corresponding description. The description is returned.</p><p>5.get_disease_precautions(disease):</p><p>This function retrieves the precautions associated with a given disease from the disease_precaution_df DataFrame.</p><ul><li>disease: The name of the disease for which the precautions are required.</li></ul><p>It locates the row in the DataFrame where the disease name matches and removes the “Disease” column. The precautions are stored as a numpy array and then capitalized and underscores are removed using the capitalize_and_remove_underscore function (not shown in the provided code). The precautions are returned as a list.</p><p>6.get_explanations(symptoms):</p><p>This function provides rule-based explanations for the given symptoms.</p><ul><li>symptoms: A list of symptoms for which explanations are required.</li></ul><p>It iterates over each disease in the disease_symptom_dict and checks if the given symptoms are a subset of the disease&#39;s symptoms. If the symptoms match, it generates an explanation using the disease and symptoms. The explanations are stored in a list and returned.</p><p>Triage Categories and their weight ranges:</p><p>Defines various triage categories along with their corresponding importance. These categories help prioritize the severity of symptoms based on the total weight calculated from the symptom_severity_dict. The categories range from “Non-Urgent Care” to “Immediate Attention,” with increasing levels of urgency.</p><p>7.calculate_triage_priority(symptoms):</p><p>This function calculates the triage priority based on the total weight of the symptoms.</p><ul><li>symptoms: A list of symptoms for which the triage priority is determined.</li></ul><p>It sums up the severity weights of all the symptoms from the symptom_severity_dict. Depending on the total weight, it assigns the corresponding triage priority category. The triage priority is returned as a string.</p><p>8.classify_disease(disease):</p><p>This function classifies a disease into different categories based on predefined lists of diseases.</p><ul><li>disease: The name of the disease to be classified.</li></ul><p>It checks if the disease name belongs to any of the predefined lists (urgent_care_diseases, prompt_medical_attention_diseases, non_urgent_care_diseases). If the disease is found in any list, it returns the corresponding category. Otherwise, it returns “Unclassified.”</p><p>9.provide_verdict(symptoms, predicted_disease):</p><p>This function provides a verdict based on the calculated triage priority, disease classification, and importance.</p><ul><li>symptoms: A list of symptoms used for prediction.</li><li>predicted_disease: The predicted disease.</li></ul><p>It calls the calculate_triage_priority function to determine the triage priority. It calls the classify_disease function to classify the disease. Based on the triage priority and disease classification, it assigns an importance level. The verdict, including the triage priority, disease classification, and importance, is returned as a string.</p><h3>Step 4: Displaying the output to the user</h3><p>The output displayed to the user provides comprehensive information regarding the predicted disease and additional details related to the symptoms entered.</p><p>First, it displays the predicted disease based on the model’s analysis. However, the user is also informed that there maybe other potential diseases that could be possible based on the symptoms provided. The user is given the choice to proceed with checking these alternative diseases or continue with the initial prediction. (If the user says yes, they would be asked about any other symptoms to predict the disease).</p><p>The model then generates a detailed analysis assuming the user proceeds with the prediction. It includes:</p><ul><li>rule-based explanations for the symptoms entered,</li><li>the patient’s symptoms,</li><li>the predicted disease, and</li><li>a final verdict (about the disease classification and triage priority).</li></ul><p>Additionally, feature importance is shown, which provides some insight on the symptoms that heavily influenced the prediction. The output also provides an explanation of how the neurosymbolic AI system works, offering insights into how the model combines neural network predictions and symbolic reasoning to make the disease prediction. Moreover, the symptom analysis provides a breakdown of the symptoms and their respective severities. Disease-symptom information is incorporated, showcasing the model’s understanding of the relationships between symptoms and diseases. A description of the predicted disease is given, along with precautions that should be taken.</p><h4>Getting the symptoms and displaying the output</h4><pre># Example usage<br>patient_symptoms = [&#39;vomiting&#39;,&#39;breathlessness&#39;, &#39;sweating&#39;, &#39;chest_pain&#39;]<br>triage_priority = calculate_triage_priority(patient_symptoms)<br>predicted_disease = predict_disease(patient_symptoms)<br>explanation = explain_decision(patient_symptoms, patient_symptoms)<br>explanations = get_explanations(patient_symptoms)<br><br># Print the explanations<br>if explanations:<br>    print(&quot;Rule based explanations based on entered symptoms:&quot;)<br>    for expln in explanations:<br>        print(f&quot;- {expln}&quot;)<br>else:<br>    print(&quot;No rule based explanations found for the given symptoms.\n&quot;)<br><br>print(&#39;\nPatient Symptoms:&#39;)<br>for symptom in patient_symptoms:<br>    print(symptom)<br>print(&#39;\nPredicted Disease:\n&#39;, predicted_disease)<br><br>print(&quot;\n&quot;,provide_verdict(patient_symptoms,predicted_disease))<br>print(&#39;\nExplanation:\n&#39;, explanation)</pre><p>The example usage shows how we can display the information to the user. It starts by providing a list of patient symptoms, which are then used to calculate a triage priority and predict the most probable disease. The explain_decision function generates an explanation for the prediction based on the entered symptoms. The get_explanations function retrieves multiple explanations for the symptoms. The code then proceeds to print the explanations if they exist, along with the patient&#39;s symptoms, the predicted disease, a verdict based on the symptoms and predicted disease and the explanation for the prediction. This example usage showcases the functionality of the system in providing explanations and insights based on patient symptoms.</p><h4>Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*81FAJwV6nATjgG0p7F3kNQ.png" /></figure><p>The output displayed to the user provides information regarding the predicted disease and additional insights related to the symptoms entered. In this particular example, the model predicts the disease as ‘Heart attack’. The user is then informed that there are three other diseases that can be checked based on the symptoms entered: Tuberculosis, Malaria, and Bronchial Asthma. The user is given the option to proceed with checking these diseases or continue with the prediction. Since the user chooses to proceed with the prediction, the model displays rule-based explanations for the entered symptoms, patient symptoms, the predicted disease, and a verdict. The output also includes feature importance, neurosymbolic explanation, symptom analysis, disease-symptom information, a description of the predicted disease, and precautions to be taken, such as calling an ambulance, chewing or swallowing aspirin, and keeping calm.</p><h3>Status Quo</h3><p>Existing approaches for disease prediction and triage management have predominantly relied on statistical methods or rule-based systems. These approaches often face limitations in capturing complex patterns and adapting to new information. As a result, patient outcomes may be compromised. The introduction of advanced machine learning techniques, such as neurosymbolic AI, addresses these limitations by combining statistical learning with symbolic reasoning to enhance interpretability and accuracy.</p><ol><li><strong>Statistical Models</strong>: Statistical models use machine learning algorithms to analyze large datasets and identify patterns correlating with specific diseases. These models often employ techniques like logistic regression, decision trees, support vector machines, or random forests. While statistical models can be effective in predicting diseases based on patterns, they may struggle to capture complex relationships between symptoms and diseases. They heavily rely on the availability and quality of training data and may face challenges in adapting to new information or emerging diseases.</li><li><strong>Rule-Based Systems</strong>: Rule-based systems rely on predefined rules and expert knowledge to classify diseases and prioritize patient care. These systems typically use if-then statements or decision trees to match symptoms with corresponding conditions. Rule-based systems can provide transparent and interpretable predictions. However, they may need more flexibility in adapting to variations in symptom presentations and often require frequent updates to accommodate new diseases or changes in medical guidelines.</li><li><strong>Clinical Scoring Systems: </strong>Clinical scoring systems, such as the Acute Physiology and Chronic Health Evaluation (APACHE) or the Sequential Organ Failure Assessment (SOFA), use predefined scores and thresholds to assess the severity of a patient’s condition and guide triage decisions. These systems often rely on physiological parameters, laboratory values, and clinical observations. While clinical scoring systems provide standardized approaches to prioritize patients, they may overlook subtle symptom variations or fail to capture complex interactions between symptoms and diseases.</li><li><strong>Decision Support Systems:</strong> Decision support systems integrate clinical data, patient history, and medical knowledge to provide recommendations for disease diagnosis and triage. These systems often utilize algorithms that combine statistical analysis with expert guidelines. While decision support systems can assist healthcare professionals in making informed decisions, they may still face challenges in accurately predicting complex diseases or handling large volumes of data in real-time.</li><li><strong>Artificial Intelligence (AI) and Machine Learning: </strong>AI and machine learning approaches are increasingly being explored for disease prediction and triage management. These approaches leverage large-scale datasets and advanced algorithms, such as deep learning, to identify patterns and make predictions. However, they often require substantial amounts of labeled data for training and may face challenges in interpretability and explainability, which are critical in healthcare settings.</li></ol><p>These existing approaches have made significant contributions to disease prediction and triage management. However, they do face limitations in capturing complex patterns, adapting to new diseases, handling uncertainty, and providing transparent explanations for their predictions. The integration of neurosymbolic AI, as a hybrid approach, aims to address some of these limitations by combining the strengths of neural networks and symbolic reasoning to enhance accuracy, interpretability, and adaptability in disease classification and triage management.</p><h3>Strengths &amp; Limitations</h3><p>The neurosymbolic AI system for triage management and disease classification offers several strengths that contribute to its effectiveness in healthcare settings.</p><ul><li><strong>Integration of neural networks and symbolic reasoning: </strong>allows for the analysis of symptom severity, learning patterns from data, and leveraging predefined rules and relationships between symptoms and diseases. This combination enables more accurate disease prediction and efficient triage management.</li><li><strong>Ability to provide rule-based explanations for predictions and recommendations:</strong> By using a knowledge graph constructed from disease-symptom relationships, the system can offer interpretable insights into its decision-making process. This feature is crucial in healthcare, as it enables both users and healthcare professionals to understand and trust the system’s recommendations, leading to improved collaboration between AI and human experts.</li><li><strong>Adapt to new information and update its knowledge base: </strong>As new research and data become available, the system can incorporate them into its symbolic rules, enhancing its accuracy and relevance over time. This adaptability ensures that the system remains up-to-date with the latest medical advancements and findings.</li></ul><p>However, the neurosymbolic AI system also has certain limitations that need to be considered.</p><ul><li><strong>Defining accurate and comprehensive symbolic rules: </strong>Creating and maintaining an extensive knowledge graph that encompasses the complexities of diseases and symptoms requires significant expertise and ongoing effort. Incomplete or erroneous rules could lead to incorrect predictions or recommendations, underscoring the importance of rigorous validation and continuous refinement.</li><li><strong>Availability and quality of data:</strong> Robust and diverse datasets are necessary to train the neural network component effectively. Insufficient or biased data could result in limited generalization and potential disparities in disease predictions across different populations or demographics. Addressing data biases and ensuring data representativeness are critical considerations in deploying and utilizing the system responsibly.</li><li><strong>Computational complexity of the neurosymbolic AI system: </strong>There may be some challenges in terms of scalability and real-time performance. The integration of neural networks and symbolic reasoning requires substantial computational resources, which could hinder its practical implementation in resource-constrained healthcare environments or in scenarios that demand real-time decision-making.</li></ul><h3>Implementation in the real world</h3><p>The implementation of the hybrid approach, combining neural networks and symbolic reasoning in the neurosymbolic AI system, has several practical implications for integration with existing healthcare systems.</p><ul><li>As mentioned in the strengths of this system, the hybrid approach can <strong>enhance the accuracy and efficiency</strong> of disease classification and triage management. By leveraging the power of neural networks to analyze symptom severity and learn patterns from data, coupled with symbolic reasoning that incorporates predefined rules and relationships between symptoms and diseases, the system can provide more accurate predictions and recommendations.</li><li>The integration of the hybrid approach with existing healthcare systems <strong>can lead to improved workflow and resource allocation</strong>. The system can aid in streamlining the triage process by automatically analyzing patient symptoms, predicting diseases, and assigning appropriate priority levels. This can optimize the utilization of healthcare resources, ensure timely interventions for critical cases, and reduce waiting times for patients.</li><li>The neurosymbolic AI system’s ability to provide rule-based explanations for its predictions and recommendations has practical implications for healthcare professionals and patients. The system can <strong>generate understandable and interpretable explanations based on the underlying knowledge graph and symbolic rules</strong>. This can help healthcare professionals in understanding the reasoning behind the system’s decisions and building trust in its capabilities. Additionally, patients can benefit from transparent explanations that empower them to actively participate in their healthcare journey and make well-informed decisions.</li><li>Integration with existing healthcare systems also entails considerations of interoperability and data sharing. In the future, the neurosymbolic AI system <strong>could be designed to seamlessly integrate with electronic health record (EHR) systems, enabling the exchange of patient data and facilitating the incorporation of real-time information for accurate predictions</strong>. Robust data security measures and compliance with privacy regulations are crucial to protect patient confidentiality and ensure the responsible handling of sensitive healthcare information.</li><li>The implementation of the hybrid approach can contribute to the accumulation and utilization of medical knowledge. The system <strong>can continuously learn from new data, update the knowledge graph, and refine its predictions and recommendations over time</strong>. This iterative learning process can lead to the discovery of new patterns, insights, and potential correlations between symptoms and diseases, further improving the accuracy of the system.</li></ul><p>Overall, integrating the neurosymbolic AI system with existing healthcare systems offers practical benefits such as <strong>enhanced accuracy, streamlined workflow, improved resource allocation, transparent explanations, and the potential for continuous learning</strong>. It holds promise for optimizing healthcare delivery, improving patient outcomes, and supporting healthcare professionals in making informed decisions.</p><h3>Conclusion:</h3><p>The proposed neurosymbolic AI system presents a hybrid approach that combines neural networks and symbolic reasoning for improved disease classification and triage management. The integration of statistical learning with rule-based reasoning enables accurate predictions and transparent explanations. The potential impact of the hybrid approach in optimizing healthcare outcomes and resource allocation is significant. By leveraging the strengths of both neural networks and symbolic reasoning, the model offers a promising solution to enhance triage management and disease classification in healthcare settings. There are several future research directions that can be pursued to further refine and expand the capabilities of the neurosymbolic AI model for triage management and disease classification:</p><ol><li><strong>Integration of Temporal Information:</strong> Incorporating temporal information, such as the sequence of symptom occurrence or changes over time, can provide valuable insights for disease diagnosis and monitoring. Future research can explore methods to integrate temporal data into the neurosymbolic AI model, enabling it to capture dynamic patterns and better adapt to evolving patient conditions.</li><li><strong>Addressing Data Biases and Generalization:</strong> For now, the data only includes diseases and symptoms, however as it is integrated into real-life systems, there would be confidential patient data such as age, gender, etc. being integrated and there would be certain ethical considerations to be considered. These considerations in healthcare AI necessitate addressing potential biases in data and decision-making. Future research should focus on developing techniques to mitigate biases and ensure fairness in disease classification and triage management.</li><li><strong>Explainability and Interpretability:</strong> Although the neurosymbolic AI model provides certain explanations to the user about the symptoms and the diseases, further research can be conducted to enhance the explainability and interpretability of its predictions. This includes developing methods to generate more detailed and context-specific explanations, as well as designing user-friendly interfaces that effectively communicate the model’s reasoning to healthcare professionals and patients.</li><li><strong>Clinical Validation and Real-World Deployment: </strong>Conducting extensive clinical validation studies and evaluating the performance of the neurosymbolic AI model in real-world healthcare settings is crucial. Future research should focus on conducting rigorous evaluations to assess the model’s efficacy, reliability, and impact on healthcare outcomes. This includes validating its performance against existing clinical guidelines and benchmarking it against other established diagnostic methods.</li><li><strong>Collaboration and Data Sharing:</strong> Collaboration among researchers, healthcare professionals, and institutions is essential for the further refinement and expansion of the neurosymbolic AI model. Future research should emphasize data-sharing initiatives, fostering collaborations to access larger and more diverse datasets. This can facilitate the development of more robust and generalizable models while addressing privacy and security concerns through appropriate data governance frameworks.</li></ol><p>By exploring these future research directions, we can continue to advance the neurosymbolic AI model, refine its capabilities, and maximize its potential for improving triage management and disease classification in healthcare.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efed9f8ae2d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing Mocktail Creation with Neurosymbolic AI: Building a Personalized System]]></title>
            <link>https://prabhatm27.medium.com/revolutionizing-mocktail-creation-with-neurosymbolic-ai-building-a-personalized-system-b40f8170f3e7?source=rss-f0451664d8fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b40f8170f3e7</guid>
            <category><![CDATA[neurosymbolic-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Prabhat M]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 04:38:05 GMT</pubDate>
            <atom:updated>2023-06-08T07:04:04.663Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how new mocktails are created? Do you ever find yourself tired of the same old mocktail flavors, but unsure of how to create something new and exciting? With the rise of artificial intelligence and machine learning, there is a new way to create personalized mocktails that perfectly match your taste preferences. Aneurosymbolic AI system can identify the best mocktail combinations while simultaneously eliminating any bad or incompatible ingredients. In this article, we will explore how to build a neurosymbolic AI system that can create a personalized mocktail recipe based on your preferred flavors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ARfnUOmYYqTqwr2Z.jpg" /></figure><p>Neurosymbolic AI is a powerful, relatively new technology that uses a combination of deep learning and symbolic reasoning to create intelligent systems capable of decision-making and reasoning. When applied to mocktail creation, a neurosymbolic AI system can take into account all the ingredients used to make a mocktail and identify the best combination of flavors that match a user’s preferences. Using a neural network, the system can learn from the previous choices and make recommendations based on their taste. The symbolic reasoning component comes into play by removing any bad or incompatible ingredients from the list of possible combinations, ensuring that only the best options are presented to the user. Building a neurosymbolic AI system for mocktail creation involves training the neural network with a dataset of flavor combinations and teaching the system to choose the best combinations from the ones generated by the user. With the right approach, a neurosymbolic AI system can help users create personalized mocktail recipes that perfectly match their taste preferences.</p><p>Neurosymbolic AI is a hybrid approach to artificial intelligence that combines the <strong>power of machine learning with the human-like reasoning abilities of symbolic AI</strong>. By using this approach, we can create a system that not only learns from data but also incorporates human knowledge and domain expertise. The article will provide a step-by-step guide on how to design and implement a neurosymbolic AI system using the Keras library and a rule-based system. The aim is to make it easy for readers to understand and apply this approach to create their mocktail recipes using artificial intelligence.</p><ol><li><strong>Deep learning:</strong> This is a subfield of machine learning that involves training neural networks with large amounts of data to make accurate predictions or classifications.</li><li><strong>Neural networks:</strong> This is a type of machine learning algorithm that is modeled after the structure and function of the human brain.</li><li><strong>Symbolic AI: </strong>This refers to the use of logical reasoning and symbolic representation to solve problems.</li><li><strong>Knowledge representation:</strong> This is the process of encoding knowledge into a format that can be used by a computer.</li><li><strong>Rule-based systems:</strong> These are systems that use a set of if-then rules to make decisions or draw conclusions.</li><li><strong>Keras: </strong>This is a high-level neural networks API, written in Python, that is designed to enable fast experimentation with deep neural networks.</li></ol><h3>A Simple Explanation of the neurosymbolic AI System</h3><p>The neurosymbolic AI system has two key components: a <strong>symbolic reasoning component</strong> and a <strong>neural network component</strong>. The system has access to a database of over 100 mocktail recipes and their associated ingredients and flavor profiles. When a user requests a mocktail with specific flavor profiles, the system generates combinations of three ingredients from the available ingredients that match the requested flavor profiles.</p><p>This is where the <strong>symbolic reasoning component</strong> comes into play. The system uses rules and logic to eliminate combinations of ingredients that are unlikely to produce a good mocktail. For example, the system might remove a combination of <strong>maraschino cherry and lime juice</strong> because they are not likely to complement each other. Once the system has eliminated all the bad combinations, the neural network is trained on the remaining good and compatible combinations to identify the best mocktail recipe. In this way, the neurosymbolic AI system combines symbolic reasoning and neural network techniques to create a sophisticated and accurate mocktail recommendation system.</p><p>Imagine a detective trying to solve a crime. They have access to a lot of evidence, witness statements, and other information about the case. To solve the crime, the detective needs to use both logic and intuition. They need to use logic to eliminate possible suspects and scenarios that don’t make sense, and intuition to make connections between pieces of evidence that might seem unrelated.</p><p>Similarly, a neurosymbolic system combines two different approaches to solving a problem — <strong>symbolic reasoning and neural networks</strong>. The symbolic reasoning component helps to eliminate unlikely solutions based on rules and logic, while the neural network component can use machine learning techniques to find patterns and connections in data. By combining these two approaches, a neurosymbolic system can create a more accurate and effective solution to a complex problem.</p><p>With the help of a neurosymbolic AI system for mocktail creation, you can now say goodbye to the guesswork involved in mixing ingredients to make a perfect mocktail. No more frustration and disappointment of not getting the taste you desire. Instead, get ready to enjoy the perfect blend of flavors that suit your taste buds. The neurosymbolic system is like your very own mocktail personal assistant, helping you create the perfect drink based on your flavor preferences. So sit back, relax, and enjoy your personalized mocktail with the perfect blend of flavors!</p><h3>Type of neurosymbolic AI approaches (Wikipedia):</h3><ul><li><strong>Symbolic Neural symbolism</strong> is a way of using large language models in natural language processing, such as BERT, RoBERTa, and GPT-3, where words or subword tokens are both the input and output.</li><li><strong>Symbolic[Neural]</strong> is a combination of symbolic and neural techniques used in AlphaGo, where Monte Carlo tree search is used symbolically, and neural techniques are used to evaluate game positions.</li><li><strong>Neural|Symbolic</strong> uses a neural architecture to interpret perceptual data as symbols and relationships that are then reasoned about symbolically. The Neural-Concept Learner is an example.</li><li><strong>Neural:Symbolic → Neural</strong> relies on symbolic reasoning to create or label training data that is then learned by a deep learning model. For example, a Macsyma-like symbolic mathematics system can be used to create or label examples to train a neural model for symbolic computation.</li><li><strong>Neural_{Symbolic}</strong> uses a neural net generated from symbolic rules. The Neural Theorem Prover is an example, which constructs a neural network from an AND-OR proof tree generated from knowledge base rules and terms. Logic Tensor Networks also fall into this category.</li><li><strong>Neural[Symbolic] </strong>allows a neural model to directly call a symbolic reasoning engine, such as to perform an action or evaluate a state.</li></ul><p>Here, I am using this approach: <strong>Neural:Symbolic → Neural, </strong>where I generated the good combinations using symbolic reasoning and the neural network to predict the best combination from that.</p><h3>Steps:</h3><ol><li><strong>Data collection &amp; User input</strong></li><li><strong>Filter matching ingredients &amp; Generate possible combinations</strong></li><li><strong>Symbolic reasoning</strong></li><li><strong>Neural network training &amp; Prediction</strong></li><li><strong>Naming and presentation of the recommendation</strong></li></ol><h3>Discussion of the techniques used</h3><p><strong>Neural AI:</strong> The neural AI part of a neurosymbolic AI system involves the use of deep learning techniques, such as neural networks, to process and analyze data. This component is responsible for tasks such as feature extraction, pattern recognition, and prediction, and it typically learns from large amounts of labeled data. It is designed to handle complex, high-dimensional data and can make predictions or classifications with high accuracy.</p><p><strong>Symbolic AI:</strong> Symbolic AI, also known as rule-based AI or expert systems, is a branch of artificial intelligence that deals with the representation and manipulation of knowledge formally and logically. It involves the use of logic and symbolic reasoning to make decisions and draw conclusions based on a set of rules or knowledge bases. Symbolic AI is often used in domains where human expertise and knowledge are required, such as in medical diagnosis or legal reasoning.</p><p><strong>Neural Network: </strong>A type of machine learning algorithm that is modeled after the structure and function of the human brain. It is used for tasks such as pattern recognition and prediction.</p><h3>Step 1: Data collection &amp; User input</h3><p>The dataset used for the mocktail-creating neurosymbolic system consists of several columns: Cocktail Name, Ingredient 1, Ingredient 2, Ingredient 3, Flavor Profile 1, Flavor Profile 2, and User Rating. The Cocktail Name column contains the name of the mocktail, while the Ingredient 1, Ingredient 2, and Ingredient 3 columns contain the names of the ingredients used to make the mocktail. The Flavor Profile 1 and Flavor Profile 2 columns represent the primary and secondary flavor profiles of the mocktail. Finally, the User Rating column contains the average rating given by users who have tried the mocktail.</p><p>This dataset was generated by ChatGPT, a large language model trained by OpenAI, based on the GPT-3.5 architecture. ChatGPT was trained on a vast amount of text data from the internet and can generate high-quality text in natural language. For this specific dataset, ChatGPT used its knowledge of cocktail recipes and flavor profiles to generate a list of mocktails and their corresponding ingredients and ratings.</p><h3>Code:</h3><h4><strong>1. Installing &amp; importing the necessary libraries:</strong></h4><p>The code imports several libraries to support the implementation of this neurosymbolic AI mocktail creation system. These libraries include pandas, numpy, TensorFlow, itertools, random and several models from tensorflow.keras models.</p><pre>!pip install tensorflow-gpu==2.4.1</pre><pre># Import required libraries<br>import numpy as np # linear algebra<br>import tensorflow as tf<br>import pandas as pd<br>import itertools<br>import random<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense, Dropout, BatchNormalization<br>from keras.callbacks import EarlyStopping<br><br># Input data files are available in the read-only &quot;../input/&quot; directory<br># For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory<br><br>import os<br>for dirname, _, filenames in os.walk(&#39;/kaggle/input&#39;):<br>    for filename in filenames:<br>        print(os.path.join(dirname, filename))</pre><h4><strong>2. Importing the data</strong></h4><p>I have different versions of the dataset and the final version I am using is “Mocktail data v5.csv”</p><pre># Load the dataset<br>df = pd.read_csv(&#39;/kaggle/input/mocktail-dataset/Mocktail data v5.csv&#39;)<br>df.head()</pre><ul><li><strong>Mocktail data v5.csv</strong>: This dataset contains the names of the mocktails, the three ingredients used, and the two flavor profiles (primary and secondary)</li></ul><h4><strong>3. Preprocessing the data</strong></h4><p>Since this dataset has been generated by ChatGPT, there aren&#39;t a lot of preprocessing steps to be done here. However, there are a few important checks to be done like checking for any null values, checking for duplicate values, etc.</p><pre>#Checking any null values<br>df.isna().sum()</pre><pre># check for duplicates<br>duplicates = df.duplicated()<br><br># print the boolean series of duplicates<br>print(duplicates)</pre><h4><strong>4. Defining flavor profiles from user input</strong></h4><p>This code is a Python program that helps the user choose their preferred flavor profile from a list of options. The program displays the options to the user and prompts them to select their preferred option by entering a number. The program then processes the user’s choice by assigning two flavor profiles based on the chosen option. To make things a little interesting, I have made all the statements said by the Python program to be similar to that of <strong>Ryan Reynolds</strong> (courtesy of ChatGPT) and it seems pretty funny.</p><p>If the user selects option 4, the program prompts the user to enter their preferred flavor profiles. If the entered flavor profiles are not valid, the program prompts the user to enter valid flavor profiles. If the user only selects one flavor profile, the program prints the selected flavor profile. Otherwise, the program recommends complementary flavor profiles and prompts the user to confirm whether they want to accept the recommendations or not. The program then prints the preferred flavor profiles and a message acknowledging the user’s choice.</p><pre># Define possible flavor profiles<br>flavors = [&#39;Sweet&#39;, &#39;Sour&#39;, &#39;Bitter&#39;, &#39;Refreshing&#39;, &#39;Creamy&#39;]<br><br># Set complimentary flavours<br>complementary_flavors={<br>    &#39;Sweet&#39;:&#39;Sour&#39;,<br>    &#39;Sour&#39;:&#39;Sweet&#39;,<br>    &#39;Bitter&#39;:&#39;Refreshing&#39;,<br>    &#39;Refreshing&#39;:&#39;Bitter&#39;,<br>    &#39;Creamy&#39;:&#39;Refreshing&#39;<br>}<br><br># Display options to the user<br>print(&quot;Hey there! We&#39;ve got some amazing options for you to choose from. Take a look at these options:&quot;)<br>print(&quot;1. Sweet &amp; Sour - for those who like it classic&quot;)<br>print(&quot;2. Creamy &amp; Refreshing - because life&#39;s too short to be anything else&quot;)<br>print(&quot;3. Bitter &amp; Refreshing - for the adventurous souls out there&quot;)<br>print(&quot;4. Custom - because you&#39;re a rebel, and we like that!&quot;)<br><br># Get user&#39;s choice<br>choice = input(&quot;\nAlright, let&#39;s get to it. What&#39;s your poison? Enter the number of your preferred option:&quot;)<br><br># Process user&#39;s choice<br>if choice == &quot;1&quot;:<br>    flavour_1 = &quot;Sweet&quot;<br>    flavour_2 = &quot;Sour&quot;<br>    print(&quot;Ah, the classic sweet and sour combo. You have a refined palate!&quot;)<br>    preferred_flavors = [flavour_1, flavour_2]<br>elif choice == &quot;2&quot;:<br>    flavour_1 = &quot;Creamy&quot;<br>    flavour_2 = &quot;Refreshing&quot;<br>    print(&quot;Creamy and refreshing? You&#39;re definitely a person who knows how to keep it cool!&quot;)<br>    preferred_flavors = [flavour_1, flavour_2]<br>elif choice == &quot;3&quot;:<br>    flavour_1 = &quot;Bitter&quot;<br>    flavour_2 = &quot;Refreshing&quot;<br>    print(&quot;Bitter and refreshing? You like to live dangerously, don&#39;t you?&quot;)<br>    preferred_flavors = [flavour_1, flavour_2]<br>elif choice == &quot;4&quot;:<br>    flavour_1 = input(&#39;What is the first flavor profile would you like? (Sweet, Sour, Bitter, Refreshing, Creamy)&#39;)<br>    if flavour_1 not in flavors:<br>        print(&quot;That is not a valid flavour profile (atleast according to my program&quot;)<br>        flavour_1 = input(&quot;Please enter a valid flavour profile - Sweet, Sour, Bitter, Refreshing, Creamy&quot;)<br><br>    flavour_2 = input(&#39;What is the second flavor profile would you like? (Sweet, Sour, Bitter, Refreshing, Creamy) (Leave blank if you only want one flavor profile)&#39;)<br>    if flavour_2:<br>        if flavour_2 not in flavors:<br>            print(&quot;That is a not valid flavour profile&quot;)<br>            flavour_2 = input(&quot;Please enter a valid flavour profile&quot;)<br><br><br>        if flavour_1 == flavour_2:<br>            print(&quot;Both flavors can&#39;t be the same. Please try again.&quot;)<br>            flavour_2 = input(&#39;Press Enter if you only want one&#39;)<br><br>        # Recommend complementary flavor profile if only one flavor is sweet or sour<br>        if flavour_1 in [&#39;Sweet&#39;, &#39;Sour&#39;] and flavour_2 not in [&#39;Sweet&#39;, &#39;Sour&#39;]:<br>            print(f&quot;You chose {flavour_1} as your first flavor profile. We recommend {complementary_flavors[flavour_1]} as your second flavor profile.&quot;)<br>            ans = input(&quot;Type &#39;Yes&#39; if you want to this new combination - Sweet &amp; Sour or if you type anything else, we will go ahead with your choice&quot;)<br>            if(ans.lower() == &#39;yes&#39;):<br>                flavour_2 = complementary_flavors[flavour_1]<br>            else:<br>                flavour_2 = flavour_2<br>        elif flavour_2 in [&#39;Sweet&#39;, &#39;Sour&#39;] and flavour_1 not in [&#39;Sweet&#39;, &#39;Sour&#39;]:<br>            print(f&quot;You chose {flavour_2} as your second flavor profile. We recommend {complementary_flavors[flavour_2]} as your first flavor profile.&quot;)<br>            ans = input(&quot;Type &#39;Yes&#39; if you want to this new combination - Sweet &amp; Sour or if you type anything else, we will go ahead with your choice&quot;)<br>            if(ans.lower()  == &#39;yes&#39;):<br>                flavour_1 = complementary_flavors[flavour_2]<br>            else:<br>                flavour_1 = flavour_1<br>        elif flavour_1 in [&#39;Bitter&#39;, &#39;Refreshing&#39;] and flavour_2 not in [&#39;Bitter&#39;, &#39;Refreshing&#39;]:<br>            print(f&quot;You chose {flavour_1} as your first flavor profile. We recommend {complementary_flavors[flavour_1]} as your second flavor profile.&quot;)<br>            ans = input(&quot;Type &#39;Yes&#39; if you want to this new combination - Bitter &amp; Refreshing or if you type anything else, we will go ahead with your choice&quot;)<br>            if(ans.lower()  == &#39;yes&#39;):<br>                flavour_2 = complementary_flavors[flavour_2]<br>            else:<br>                flavour_2 = flavour_2<br>        elif flavour_2 in [&#39;Bitter&#39;, &#39;Refreshing&#39;] and flavour_1 not in [&#39;Bitter&#39;, &#39;Refreshing&#39;]:<br>            print(f&quot;You chose {flavour_2} as your second flavor profile. We recommend {complementary_flavors[flavour_2]} as your first flavor profile.&quot;)<br>            ans = input(&quot;Type &#39;Yes&#39; if you want to this new combination - Bitter &amp; Resfreshing or if you type anything else, we will go ahead with your choice&quot;)<br>            if(ans.lower()  == &#39;yes&#39;):<br>                flavour_1 = complementary_flavors[flavour_2]<br>            else:<br>                flavour_1 = flavour_1<br>        elif flavour_2 in [&#39;Creamy&#39;, &#39;Refreshing&#39;] and flavour_1 not in [&#39;Creamy&#39;, &#39;Refreshing&#39;]:<br>            print(f&quot;You chose {flavour_2} as your second flavor profile. We recommend {complementary_flavors[flavour_2]} as your first flavor profile.&quot;)<br>            ans = input(&quot;Type &#39;Yes&#39; if you want to this new combination - Creamy &amp; Refreshing or if you type anything else, we will go ahead with your choice&quot;)<br>            if(ans.lower()  == &#39;yes&#39;):<br>                flavour_1 = complementary_flavors[flavour_2]<br>            else:<br>                flavour_1 = flavour_1<br><br>        # Print preferred flavor profiles<br>        print(f&quot;Your preferred flavor profiles are: {flavour_1} and {flavour_2}&quot;)<br>        print(&quot;Custom, eh? You&#39;re the adventurous type, I like it!&quot;)<br><br>        preferred_flavors = [flavour_1, flavour_2]<br>    else:<br>        print(f&quot;You have chosen only {flavour_1} flavor profile.&quot;)<br>        preferred_flavors = [flavour_1]</pre><h4>Example of the output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngDIOm3Z1wHYULOXDlU-DQ.png" /></figure><p><strong>(OPTIONAL) 5. Asking the user to rate some mocktails: </strong>In the previous project, the program used user ratings as the primary input to generate movie recommendations. However, for the current project, the approach is different. Instead of asking the user to rate the mocktails, the program is only asking for their preferred flavor profiles. This means that the program is not solely relying on user preferences to generate recommendations. Instead, it is utilizing the dataset of over 100 mocktail recipes with their respective flavor profiles and ingredients to create the combinations that match the user’s preference. This approach can help in generating more diverse and accurate mocktail recommendations for the user, as it takes into account the compatibility between different ingredients and flavor profiles, in addition to the user’s preference.</p><h3>Step 2: <strong>Filter matching ingredients &amp; Generate possible combinations</strong></h3><p>After completing the initial steps of loading the dataset and accepting the user’s preferred flavor profiles, the next crucial step in the process is to find the ingredients that match the selected flavor profiles and generate mocktail combinations that are in line with the user’s preferences.</p><p>To achieve this, we start by creating a list of all the ingredients that are present in the mocktails belonging to one of the user-selected flavor profiles. This list is compiled by analyzing the ingredients used in each mocktail belonging to the chosen flavor profile.</p><p>Once we have a comprehensive list of ingredients, we can move on to generating all possible mocktail combinations that contain three ingredients. This is done by considering every possible combination of three ingredients from the compiled ingredient list. The generation of mocktail combinations in this way ensures that we explore all possible combinations that match the selected flavor profiles, providing the user with a wide range of options to choose from.</p><h3>Code</h3><h4>1. Filtering ingredients for preferred flavors</h4><p>This code defines two functions that are used to filter a dataset of ingredients based on a user’s preferred flavor profile(s).</p><p>The has_flavor() function takes three arguments: ingredient (a string representing the name of an ingredient), flavor_profiles (a list of strings representing the user&#39;s preferred flavor profile(s)), and df (a pandas DataFrame containing ingredient data). The function first checks if the ingredient is in the dataset df by checking if the Ingredient 1 column of df contains the ingredient. If the ingredient is not in the dataset, the function returns False. If the ingredient is in the dataset, the function counts the number of times it appears in the Ingredient 1 column of df. For each row where ingredient appears in the Ingredient 1 column, the function checks if the row has one of the desired flavor profiles in either the Flavor Profile 1 or Flavor Profile 2 columns. If any row has a desired flavor profile, the function returns True. If none of the rows have a desired flavor profile, the function returns False.</p><p>The filter_by_flavor() function takes two arguments: df (a pandas DataFrame containing ingredient data) and preferred_flavors (a list of strings representing the user&#39;s preferred flavor profile(s)). The function initializes an empty set matching_ingredients to store the ingredients that match the user&#39;s preferred flavors. The function then loops through each preferred flavor in preferred_flavors and filters the dataset df to find ingredients that have the desired flavor profile using the has_flavor() function. The filtered dataset is stored in the variable filtered_df. The function then updates the matching_ingredients set to include the ingredients in the filtered dataset by using the unique() method to get the unique values of the Ingredient 1, Ingredient 2, and Ingredient 3 columns in the filtered dataset and using the set union (|=) operator to add these unique values to the matching_ingredients set. Finally, the function returns the matching_ingredients set, which contains all the ingredients that match the user&#39;s preferred flavors.</p><pre># Check if the ingredient is part of the users preferred flavour profile(s)<br>def has_flavor(ingredient, flavor_profiles, df):<br>    # Check if the ingredient is in the dataset<br>    if not df[&#39;Ingredient 1&#39;].isin([ingredient]).any():<br>        return False<br>    <br>    # Get the number of ingredients in the row<br>    num_ingredients = df.loc[df[&#39;Ingredient 1&#39;] == ingredient].shape[0]<br>    <br>    # Check if the ingredient has the desired flavor profile in any of its columns<br>    for i in range(num_ingredients):<br>        row = df.loc[df[&#39;Ingredient 1&#39;] == ingredient].iloc[i]<br>        if any(flavor in [row[&#39;Flavor Profile 1&#39;], row[&#39;Flavor Profile 2&#39;]] for flavor in flavor_profiles):<br>            return True<br>    <br>    # If none of the ingredients have the desired flavor profile, return False<br>    return False<br>    <br># Return all ingredients with users preferred flavours<br>def filter_by_flavor(df, preferred_flavors):<br>    matching_ingredients = set()<br>    for flavor in preferred_flavors:<br>        # Filter the dataset to find ingredients with the desired flavor profile<br>        filtered_df = df[(df.apply(lambda x: has_flavor(x[&#39;Ingredient 1&#39;], [flavor], df) or <br>                                   has_flavor(x[&#39;Ingredient 2&#39;], [flavor], df) or <br>                                   has_flavor(x[&#39;Ingredient 3&#39;], [flavor], df) if len(x) &gt; 0 else False, axis=1))]<br>        matching_ingredients |= set(filtered_df[&#39;Ingredient 1&#39;].unique()) | set(filtered_df[&#39;Ingredient 2&#39;].unique()) | set(filtered_df[&#39;Ingredient 3&#39;].unique())<br>    return matching_ingredients</pre><h4>2. Displaying the ingredients with either one of the required flavor profiles</h4><p>This code filters a data frame of all possible ingredients by preferred flavors and then selects the first 60 matching ingredients to be used in the mocktail creation process. Unfortunately, due to the strain on computing resources, we had to limit the number of ingredients to 60 out of the possible 100. Who knew creating mocktails could be so computationally intense? But fear not, with our neurosymbolic AI system, we are still able to create delicious and unique mocktails using this limited set of ingredients!</p><pre># Filter the dataframe by preferred flavors and getting all ingredients for either flavour profile<br>matching_ingredients = filter_by_flavor(df, preferred_flavors)<br>matching_ingredients = list(matching_ingredients)[:60]<br>print(&quot;Matching ingredients&quot;, matching_ingredients)<br>print()<br>print(&quot;Total number of matching ingredients&quot;, len(matching_ingredients))</pre><h4>Example Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y_PwvDYzWciVJXwHIs8Fag.png" /></figure><h4>3. Generating all possible combinations of 3 ingredients for a mocktail</h4><p>This code generates all possible combinations of 3 ingredients from the set of matching ingredients. It first initializes an empty list called “possible_combinations” to store all the combinations. Then, it uses a nested loop to iterate over all possible combinations of 3 ingredients from the matching ingredients.</p><p>After generating each combination, it checks if it already exists in the list “possible_combinations”. If it does not exist, it appends the combination to the list.</p><p>Next, it creates a new list called “new_list” to store all the unique combinations. It uses a for loop to iterate over each combination in “possible_combinations”. For each combination, it sorts the ingredients alphabetically and converts them into a tuple, then checks if the sorted combination already exists in “new_list”. If it does not exist, it appends the sorted combination to “new_list”.</p><p>The code then prints out all the possible combinations and the total number of all possible combinations. It is worth noting that due to limited computing resources, the code is generating combinations using only 60 ingredients.</p><pre># Generate all possible combinations of 3 ingredients from the set<br>possible_combinations = []<br><br>for i in range(len(matching_ingredients)):<br>    for j in range(i+1, len(matching_ingredients)):<br>        for k in range(j+1, len(matching_ingredients)):<br>            combination = [matching_ingredients[i], matching_ingredients[j], matching_ingredients[k]]<br>            if combination not in possible_combinations:<br>                possible_combinations.append(combination)<br>new_list = []<br>for combination in possible_combinations:<br>    sorted_combination = tuple(sorted(combination))<br>    if sorted_combination not in new_list:<br>        new_list.append(sorted_combination)<br>        <br>print()<br>print(&quot;All possible combinations&quot;)<br>print(&quot;Total number of all possible combinations&quot;, len(new_list))<br>print()</pre><h4>Example output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*zadfxFJGOhioUOrvoiF5tA.png" /></figure><p>There are a total of 34220 possible mocktail combinations!</p><h3>Step 3: <strong>Symbolic reasoning</strong></h3><p>The symbolic reasoning component for a neurosymbolic AI system contains a set of logical rules that check the feasibility of a given combination of ingredients for a drink based on a specified flavor profile. The function uses a set of rules that incorporate domain-specific knowledge about flavor pairings and incompatibilities among ingredients, as well as constraints for certain flavor profiles. By applying these rules, the function determines whether the combination of ingredients satisfies the given criteria or not. This type of symbolic reasoning can be useful for AI systems that require domain-specific knowledge to perform tasks, such as in the case of food and beverage recommendation systems.</p><h3>Code</h3><h4>1. A function to remove all bad &amp; incompatible combinations of mocktails</h4><p>This code defines a function called is_feasible that checks whether a given combination of ingredients is feasible based on a set of rules. The function takes two inputs: the combination of ingredients and the flavor profile of the drink. The function first checks if any of the ingredients in the combination are incompatible with each other or with the given flavor profile. If any of the rules are violated, the function returns False; otherwise, the function returns True. The rules include avoiding combinations of ingredients that may clash in flavor, avoiding combinations of ingredients that may cause unpleasant textures or curdling, and avoiding combinations of ingredients that may result in an overpowering sweetness. The function also checks whether the combination of ingredients contains specific ingredients that are not compatible with certain flavor profiles, such as &#39;Jalapeno&#39; or &#39;Soda Water&#39; with &#39;Creamy&#39; flavor.</p><pre>#This is a function that checks if a given combination of ingredients is feasible, based on a set of rules.<br>#The function takes two inputs: the combination of ingredients, and the flavor profile of the drink.<br>#The function checks if any of the ingredients in the combination are incompatible with each other or with the given flavor profile.<br>#If any of the rules are violated, the function returns False.<br>#Otherwise, the function returns True.<br><br>def is_feasible(combination, flavor_profile):<br>    # Based on flavour profiles<br>    if(len(flavor_profile)==1):<br>        flavor_1 = flavor_profile[0]<br>    else:<br>        flavor_1 = flavor_profile[0]<br>        flavor_2 = flavor_profile[1]<br>        <br>    creamc = 0    <br>    <br>    if(len(flavor_profile)==1):<br>        if(flavor_1 == &quot;Creamy&quot;):<br>            if &#39;Jalapeno&#39; in combination or &#39;Soda Water&#39; in combination:<br>                return False<br>            cream = [&#39;Yogurt&#39;, &#39;Coconut Milk&#39;, &#39;Milk&#39;, &#39;Coconut Cream&#39;]<br>            for ingredient in combination:<br>                if ingredient in cream:<br>                    creamc = creamc + 1<br>            if(creamc&lt;1 or creamc&gt;1):<br>                    return False<br>        elif(flavor_1==&quot;Sour&quot;):<br>            if &#39;Coconut Cream&#39; in combination:<br>                return False<br>            notsour = [&#39;Yogurt&#39;, &#39;Cinnamon Stick&#39;, &#39;Orange Peel&#39;, &#39;Apple Cider&#39;, &#39;Maraschino Cherry&#39;, &#39;Star Anise&#39;, &#39;Worcestershire Sauce&#39;, &#39;Carrot Juice&#39;, &#39;Beetroot Juice&#39;, &#39;Passionfruit Juice&#39;, &#39;Spinach&#39;, &#39;Cola&#39;, &#39;Raspberries&#39;, &#39;Vanilla Extract&#39;, &#39;Cherry Syrup&#39;, &#39;Tabasco Sauce&#39;, &#39;Celery Juice&#39;, &#39;Honey&#39;, &#39;Grenadine&#39;, &#39;Mango&#39;]<br>            for ingredient in combination:<br>                    if ingredient in notsour:<br>                        return False<br>            if &#39;Lime Juice&#39; not in combination or &#39;Lemon Juice&#39; not in combination or &#39;Grapefruit juice&#39; not in combination or &#39;Pomegranate juice&#39; not in combination:<br>                return False<br>        <br>            <br>    if &#39;Sweet&#39; in flavor_profile:<br>        if &#39;Jalapeno&#39; in combination or &#39;Grapefruit Juice&#39; in combination or &#39;Lime Juice&#39; in combination:<br>            return False<br>    <br>    if(flavor_1 == &quot;Creamy&quot; or flavor_2 == &#39;Creamy&#39;):<br>            if &#39;Jalapeno&#39; in combination or &#39;Soda Water&#39; in combination:<br>                return False<br>            cream = [&#39;Yogurt&#39;, &#39;Coconut Milk&#39;, &#39;Milk&#39;, &#39;Coconut Cream&#39;]<br>            for ingredient in combination:<br>                if ingredient in cream:<br>                    creamc = creamc + 1<br>            if(creamc&lt;1 or creamc&gt;1):<br>                return False<br>            <br>    if(len(flavor_profile)==2):<br>        #Sweet and Sour<br>        if(flavor_1 in [&quot;Sweet&quot;,&quot;Sour&quot;] and flavor_2 in [&quot;Sweet&quot;, &quot;Sour&quot;]):<br>            if &#39;Milk&#39; in combination or &#39;Coconut Cream&#39; in combination:<br>                return False<br>        if(flavor_1 in [&quot;Creamy&quot;, &quot;Refreshing&quot;] and flavor_2 in [&quot;Creamy, Refreshing&quot;]):<br>            if &#39;Grenadine&#39; in combination and &#39;Milk&#39; in combination:<br>                return False<br>            cream = [&#39;Yogurt&#39;, &#39;Coconut Milk&#39;, &#39;Coconut Cream&#39;]<br>            for ingredient in combination:<br>                if ingredient in cream:<br>                    creamc = creamc + 1<br>            if(creamc&lt;1 or creamc&gt;1):<br>                return False<br>                <br>    # Removing all combinations with ingredients which do not work<br>    # Avoid using both banana and blueberries together, as their flavors may clash/they may produce an unappetizing texture.<br>    if &#39;Banana&#39; in combination and (&#39;Blueberries&#39; in combination or &#39;Raspberries&#39; in combination):<br>        return False  <br>    <br>    # Avoid combining maraschino cherry with lime juice, as they may not complement each other well.<br>    if &#39;Maraschino Cherry&#39; in combination and (&#39;Lime Juice&#39; in combination or &#39;Cola&#39; in combination):<br>        return False  <br>    <br>    # Do not use milk with any citrus-based ingredients, such as lime juice, as the acidity may cause the milk to curdle.<br>    if &#39;Milk&#39; in combination and (&#39;Lime Juice&#39; in combination or &#39;Pineapple Juice&#39; in combination):<br>        return False  <br>    <br>    # Avoid using both coconut cream and cola, as the sweetness and creaminess of coconut may not work well with the carbonation of cola.<br>    if &#39;Coconut Cream&#39; in combination and (&#39;Cola&#39; in combination or &#39;Simple Syrup&#39; in combination):<br>        return False <br>    <br>    # Avoid using both pineapple juice or blueberries and lime juice, as their flavors may clash.<br>    if (&#39;Pineapple Juice&#39; in combination or &#39;Blueberries&#39; in combination) and &#39;Lime Juice&#39; in combination:<br>        return False  <br>    <br>    # Do not use both blueberries and maraschino cherry or coconut cream together, as their flavors may clash.<br>    if &#39;Blueberries&#39; in combination and (&#39;Maraschino Cherry&#39; in combination or &#39;Coconut Cream&#39; in combination):<br>        return False  <br>    <br>    # Avoid using both simple syrup and sugar with coconut cream, as the sweetness may become overpowering.<br>    if &#39;Coconut cream&#39; in combination and (&#39;Simple Syrup&#39; in combination or &#39;Sugar&#39; in combination):<br>        return False <br>    <br>    # Avoid using both maraschino cherry/simple syrup/blueberry  and sugar together, as the sweetness may become overpowering.<br>    if (&#39;Blueberries&#39; in combination or &#39;Maraschino Cherry&#39; in combination or&#39;Simple Syrup&#39; in combination)and &#39;Sugar&#39; in combination:<br>        return False  <br><br>    # Avoid using both cola and lime juice together, as their flavors may clash.<br>    if (&#39;Cola&#39; in combination or &#39;Lemon&#39; in combination) and &#39;Lime Juice&#39; in combination:<br>        return False<br>    <br>    # Remove any combination that contains both pineapple and cranberry juice as they have strong, distinct flavors that may clash and be overpowering when combined.<br>    if &#39;Pineapple Juice&#39; in combination and &#39;Cranberry Juice&#39; in combination:<br>        return False<br>    <br>    #Remove any combination that contains both sprite and sugar as sprite is already sweetened and adding more sugar may make the drink too sweet.<br>    if &#39;Sprite&#39; in combination and (&#39;Club Soda&#39; in combination or &#39;Sugar&#39; in combination):<br>        return False<br>    <br>    # Remove any combination that includes both kiwi juice and grapefruit slice, as the flavors may not complement each other.<br>    if (&#39;Kiwi Juice&#39; in combination or &#39;Banana&#39; in combination or &#39;Mango&#39; in combination) and &#39;Grapefruit Slice&#39; in combination:<br>        return False<br>    <br>    # Remove any combination that includes both mango and mint leaves/blueberries, as the flavors may clash.<br>    if &#39;Mango&#39; in combination and (&#39;Mint Leaves&#39; in combination or  &#39;Blackberries&#39; in combination):<br>        return False<br>    <br>    # Remove any combination that includes both apple cider and coconut milk, as the flavors may clash.<br>    if (&#39;Apple Cider&#39; in combination or &#39;Raspberry&#39; in combination or &#39;Cinnamon Stick&#39; in combination) and &#39;Coconut Milk&#39; in combination:<br>        return False<br>    <br>    # Remove combinations that include both citrus and dairy, as they can curdle.<br>    if (&#39;Grapefruit&#39; in combination or &#39;Lemon&#39; in combination or &#39;Lime&#39; in combination or &#39;Orange&#39; in combination or &#39;Tangerine&#39; in combination) and (&#39;Milk&#39; in combination or &#39;Yogurt&#39; in combination):<br>        return False<br>    <br>    # Remove combinations that include both mint and cinnamon stick, as they can clash in flavor/they may produce a strange aftertaste.<br>    if &#39;Mint Leaves&#39; in combination and (&#39;Cinnamon Stick&#39; in combination or &#39;Star Anise&#39; in combination):<br>        return False<br>    <br>    # Remove combinations that include both kiwi juice and apple cider, as they may produce a gritty texture.<br>    if &#39;Kiwi Juice&#39; in combination and &#39;Apple Cider&#39; in combination:<br>        return False<br>    <br>    # No combination should contain both Sage Leaves and Maraschino Cherry.<br>    if &#39;Sage Leaves&#39; in combination and (&#39;Maraschino Cherry&#39; in combination or &#39;Tonic Water&#39; in combination):<br>        return False<br>    <br>    # Avoid combining Lime Juice and Simple Syrup, Lime.<br>    if &#39;Lime juice&#39; in combination and &#39;Simple Syrup, Lime&#39; in combination:<br>        return False<br>    <br>    # No combination should contain both Jalapeno and Raspberries.<br>    if &#39;Jalapeno&#39; in combination and &#39;Raspberries&#39; in combination:<br>        return False<br>    <br>    # Avoid combining Maraschino Cherry or Grenadine with Lime Juice or Mint Leaves.<br>    if (&#39;Maraschino Cherry&#39; in combination or &#39;Grenadine&#39; in combination) and (&#39;Lime Juice&#39; in combination or &#39;Mint Leaves&#39; in combination):<br>        return False<br>    <br>    #More conditions exist (On my GitHub page)...<br>    <br>    # If none of the above conditions are met, then the combination is feasible<br>    return True<br><br>def get_feasible_combinations(possible_combinations, preferred_flavors):<br>    feasible_combinations = []<br>    for combination in possible_combinations:<br>        if is_feasible(combination, preferred_flavors):<br>            feasible_combinations.append(combination)<br>    return feasible_combinations<br><br><br>possible_combinations = get_feasible_combinations(new_list, preferred_flavors)<br>print()<br>print(&quot;Feasible Combinations&quot;)<br>print(&quot;Total number of all possible combinations&quot;, len(possible_combinations))<br>print()</pre><h4>Example Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*8DSdQ6M8fpWJYG3BGMhwUA.png" /></figure><p>So we finally got 3787 possible mocktails from a total of 34220 combinations. This is possible because only certain ingredients (like coconut cream, coconut milk, milk, and yogurt) can be used to create a creamy mocktail. The number is bound to be higher with other combinations without a creamy flavor profile. However, this process can be further improved and simplified with more rules or even using advanced knowledge graphs.</p><h3>Step 4: Neural AI</h3><p>The neural part of our neurosymbolic AI system is built using a deep learning model implemented in Keras. We define the model architecture using the Sequential API and add several densely connected layers with varying numbers of neurons and activation functions. The first layer has 256 neurons with the rectified linear unit (ReLU) activation function and takes as input the shape of our training data. We then add a dropout layer with a rate of 0.3 to reduce overfitting. We repeat this pattern for three more layers with decreasing numbers of neurons until we reach our output layer, which has a single neuron and a linear activation function.</p><p>To prevent overfitting during training, we use the early stopping technique with a patience of 10. This means that if our model’s validation loss does not improve for 10 consecutive epochs, the training will stop early.</p><p>Finally, we compile our model using the mean squared error loss function, the Adam optimizer, and the mean absolute error metric. We then train our model on our training data with a batch size of 32 and for a maximum of 100 epochs, while monitoring the validation loss for early stopping.</p><h3>Code</h3><h4>1. Convert the dataset into the format required for neural network</h4><p>This code is for preparing data for a neural network that predicts user ratings of food recipes based on their ingredients and flavor profiles. Here’s a detailed explanation:</p><p>The first few lines of code create a list of all ingredients present in the dataset. df is a pandas data frame containing information about various recipes. ingredients_1, ingredients_2, and ingredients_3 are lists of the first, second, and third ingredients in each recipe respectively. The for loops use list comprehensions to extract these values from the data frame. These three lists are concatenated into all_ingredients, which is converted to a set to remove duplicates. The code then defines a list of possible flavor profiles, including “Sour”, “Sweet”, “Bitter”, “Creamy”, and “Refreshing”.</p><p>The row_to_input() function is defined to convert a row of the data frame into an input format that can be fed into a neural network. The function takes a single argument, rowwhich is a pandas Series containing information about a single recipe. The function first initializes two empty lists, ingredients and flavors, which will be populated with the recipe&#39;s ingredients and their corresponding flavor profiles.</p><p>The function then loops through each of the first three ingredients in the recipe (if present), extracting each ingredient and checking if it is not NaN using pd.notna(). If the ingredient is present, it is added to the ingredients list. The function then checks if the ingredient is present in all_ingredients. If it is, the function creates a new data frame ingredient_df containing only those rows where the ingredient appears in one of the three ingredient columns. The function then extracts the flavor profile for the first matching row in ingredient_df and converts it to a one-hot encoding (a binary vector indicating which of the possible flavor profiles are present in the ingredient). This one-hot encoding is appended to the flavors list. If the ingredient is not present in all_ingredients, the flavors list is appended with a vector of zeros (indicating that none of the possible flavor profiles are present).</p><p>Finally, the function checks if any ingredients were added to the ingredients list. If no ingredients were added, the function returns None. Otherwise, the flavors list is flattened into a 1D numpy array and returned.</p><p>The code then splits the dataset into training and testing sets using df.sample() and df.drop(). The training set contains 80% of the rows in the original dataset, chosen randomly with a fixed seed for reproducibility.</p><p>The train_inputs variable is created by applying row_to_input() to each row of the training set using a list comprehension. The resulting list of numpy arrays is then vertically stacked into a 2D array. The train_targets variable is created by extracting the User Rating column from the training dataframe as a numpy array.</p><pre># Get a list of all ingredients    <br>ingredients_1 = [i for i in df[&#39;Ingredient 1&#39;]]<br>ingredients_2 = [j for j in df[&#39;Ingredient 2&#39;]]<br>ingredients_3 = [k for k in df[&#39;Ingredient 3&#39;]]<br>all_ingredients = ingredients_1 + ingredients_2 + ingredients_3<br>all_ingredients = set(all_ingredients)<br><br># Define the list of flavors<br>flavors_list = [&#39;Sour&#39;, &#39;Sweet&#39;, &#39;Bitter&#39;, &#39;Creamy&#39;, &#39;Refreshing&#39;]<br><br># Convert the dataset input into format for neural network<br>def row_to_input(row):<br>    ingredients = []<br>    flavors = []<br>    for i in range(1, 4):<br>        ingredient = row[f&#39;Ingredient {i}&#39;]<br>        if pd.notna(ingredient):<br>            ingredients.append(ingredient)<br>            if ingredient in all_ingredients:<br>                ingredient_df = df[df[[&#39;Ingredient 1&#39;, &#39;Ingredient 2&#39;, &#39;Ingredient 3&#39;]].eq(ingredient).any(1)]<br>                flavor = ingredient_df[&#39;Flavor Profile 1&#39;].values[0]<br>                flavors.append([1 if f in flavor else 0 for f in flavors_list])<br>            else:<br>                flavors.append([0] * len(flavors_list))<br>    if len(ingredients) == 0:<br>        return None<br>    else:<br>        return np.array(flavors).flatten()<br><br># Split the data into training and testing data sets<br>train_df = df.sample(frac=0.8, random_state=123)<br>test_df = df.drop(train_df.index)<br><br># Convert the training and testing dataframes into TensorFlow inputs<br>train_inputs = [row_to_input(row) for _, row in train_df.iterrows() if row_to_input(row) is not None]<br>train_inputs = np.vstack(train_inputs)<br>train_targets = np.array(train_df[&#39;User Rating&#39;])</pre><h4>2. Creating a neural network model for predicting user ratings of mocktails</h4><p>This code is implementing a neural network model to predict the user rating of a mocktail based on its ingredients and flavor profiles.</p><p>First, the code defines the model architecture using the Keras Sequential model. The model consists of several Dense layers with ReLU activation functions, followed by Dropout layers to prevent overfitting. The final output layer has a linear activation function, as the goal is to predict a continuous numerical value (user rating).</p><p>The code then compiles the model, specifying the loss function to be mean squared error and the optimizer to be Adam. The model is trained on the training data using early stopping to prevent overfitting.</p><p>Next, the code evaluates the performance of the trained model on the testing data, computing the test loss.</p><p>The code then prompts the user to input the flavor profiles of a new cocktail. The neural network model is used to predict the user rating of every possible combination of three ingredients that match the flavor profiles provided by the user. The highest predicted rating is saved, along with the combination of ingredients that produced it. Finally, the code prints out the best combination of ingredients and its corresponding rating.</p><pre># Define the model architecture<br>model = Sequential()<br>model.add(Dense(256, activation=&#39;relu&#39;, input_dim=train_inputs.shape[1]))<br>model.add(Dropout(0.3))<br>model.add(Dense(128, activation=&#39;relu&#39;))<br>model.add(Dropout(0.3))<br>model.add(Dense(64, activation=&#39;relu&#39;))<br>model.add(Dropout(0.3))<br>model.add(Dense(32, activation=&#39;relu&#39;))<br>model.add(Dense(1, activation=&#39;linear&#39;))<br># Define early stopping<br>early_stopping = EarlyStopping(monitor=&#39;val_loss&#39;, patience=10)<br># Compile the model<br>model.compile(loss=&#39;mean_squared_error&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;mae&#39;])<br># Train the model with early stopping<br>model.fit(train_inputs, train_targets, epochs=100, batch_size=32, validation_split=0.2, callbacks=[early_stopping])<br><br># Evaluate the performance of the model on the testing data<br>test_inputs = [row_to_input(row) for _, row in test_df.iterrows() if row_to_input(row) is not None]<br>test_inputs = np.vstack(test_inputs)<br>test_targets = np.array(test_df[&#39;User Rating&#39;])<br>test_loss = model.evaluate(test_inputs, test_targets)<br>print(&#39;Test loss:&#39;, test_loss)<br><br># Get the flavor profiles of the new cocktail from the user<br>new_flavors = [flavour_1,flavour_2]<br><br># Use neural network to predict the user rating of each possible mocktail<br>best_rating = 0<br>best_combination = possible_combinations[0]<br>for combination in possible_combinations:<br>    # Convert the flavor profiles into the same format as the training data<br>    new_input = row_to_input({&#39;Ingredient 1&#39;: combination[0], &#39;Ingredient 2&#39;: combination[1], &#39;Ingredient 3&#39;: combination[2], &#39;Flavor Profile 1&#39;: new_flavors[0], &#39;Flavor Profile 2&#39;: new_flavors[1]})<br>    # Pass the converted input to the trained model<br>    rating = model.predict(np.array([new_input]))[0][0]<br>    if rating &gt; best_rating:<br>        best_rating = rating<br>        print(rating)<br>        best_combination = combination<br>        print(combination)<br>        <br>print(&quot;Best combination:&quot;, best_combination)<br>print(&quot;Best rating:&quot;, best_rating)</pre><h4>Example Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9EhZoo6i1abaVMAd8MD0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yHymuHn90mz7tiz32d2vPw.png" /></figure><h3>Step 5: Presenting the recommendation</h3><p>This code is creating a mocktail recipe generator that generates a random mocktail name based on the user’s preferred flavors and available ingredients. It has three dictionaries of words: flavor_profile_adjectives, flavor_nouns, and ingredient_nouns.</p><p>flavor_profile_adjectives is a dictionary with five keys, each representing a flavor profile — Sweet, Sour, Bitter, Refreshing, and Creamy. The values are lists of adjectives that describe the flavor profile.</p><p>flavor_nouns is also a dictionary with five keys representing the flavor profiles. The values are lists of nouns that are associated with the flavor profile.</p><p>ingredient_nouns is a dictionary with ingredient names as keys and lists of associated nouns as values.</p><p>The program takes the user’s preferred flavor from a list of flavors provided as input, and the ingredients available for making the mocktail. For each ingredient, it checks if there are any associated nouns in the ingredient_nouns dictionary for the corresponding flavor profile. If there are, it adds these nouns to the flavor_nouns dictionary for that flavor profile.</p><p>It then chooses a random adjective and noun from the appropriate lists in the flavor_profile_adjectives and flavor_nouns dictionaries to create the mocktail name. Finally, it prints the mocktail name and the ingredients needed to make it.</p><pre># Naming the mocktail<br>flavor_profile_adjectives = {<br>    &quot;Sweet&quot;: [&#39;Delicious&#39;, &#39;Divine&#39;, &#39;Heavenly&#39;, &#39;Luscious&#39;, &#39;Yummy&#39;, &#39;Scrumptious&#39;, &#39;Tasty&#39;, &#39;Delectable&#39;],<br>    &quot;Sour&quot;: [&#39;Tangy&#39;, &#39;Zesty&#39;, &#39;Sour&#39;, &#39;Puckery&#39;, &#39;Sharp&#39;, &#39;Lively&#39;, &#39;Fresh&#39;],<br>    &quot;Bitter&quot;: [&#39;Bold&#39;, &#39;Robust&#39;, &#39;Intense&#39;, &#39;Earthy&#39;, &#39;Smokey&#39;, &#39;Complex&#39;, &#39;Strong&#39;],<br>    &quot;Refreshing&quot;: [&#39;Cool&#39;, &#39;Crisp&#39;, &#39;Invigorating&#39;, &#39;Refreshing&#39;, &#39;Revitalizing&#39;, &#39;Soothing&#39;],<br>    &quot;Creamy&quot;: [&#39;Creamy&#39;, &#39;Smooth&#39;, &#39;Silky&#39;, &#39;Luscious&#39;, &#39;Velvety&#39;, &#39;Rich&#39;]<br>}<br><br>flavor_nouns = {<br>    &quot;Sweet&quot;: [&#39;Bliss&#39;, &#39;Crush&#39;, &#39;Dream&#39;, &#39;Delight&#39;, &#39;Sweetheart&#39;],<br>    &quot;Sour&quot;: [&#39;Lemonade&#39;, &#39;Patch&#39;, &#39;Spark&#39;, &#39;Sensation&#39;, &#39;Tingle&#39;],<br>    &quot;Bitter&quot;: [&#39;Bite&#39;, &#39;Kick&#39;, &#39;Symphony&#39;],<br>    &quot;Refreshing&quot;: [&#39;Breeze&#39;, &#39;Splash&#39;, &#39;Chill&#39;, &#39;Refresher&#39;, &#39;Revive&#39;, &#39;Rejuvenation&#39;, &#39;Mist&#39;],<br>    &quot;Creamy&quot;: [&#39;Dream&#39;, &#39;Temptation&#39;, &#39;Refresher&#39;]<br>}<br><br>ingredient_nouns = {<br>  &quot;Lime Juice&quot;: [&quot;Tang&quot;, &quot;Zest&quot;, &quot;Citrus&quot;, &quot;Limeade&quot;],<br>  &quot;Orange Juice&quot;: [&quot;Citrus&quot;, &quot;Orange Blossom&quot;, &quot;Sunny Delight&quot;, &quot;Juice&quot;],<br>  &quot;Agave Syrup&quot;: [&quot;Sweetener&quot;, &quot;Nectar&quot;, &quot;Cactus Syrup&quot;, &quot;Honey&quot;],<br>  &quot;Lemon Lime Soda&quot;: [&quot;Fizz&quot;, &quot;Citrus Bubbles&quot;, &quot;Sprite&quot;, &quot;Carbonated Water&quot;],<br>  &quot;Grenadine&quot;: [&quot;Pomegranate Syrup&quot;, &quot;Sweet Red&quot;, &quot;Ruby&quot;, &quot;Red Syrup&quot;],<br>  &quot;Maraschino Cherry&quot;: [&quot;Red Cherry&quot;, &quot;Sweet Cherry&quot;, &quot;Luxardo&quot;, &quot;Cherry Bomb&quot;],<br>  &quot;Pineapple Juice&quot;: [&quot;Tropic&quot;, &quot;Pineapple Paradise&quot;, &quot;Juicy Pineapple&quot;, &quot;Pineapple Express&quot;],<br>  &quot;Coconut Cream&quot;: [&quot;Cream of Coconut&quot;, &quot;Coconut Milk&quot;, &quot;Coconut Heaven&quot;, &quot;Coconut Dream&quot;],<br>  &quot;Pineapple Slice&quot;: [&quot;Pineapple Spear&quot;, &quot;Pineapple Wedge&quot;, &quot;Pineapple Ring&quot;, &quot;Pineapple Garnish&quot;],<br>  &quot;Mint Leaves&quot;: [&quot;Fresh Mint&quot;, &quot;Cool Mint&quot;, &quot;Mint Sprig&quot;, &quot;Minty&quot;],<br>  &quot;Soda Water&quot;: [&quot;Sparkling Water&quot;, &quot;Bubbly&quot;, &quot;Fizzy&quot;, &quot;Carbonated Water&quot;],<br>  &quot;Strawberries&quot;: [&quot;Berry&quot;, &quot;Sweetheart&quot;, &quot;Strawberry Fields&quot;, &quot;Red Delicious&quot;],<br>  &quot;Simple Syrup&quot;: [&quot;Sweet Syrup&quot;, &quot;Sugar Syrup&quot;, &quot;Clear Syrup&quot;, &quot;Sweetener&quot;],<br>  &quot;Tomato Juice&quot;: [&quot;Tomatoey&quot;, &quot;Savory Juice&quot;, &quot;Bloody Mary Mix&quot;, &quot;Spicy V8&quot;],<br>  &quot;Worcestershire Sauce&quot;: [&quot;Worcestershire&quot;, &quot;Savory Sauce&quot;, &quot;Umami Sauce&quot;, &quot;Bold Sauce&quot;],<br>  &quot;Tabasco Sauce&quot;: [&quot;Hot Sauce&quot;, &quot;Spicy Sauce&quot;, &quot;Pepper Sauce&quot;, &quot;Fiery Sauce&quot;],<br>  &quot;Cherry Syrup&quot;: [&quot;Cherry Juice&quot;, &quot;Sweet Cherry&quot;, &quot;Cherry Cola&quot;, &quot;Cherry Bomb&quot;],<br>  &quot;Cola&quot;: [&quot;Soda&quot;, &quot;Coke&quot;, &quot;Classic&quot;, &quot;Fizzy Drink&quot;],<br>  &quot;Lemonade&quot;: [&quot;Lemon Juice&quot;, &quot;Lemon Refresher&quot;, &quot;Citrus Cooler&quot;, &quot;Lemon Splash&quot;],<br>  &quot;Club Soda&quot;: [&quot;Sparkling Water&quot;, &quot;Bubbly&quot;, &quot;Fizzy&quot;, &quot;Carbonated Water&quot;],<br>  &quot;Peach Syrup&quot;: [&quot;Peach Juice&quot;, &quot;Sweet Peach&quot;, &quot;Peach Fuzz&quot;, &quot;Peachy&quot;],<br>  &quot;Peach Slice&quot;: [&quot;Peach Wedge&quot;, &quot;Peach Garnish&quot;, &quot;Peachy Keen&quot;, &quot;Peach Perfection&quot;],<br>  &quot;Blackberries&quot;: [&quot;Berry&quot;, &quot;Blackberry Bliss&quot;, &quot;Sweetheart&quot;, &quot;Dark Delight&quot;],<br>  &quot;Blueberries&quot;: [&quot;Berry&quot;, &quot;Blueberry Burst&quot;, &quot;Sweetheart&quot;, &quot;Blue Crush&quot;],<br>  &quot;Banana&quot;: [&quot;Banana Cream&quot;, &quot;Banana Split&quot;, &quot;Banana Blast&quot;, &quot;Sweetheart&quot;],<br>  &quot;Yogurt&quot;: [&quot;Creamy&quot;, &quot;Smoothie&quot;, &quot;Yogurt Delight&quot;, &quot;Yogurt Parfait&quot;],<br>  &quot;Honey&quot;: [&quot;Sweetener&quot;, &quot;Nectar&quot;, &quot;Liquid Gold&quot;, &quot;Honeycomb&quot;],<br>  &quot;Spinach&quot;: [&quot;Leafy Green&quot;, &quot;Green Goodness&quot;, &quot;Popeye&#39;s Favorite&quot;, &quot;Healthy Greens&quot;],<br>  &quot;Cranberry Juice&quot;: [&quot;Tart Juice&quot;, &quot;Cranberry Blast&quot;, &quot;Cranberry Splash&quot;, &quot;Ruby Red&quot;],<br>}<br><br>flavor_profile = preferred_flavors[0]<br>ingredients = best_combination<br><br>adjectives = flavor_profile_adjectives[flavor_profile]<br>for ingredient in ingredients:<br>    if ingredient in ingredient_nouns:<br>        nouns = ingredient_nouns[ingredient]<br>        flavor_nouns[flavor_profile].extend(nouns)<br><br>adjective = random.choice(adjectives)<br>noun = random.choice(flavor_nouns[flavor_profile])<br><br>mocktail_name = f&quot;{adjective} {noun} Mocktail&quot;<br>        <br>if best_combination is not None:<br>    print(f&quot;I suggest {mocktail_name}. This is made of {best_combination[0]}, {best_combination[1]}, and {best_combination[2]}. Enjoy!&quot;)<br>else:<br>    print(&quot;Sorry, we couldn&#39;t find a mocktail that satisfies your preferences.&quot;)</pre><p><strong>Example of the output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTa600ZwuG-4NLrrHePyjQ.png" /></figure><h3>Conclusion</h3><p>In conclusion, the development of a neurosymbolic AI system for predicting the best mocktail combinations is a significant achievement in the field of artificial intelligence. By combining neural networks with symbolic reasoning, this system can filter out bad combinations and provide users with the most compatible and delicious mocktail combinations. This innovation has the potential to revolutionize the beverage industry, as well as inspire further research and development in the realm of neurosymbolic AI. Overall, the creation of this system represents a promising step towards more advanced and efficient AI systems that can make complex decisions and judgments, while still taking into account human preferences and tastes.</p><h3>Discussion of future developments &amp; improvements</h3><p>Neurosymbolic AI is an emerging field that combines symbolic reasoning and neural networks to create intelligent systems capable of reasoning and learning. Although it has shown great potential in various domains, including natural language processing, robotics, and healthcare, it is still in its early phases of development. There are different methods for creating neurosymbolic AI systems, and researchers are exploring various approaches.</p><p>In my work, I have used a neurosymbolic AI approach that combines symbolic reasoning with a rule-based system and a neural network component. The symbolic reasoning component filters out bad combinations by using a set of rules based on ingredient clashes and complementarity. The neural network component is then trained only on the good combinations selected by the symbolic reasoning component. This approach allows for efficient and effective training of the neural network.</p><p>However, there is room for improvement in the symbolic reasoning component of the system. In the future, instead of using a rule-based system, a complex knowledge graph can be used to represent ingredients and flavor profiles. This would allow for a more nuanced and flexible representation of the data and could potentially improve the accuracy of the symbolic reasoning component.</p><p>Knowledge graphs are a more advanced method of representing data and relationships between data points. They are essentially a network of nodes (representing data points) and edges (representing relationships between those data points). In the context of a mocktail recommendation system, a knowledge graph might be used to represent the relationships between different ingredients and flavor profiles.</p><p>Using a knowledge graph allows for more complex and nuanced relationships between ingredients to be identified, rather than simply relying on predefined rules. For example, a knowledge graph might identify that certain types of fruit juices can enhance the sweetness of a mocktail when combined with certain herbs, even if this relationship isn’t explicitly stated in a set of rules.</p><h3>References:</h3><p>Image 1: <a href="https://writtygritty.com/top-15-easy-to-make-mocktail-recipes/">https://writtygritty.com/top-15-easy-to-make-mocktail-recipes/</a></p><p>Types of neurosymbolic AI approaches: <a href="https://en.wikipedia.org/wiki/Neuro-symbolic_AI">https://en.wikipedia.org/wiki/Neuro-symbolic_AI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b40f8170f3e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Deep Learning: The Rise of Neurosymbolic AI — Exploring the Cutting-Edge Hybrid Approach to…]]></title>
            <link>https://prabhatm27.medium.com/beyond-deep-learning-the-rise-of-neurosymbolic-ai-exploring-the-cutting-edge-hybrid-approach-to-c8e776132c42?source=rss-f0451664d8fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8e776132c42</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Prabhat M]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 17:41:15 GMT</pubDate>
            <atom:updated>2023-03-29T17:41:15.893Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beyond Deep Learning: The Rise of Neurosymbolic AI — Exploring the Cutting-Edge Hybrid Approach to Artificial Intelligence</h3><p>Imagine there&#39;s this amazing and super intelligent assistant that could assist medical professionals to help diagnose medical conditions. We would want this system to be able to understand the symptoms a patient is exhibiting and make a diagnosis based on logical reasoning and expert knowledge, but at the same time, we would also want it to learn from new cases and improve its overall accuracy over time. However the thing is, a purely symbolic AI system would struggle to handle the complexity and uncertainty of medical diagnosis, while a purely connectionist AI system would lack the ability to reason logically and explain its decisions. (I will be explaining symbolic AI and connectionist AI in depth later). Now, with this technology,Neurosymbolic AI, the system can be used to create a hybrid system that combines the strengths of both approaches(symbolic and connectionist). This system can use symbolic rules and expert knowledge to reason about the symptoms, and then refine its diagnosis based on the results of a neural network trained on a large dataset of medical cases. By using neurosymbolic AI, the system can handle both the complexity of medical diagnosis and the uncertainty of real-world cases, while also providing explanations for its decisions. This example of an medical assistant illustrates the potential of Neurosymbolic AI to create intelligent systems that can reason logically, learn from data, and interact with humans in more natural and intuitive ways, with a wide range of applications in various fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*Dx-HGi-stDFhcLQY" /></figure><h4>Definition of Neurosymbolic AI</h4><p>Neurosymbolic AI refers to an emerging field of artificial intelligence (AI) that <strong>combines symbolic reasoning with connectionist or neural networks.</strong> Symbolic AI is based on <strong>rule-based reasoning and logical inference</strong>, while Connectionist AI relies on <strong>neural networks to learn from data and make predictions</strong>. The integration of these two approaches in Neurosymbolic AI creates a hybrid system that can reason logically, learn from data, and adapt to new situations.</p><p>The <strong>goal of Neurosymbolic AI </strong>is to create more advanced and more intelligent systems that</p><ul><li>can handle uncertainty and ambiguity in real-world situations (as shown in the example before),</li><li>generalize better, and</li><li>interact with humans in more natural and intuitive ways.</li></ul><h4>Importance of Neurosymbolic AI</h4><p>With the rise of advanced AI models like BERT, RoBERTa, and GPT-3, it can be seen that Neurosymbolic AI is becoming increasingly important in the field of artificial intelligence (AI) because it can <strong>combine the strengths of symbolic reasoning and connectionist learning</strong>. Here are some of the key reasons why Neurosymbolic AI is important in today&#39;s world:</p><ol><li><strong>Better generalization:</strong> Neurosymbolic AI can generalize better than purely symbolic or connectionist AI system<strong>s</strong>. Symbolic AI is good at reasoning about abstract concepts and logical rules but struggles with uncertainty and variability in real-world data. Connectionist AI, on the other hand, is good at learning from data but can have difficulty generalizing beyond the training dataset. Neurosymbolic AI can <strong>combine the strengths of both approaches to create systems that can reason logically and learn from data</strong>, leading to better generalization.</li><li><strong>Explainability: </strong>Current deep learning models are considered to be a black box, as not everyone understands how the model gives the output or the process behind it. This is one of the challenges of deep learning and other connectionist approaches. Symbolic AI, on the other hand, is more transparent and easier to understand but can lack the flexibility and adaptability of connectionist approaches. Neurosymbolic AI can <strong>provide both the transparency of symbolic reasoning and the flexibility of connectionist learning</strong>, leading to more explainable and interpretable AI systems.</li><li><strong>Ability to handle uncertainty and ambiguity:</strong> Many real-world problems are characterized by uncertainty and ambiguity, which can be difficult for purely symbolic or connectionist AI systems to handle. Neurosymbolic AI<strong> </strong>can handle uncertainty and ambiguity by<strong> combining the flexibility of connectionist learning with the logical reasoning of symbolic AI.</strong></li><li><strong>Applications in various fields:</strong> Neurosymbolic AI has applications in various fields, including natural language processing, robotics, healthcare, finance, and more. By combining symbolic reasoning and connectionist learning, Neurosymbolic AI can create intelligent systems that<strong> can reason logically, learn from data, and interact with humans in more natural and intuitive ways.</strong></li></ol><p>Overall, Neurosymbolic AI is important because it <strong>can create more powerful, flexible, and transparent AI systems</strong> that can handle uncertainty and ambiguity and have a wide range of applications in various fields.</p><h4>A brief history of Neurosymbolic AI</h4><p>The idea of combining symbolic reasoning with connectionist learning in AI has been around for several decades (almost for the past 30 years), but there has been evidence to suggest that the term “Neurosymbolic AI” was only coined in the early 2000s. Here is a brief history of the development of Neurosymbolic AI from the early 1980s:</p><ol><li><strong>Early work in hybrid AI:</strong> In the 1980s and 1990s, researchers started the process of exploring the idea of combining symbolic reasoning with connectionist learning in AI. One of the earliest mentions of the concept of neurosymbolic AI is in the research paper by Sun, Ron; Bookman, Lawrence (1994) titled “<em>Computational Architectures Integrating Neural and Symbolic Processes</em>.” Kluwer.</li><li><strong>The emergence of hybrid systems:</strong> In the 2000s, researchers began developing hybrid systems that combined symbolic and connectionist approaches more explicitly. One example was seen in the paper by Valiant, Leslie G (2008). “<em>Knowledge Infusion: In Pursuit of Robustness in Artificial Intelligence</em>”.</li><li><strong>Development of Neurosymbolic AI:</strong> Now several companies have invested in creating neurosymbolic models with some popular language models like BERT, GPT using this approach. Another example of a visual neurosymbolic AI system is The Neuro-Symbolic Concept Learner which has been developed by MIT and IBM. The NSCL uses a neural network to process and analyze unstructured data such as natural language text or images, and a symbolic reasoning system to reason over the extracted features and generate explanations based on its knowledge. The symbolic reasoning component of the NSCL uses a knowledge graph to represent the relationships between different concepts, which enables the system to reason about complex relationships and to generate explanations that are grounded in logical rules.</li><li><strong>Recent developments</strong>: In recent years, there have been several exciting developments in Neurosymbolic AI, including the use of graph neural networks for reasoning and the development of new frameworks and tools for building hybrid systems. A new language, called <a href="https://scallop-lang.github.io/">Scallop</a>, has been developed specifically for neurosymbolic programming. There is also a growing interest in using Neurosymbolic AI for applications such as natural language processing, robotics, and drug discovery. An example of recent development of a tool is a research paper by Serafini, Luciano; Garcez, Artur d’Avila (2016–07–07) titled “<em>Logic Tensor Networks: Deep Learning and Logical Reasoning from Data and Knowledge</em>”</li></ol><p>Overall, the history of Neurosymbolic AI reflects most of the efforts of researchers to combine the strengths of symbolic reasoning and connectionist learning in AI, to create more powerful, flexible, and transparent intelligent systems.</p><h3>Components of Neurosymbolic AI — Symbolic AI &amp; Connectionist AI</h3><p>To fully understand Neurosymbolic AI, it’s important to have a deep understanding of the two main components of Neurosymbolic AI which are Symbolic AI and Connectionist AI. Symbolic AI and Connectionist AI represent two <strong>fundamentally different approaches to AI</strong> that have been developed over several decades.</p><p>Symbolic AI, also known as <strong>rule-based or logic-based AI</strong>, is based on the idea of <strong>using symbols and rules to represent knowledge and reasoning</strong>. It is particularly good at handling structured data and reasoning about abstract concepts. However, one of its key limitations is that it can struggle with uncertainty and ambiguity in real-world data, making it less useful for many applications.</p><p>On the other hand, Connectionist AI, also known as <strong>neural network-based AI</strong>, is based on the idea of using <strong>artificial neural networks to learn from data and make predictions</strong>. It is particularly good at handling unstructured data and learning from patterns in the data. However, it can <strong>struggle with reasoning and logical inference</strong>, making it less useful for applications that require more advanced decision-making.</p><p>In the context of Neurosymbolic AI, these <strong>two approaches are combined to create more powerful and flexible AI systems</strong> that can handle a wider range of tasks and applications. By understanding both Symbolic AI and Connectionist AI in depth, we can better understand how they are integrated into Neurosymbolic AI and the potential benefits and limitations of this approach.</p><h3>Symbolic AI</h3><p>Symbolic AI is an <strong>important component</strong> of the Neurosymbolic AI approach. It involves the use of symbols and rules to represent knowledge and perform reasoning tasks. Symbolic AI is particularly useful in domains where <strong>explicit knowledge representation and reasoning are essential</strong>, such as expert systems, natural language processing, and planning. The reason we haveIn the context of Neurosymbolic AI, symbolic reasoning and connectionist learning are integrated to create a <strong>more robust and flexible approach</strong> that can handle complex and dynamic environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r48I8yQiaHsaAgV8" /></figure><h4>Overview of Symbolic AI</h4><p>Symbolic AI, also known as rule-based or logic-based AI, is a branch of artificial intelligence that deals with the <strong>manipulation of symbols and rules to represent and reason knowledge</strong>. It is based on the idea that <strong>human-like intelligence</strong> can be achieved by manipulating symbols and applying rules to them, much like how humans reason about the world.</p><p>In Symbolic AI, knowledge is represented in the form of symbols, such as words or concepts, and rules are used to manipulate these symbols to draw conclusions and make decisions. Symbolic AI systems are <strong>usually built using logic-based programming languages such as Prolog and Lisp.</strong></p><p>The key strength of Symbolic AI is its ability to <strong>handle structured data and reason about abstract concepts</strong>. It is particularly well-suited to tasks that require logical inference, such as <strong>deductive reasoning and planning</strong>. (This brings to mind how police detectives use clues to develop a hypothesis and eventually find the perpetrator). Symbolic AI has been successfully applied in many domains, including expert systems, natural language processing, and robotics.</p><p>However, one of the limitations of Symbolic AI is that <strong>it can struggle with uncertainty and ambiguity in real-world data</strong>. It is less effective at handling unstructured data, such as images and natural language, and can struggle with tasks that require learning from large amounts of data.</p><p>Despite its limitations, Symbolic AI remains an important and active area of research, particularly in combination with Connectionist AI in Neurosymbolic AI systems. By combining the strengths of Symbolic AI and Connectionist AI, researchers are working to create more powerful and flexible AI systems that can handle a wider range of tasks and applications.</p><h4>Knowledge Representation</h4><p>In the this particular context, knowledge representation refers to how information and knowledge are stored and organized so that they can be used by an AI system. In this approach, knowledge is represented using a combination of symbolic and neural techniques.</p><p>Symbolic knowledge representation involves the <strong>use of logic and formal languages to represent knowledge in a structured and organized manner.</strong> This is particularly useful for representing abstract concepts and relationships, such as cause-and-effect relationships, that are <strong>difficult to represent using neural networks alone.</strong></p><p>Neural knowledge representation, on the other hand, involves the use of neural networks to represent knowledge in a way that <strong>mimics how the human brain processes information</strong>. This is particularly useful for representing patterns and relationships that are difficult to describe using formal language.</p><p>By combining these two approaches, neuro-symbolic AI can represent and <strong>reason complex knowledge in a way that is both structured and flexible</strong>. This allows the system to learn and adapt to new information and situations, making it well-suited for a wide range of applications, from natural language processing to robotics and autonomous systems.</p><h4>Rule-based Reasoning</h4><p>Rule-based reasoning is a <strong>type of reasoning in artificial intelligence</strong> that uses a <strong>set of rules to make decisions or draw conclusions about a given problem</strong>. In neuro symbolic AI, rule-based reasoning involves using <strong>both</strong> <strong>symbolic reasoning and neural networks</strong> to process and interpret data.</p><p>The rules in rule-based reasoning are typically represented using <strong>if-then statements.</strong> For example, if a person has a fever, then they may have an infection. In neuro symbolic AI, these rules can be learned by neural networks through a process called knowledge acquisition. Once the rules are learned, <strong>they can be used to make decisions or draw conclusions about new data.</strong></p><p>The neural networks in neuro symbolic AI can also be used to augment the rule-based reasoning process. For example, the neural network can be <strong>trained to recognize patterns in data that may not be immediately apparent using only symbolic reasoning.</strong> This can lead to more accurate and efficient decision-making.</p><p>Overall, rule-based reasoning in neuro symbolic AI allows for the integration of both symbolic reasoning and neural networks to create more powerful and flexible systems for processing and interpreting complex data.</p><h4>Limitations of Symbolic AI</h4><p>Symbolic AI has several limitations that can also apply to Neurosymbolic AI. One major limitation is that symbolic AI systems tend to be brittle and inflexible when it comes to dealing with complex, real-world problems. This is because they are heavily reliant on handcrafted rules and pre-defined knowledge, which can become outdated or incomplete over time. Additionally, symbolic AI is limited in its ability to learn and adapt on its own, as it typically requires significant human input and expertise to create and maintain its knowledge base.</p><p>Another limitation of symbolic AI is its difficulty in dealing with uncertainty and incomplete information. Symbolic AI assumes a perfect understanding of the world, but in reality, there is often ambiguity and uncertainty in the data and information available. This makes it difficult for symbolic AI to reason effectively and make accurate decisions.</p><h3>Connectionist AI</h3><p>Connectionist AI, also known as <strong>neural network-based AI</strong>, emphasizes the use of artificial neural networks to s<strong>imulate the behavior and function of the human brain</strong>. Connectionist AI differs from Symbolic AI in that it focuses on pattern recognition, learning through experience, and the ability to generalize information. Neural networks can adapt to new information and adjust their output based on the input received, making them useful for tasks such as image and speech recognition, natural language processing, and predictive modeling. Connectionist AI has shown promise in many areas and is often used in applications such as <strong>autonomous vehicles, medical diagnosis, and fraud detection</strong>. However, it also faces challenges such as overfitting, training time, and the need for large amounts of data to achieve high accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YBRaPHJZ7GimMncn" /></figure><h4>Overview of Connectionist AI</h4><p>Connectionist AI is an approach to AI that <strong>models the behavior of the brain by using interconnected nodes, or neurons</strong>, that are arranged in layers. These neurons work together to process information and solve problems, learning and improving over time.</p><p>In the context of neuro symbolic AI, connectionist AI can be used to process and analyze data, such as <strong>sensory information, and generate features that can be used in symbolic reasoning</strong>. For example, a neural network can be trained to recognize objects in images, and then this information can be used as input for symbolic reasoning to make decisions based on the identified objects.</p><p>One of the key strengths of connectionist AI is its <strong>ability to learn and adapt to new situations</strong>, making it well-suited for tasks such as image and speech recognition. However, it can be difficult to interpret how the neural network arrives at its conclusions, making it challenging to use in applications where <strong>transparency and interpretability are important</strong>. In addition, connectionist AI often requires large amounts of data and computing power to train and operate effectively.</p><h4>Neural Networks</h4><p>Neural networks are a <strong>type of computational model</strong> used in Connectionist AI that is inspired by the structure and function of biological neural networks in the brain. These networks are composed of layers of artificial neurons that are interconnected with each other through weighted connections. Each neuron receives input signals from the previous layer, processes them using an activation function, and sends output signals to the next layer.</p><p>During training, the weights of the connections are adjusted to optimize the network’s ability to make accurate predictions or classifications on a given set of input data. This training process is typically done using a technique called backpropagation, where the error between the predicted output and the actual output is propagated back through the network to adjust the weights of the connections.</p><p>Neural networks are highly effective in a wide range of applications, including image and speech recognition, natural language processing, and predictive analytics. In neurosymbolic AI, neural networks can be combined with symbolic AI techniques to create hybrid models that can reason with both structured and unstructured data.</p><h4>Training Algorithms</h4><p>Training algorithms are used in connectionist AI to train neural networks to perform specific tasks. These algorithms are used to adjust the weights and biases of the connections between neurons in the network to minimize the error between the network’s output and the desired output. There are several training algorithms used in connectionist AI, including supervised learning, unsupervised learning, and reinforcement learning.</p><p>Supervised learning is the most common training algorithm used in connectionist AI, where the network is trained using labeled examples. In supervised learning, the network is presented with input data along with the desired output. The network then adjusts its weights and biases to minimize the error between its output and the desired output.</p><p>Unsupervised learning, on the other hand, is used when the desired output is not available. In unsupervised learning, the network is presented with input data and is left to find patterns and relationships in the data on its own.</p><p>Reinforcement learning is used in situations where the network interacts with an environment and learns through trial and error. The network is rewarded for correct actions and penalized for incorrect actions, which allows it to learn through feedback.</p><p>Overall, training algorithms are an essential component of connectionist AI, as they allow neural networks to learn and adapt to perform specific tasks.</p><h4>Applications of Connectionist AI</h4><p>Connectionist AI, or neural network-based AI, has a wide range of applications in various fields. Here are some examples:</p><ol><li>Image and speech recognition: Neural networks have proven to be highly effective in image and speech recognition tasks. They can be used to recognize faces, objects, and even emotions from images and videos, as well as to transcribe speech into text.</li><li>Natural language processing: Neural networks are used in natural language processing applications, such as language translation, sentiment analysis, and chatbots. They can learn to understand and generate human-like language.</li><li>Fraud detection: Neural networks are used to detect fraudulent activities in financial transactions. They can learn to identify patterns and anomalies in large amounts of data, helping to prevent fraudulent activities.</li><li>Autonomous vehicles: Neural networks are used in the development of self-driving cars. They can learn to recognize objects on the road, navigate through traffic, and make decisions in real-time.</li><li>Healthcare: Neural networks are used in medical applications such as disease diagnosis, drug discovery, and personalized medicine. They can learn to analyze medical images, predict disease outcomes, and recommend treatment options.</li></ol><p>These are just a few examples of the many applications of connectionist AI. As the technology continues to develop, we can expect to see even more innovative uses of neural networks in the future.</p><h4>Limitations of Connectionist AI</h4><p>Connectionist AI, like any other technology, has its limitations. Here are some limitations of Connectionist AI:</p><ol><li>Limited interpretability: Neural networks are often considered black boxes because of their inability to provide clear explanations for their outputs. This makes it difficult for users to understand why a particular output was produced.</li><li>Large data requirements: Connectionist AI requires a large amount of data to train the neural network. Without sufficient data, the network may not be able to generalize to new data.</li><li>Computationally intensive: Neural networks require a lot of computational power to train and run. This can make them time-consuming and expensive to develop.</li><li>Lack of symbolic reasoning: Connectionist AI is often criticized for its inability to perform symbolic reasoning, which is the ability to manipulate symbols and concepts in a logical and meaningful way.</li><li>Overfitting: Neural networks are prone to overfitting, which occurs when the network is trained too well on the training data and becomes too specific to that data. This can lead to poor performance on new data.</li></ol><p>Despite these limitations, Connectionist AI has been successfully applied in a variety of fields, including image and speech recognition, natural language processing, and robotics.</p><h3>Integration of Symbolic and Connectionist AI</h3><p>The integration of Symbolic AI and Connectionist AI is also known as Neurosymbolic AI. This approach combines the strengths of both symbolic and connectionist AI to create more powerful AI systems. Symbolic AI is good at representing and reasoning with abstract knowledge, while Connectionist AI is good at learning and recognizing patterns in large datasets.</p><p>In Neurosymbolic AI, symbolic knowledge is represented using neural networks, which can learn to reason with this knowledge and perform tasks such as classification, prediction, and decision-making. The integration of symbolic and connectionist AI allows for more flexible and adaptable AI systems, capable of reasoning with complex and uncertain knowledge.</p><p>One approach to integrating symbolic and connectionist AI is to use hybrid models that combine both types of AI. These models can use symbolic reasoning to guide learning in connectionist networks or use connectionist networks to provide symbolic reasoning with more accurate and detailed data.</p><p>Overall, the integration of symbolic and connectionist AI has the potential to create more advanced and capable AI systems, with applications in fields such as healthcare, finance, and robotics.</p><h4>Motivation for Integration</h4><p>The motivation for integrating Symbolic and Connectionist AI is to create a hybrid system that can overcome the limitations of each approach and take advantage of their respective strengths. Symbolic AI is strong in rule-based reasoning and knowledge representation, while Connectionist AI is powerful in pattern recognition and learning from data. By combining these two approaches, we can create a system that can reason symbolically using structured knowledge and learn from data to improve its performance over time. This can lead to more robust and flexible AI systems that can handle complex real-world problems.</p><h4>Hybrid Architectures</h4><p>Several hybrid architectures integrate symbolic and connectionist AI, including:</p><ol><li><strong>Neural-symbolic integration:</strong> This approach uses neural networks to learn representations of symbolic data and combine them with symbolic reasoning methods. For example, a neural network can learn to recognize objects in images and then use symbolic rules to reason about the relationships between those objects.</li><li><strong>Symbolic-neural integration:</strong> In this approach, symbolic reasoning methods are used to generate hypotheses or predictions, which are then evaluated using neural networks. For example, a symbolic reasoning system might generate a hypothesis about the meaning of a sentence, which is then evaluated using a neural network trained to recognize natural language.</li><li><strong>Neuro-fuzzy integration:</strong> This approach combines fuzzy logic, which allows for reasoning with imprecise or uncertain data, with neural networks. This allows for more flexible and robust reasoning in uncertain environments.</li><li><strong>Evolutionary computation and neural networks: </strong>This approach combines evolutionary algorithms, which can optimize complex systems, with neural networks. This allows for the automatic optimization of neural network architectures and parameters.</li></ol><p>These hybrid architectures are motivated by the desire to combine the strengths of symbolic and connectionist AI and to overcome the limitations of each approach when used alone.</p><h4>Neurosymbolic Learning</h4><p>Neurosymbolic learning is an approach to artificial intelligence that combines symbolic reasoning with neural network-based learning. It involves the development of algorithms and architectures that can integrate symbolic reasoning and neural network-based learning techniques seamlessly. The idea behind neurosymbolic learning is to leverage the strengths of both symbolic and connectionist AI to achieve better performance on a wide range of tasks. This hybrid approach allows for more efficient and effective knowledge representation and reasoning, as well as the ability to learn from large amounts of data. Neurosymbolic learning has the potential to be used in a variety of applications, including natural language processing, robotics, and computer vision.</p><h3>Cognitive Neuroscience</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pvZiijRkYMmgnwlZ.jpg" /></figure><h4>Basics of Cognitive Neuroscience</h4><p>Cognitive neuroscience is a field that studies the relationship between the brain and cognitive processes such as perception, attention, memory, language, decision-making, and emotion. It involves the use of various techniques such as brain imaging, electrophysiology, and lesion studies to understand how the brain processes information and how this relates to behavior.</p><p>The field of cognitive neuroscience is interdisciplinary, drawing on knowledge and techniques from neuroscience, psychology, linguistics, philosophy, computer science, and other related fields. It aims to provide a better understanding of how the brain gives rise to behavior and cognition, and how these processes can be altered or optimized.</p><p>Some of the main areas of research in cognitive neuroscience include investigating the neural basis of perception, exploring the mechanisms of attention and working memory, understanding language processing, studying the role of emotion in decision-making, and examining the effects of learning and plasticity on brain function.</p><h4>Neural Basis of Symbolic Reasoning</h4><p>Symbolic reasoning, which involves the manipulation of abstract symbols and logical operations, is believed to be supported by the prefrontal cortex and related areas of the brain. Studies have shown that different regions of the prefrontal cortex are involved in different aspects of symbolic reasoning, such as working memory, rule representation, and task switching. Additionally, there is evidence that symbolic reasoning engages a distributed network of brain regions, including the parietal cortex and the basal ganglia. Neuroimaging studies have also revealed that activity in this network increases as the complexity of symbolic reasoning tasks increases. Overall, while the neural basis of symbolic reasoning is complex and multifaceted, it is clear that it relies on the coordinated activity of multiple brain regions.</p><h4>Neural Basis of Connectionist Learning</h4><p>The neural basis of connectionist learning involves changes in the strengths of synaptic connections between neurons. When a connectionist model is trained on a task, such as recognizing handwritten digits, the weights between neurons are adjusted so that the output of the model matches the correct answer. This adjustment is typically done using an optimization algorithm, such as gradient descent, which iteratively adjusts the weights to minimize the difference between the model’s output and the correct answer. The learning rules used to adjust the weights are based on the principles of Hebbian learning, which states that synapses are strengthened when the neurons connect. This type of learning is thought to be implemented in the brain through a process called long-term potentiation (LTP), which strengthens synapses between neurons that are activated at the same time.</p><h4>Inspiration for Neurosymbolic AI</h4><p>Neurosymbolic AI draws inspiration from the complementary strengths of symbolic AI and connectionist AI. Symbolic AI relies on rules and logic to represent and manipulate knowledge, while connectionist AI uses artificial neural networks to learn from data and make predictions. By combining the two approaches, neurosymbolic AI aims to create more flexible, adaptable, and powerful AI systems that can learn and reason in complex, real-world environments. This interdisciplinary approach also draws inspiration from cognitive neuroscience, which seeks to understand how the brain processes information and performs cognitive tasks, to build more biologically inspired AI systems.</p><h3>Advantages of Neurosymbolic AI</h3><p>Here are some advantages of neurosymbolic AI:</p><ol><li><strong>Better Generalization:</strong> Neurosymbolic AI can better generalize to new scenarios <strong>because it combines the strengths of symbolic reasoning and connectionist learning</strong>. Symbolic reasoning can be used to represent high-level concepts and rules, while connectionist learning can be used to learn patterns and associations in data. By combining these two approaches, Neurosymbolic AI can better generalize to new scenarios.</li><li><strong>Ability to Handle Uncertainty and Ambiguity:</strong> In the real world, many problems are inherently uncertain and ambiguous. Neurosymbolic AI can handle uncertainty and ambiguity by combining probabilistic reasoning with connectionist learning. Probabilistic reasoning can be <strong>used to reason about uncertain or incomplete information</strong>, while connectionist learning can be used to learn patterns in data even if the data is noisy or ambiguous.</li><li><strong>Explainability: </strong>One of the challenges with many machine learning approaches is that they can be difficult to understand and explain. Neurosymbolic AI <strong>can be more easily explained because it uses a combination of symbolic reasoning and connectionist learning</strong>. Symbolic reasoning can be used to represent high-level concepts and rules that are easier for humans to understand, while connectionist learning can be used to learn patterns in data that might be difficult for humans to identify.</li><li><strong>Robustness:</strong> Another advantage of Neurosymbolic AI is its robustness. By combining symbolic reasoning and connectionist learning, Neurosymbolic AI <strong>can be more robust to errors in data or faulty assumptions in the model.</strong> Symbolic reasoning can help to constrain the space of possible solutions, while connectionist learning can adapt to new data and adjust the model accordingly.</li></ol><h3>Applications of Neurosymbolic AI</h3><p>Here’s a brief explanation of each application:</p><ol><li><strong>Natural Language Processing: </strong>Neurosymbolic AI can be used to improve natural language understanding and generation, as it combines the strengths of symbolic and connectionist AI. It can help in tasks such as <strong>text summarization, machine translation, sentiment analysis, and chatbots</strong>.</li><li><strong>Robotics:</strong> Neurosymbolic AI can enable robots to interact with the environment more effectively by combining symbolic reasoning with sensory input. It can also help in tasks such as <strong>object recognition, manipulation, and navigation.</strong></li><li><strong>Healthcare:</strong> Neurosymbolic AI can be used to develop more accurate and interpretable medical diagnostic systems by combining symbolic reasoning with clinical data. It can also help in tasks such as <strong>drug discovery, personalized medicine, and predicting patient outcomes.</strong></li><li><strong>Finance:</strong> Neurosymbolic AI can be used to improve financial forecasting and decision-making by combining symbolic reasoning with large datasets. It can also help in tasks such as <strong>fraud detection, risk assessment, and portfolio optimization.</strong></li></ol><p>Overall, the <strong>unique capabilities of neurosymbolic AI make it a promising approach for solving complex and real-world problems</strong> in a variety of fields.</p><h3>Challenges</h3><ol><li><strong>Scalability: </strong>It refers to the <strong>ability of a system to handle increasing amounts of data, complexity, or size without sacrificing performance.</strong> In neurosymbolic AI, scalability is a challenge because it involves integrating two very different types of AI systems, each with its own set of complexities and requirements. Finding a way to scale neurosymbolic AI systems to handle both types of data efficiently is a major challenge.</li><li><strong>Data requirements: </strong>This refers to the <strong>amount and quality of data needed to train and test a neurosymbolic AI system</strong>. Because neurosymbolic AI involves integrating both symbolic and connectionist AI techniques, it requires a large amount of diverse and complex data to train and test the system. The data must be both structured and unstructured, and it must be relevant to the specific application being developed. Collecting and preparing such data can be time-consuming and expensive, and the data may not always be available or easy to obtain.</li></ol><h3>Future directions</h3><p><strong>Integration with Other AI Techniques:</strong> Neurosymbolic AI is a rapidly developing field that holds great promise for the integration of symbolic and connectionist AI techniques. Future research in this area is expected to focus on developing more efficient and effective techniques for integrating these two approaches, including the use of hybrid architectures and the development of new algorithms for neuro symbolic learning.</p><p><strong>Ethical Considerations:</strong> As with any AI system, there are important ethical considerations to take into account when developing and deploying neurosymbolic AI applications. These include issues related to privacy, bias, and fairness. It will be important for researchers and developers to work closely with ethicists and stakeholders to ensure that these systems are developed and deployed responsibly and ethically. Additionally, there may be concerns related to the potential misuse of these systems, such as the development of autonomous weapons or other forms of AI-enabled violence.</p><p>Overall, the future of neurosymbolic AI is <strong>exciting and full of potential.</strong> With the ability to combine the strengths of symbolic and connectionist AI, these systems have the potential to revolutionize a wide range of fields, from healthcare and finance to robotics and natural language processing. However, as with any new technology, there are also <strong>important challenges and ethical considerations</strong> that must be carefully considered and addressed. By working together to address these challenges, we can harness the power of neurosymbolic AI to create a better and more just world for all.</p><h3>Conclusion</h3><p>Neurosymbolic AI is an emerging field that integrates symbolic and connectionist AI techniques to enhance the strengths of each approach. It uses knowledge representation, rule-based reasoning, and neural networks to build more powerful models that can handle uncertainty, ambiguity, and other real-world challenges. One of the key advantages of neurosymbolic AI is its ability to generalize better than traditional symbolic approaches, making it useful in applications like natural language processing, robotics, healthcare, and finance. However, there are also challenges to overcome, such as scalability and data requirements. The field is still in its early stages, and there is ongoing research into how to integrate neurosymbolic AI with other AI techniques and how to address ethical considerations.</p><p>Overall, neurosymbolic AI <strong>shows great potential for solving complex problems and advancing AI as a whole</strong>, and it will be exciting to see how the field develops in the coming years.</p><h3>References</h3><ul><li><a href="https://www.forbes.com/sites/forbestechcouncil/2019/03/26/artificial-intelligence-beyond-deep-neural-networks/?sh=312513bc2c96">Council Post: Artificial Intelligence Beyond Deep Neural Networks</a></li><li><a href="https://bdtechtalks.com/2019/11/18/what-is-symbolic-artificial-intelligence/">What is symbolic artificial intelligence? - TechTalks</a></li><li><a href="https://en.wikipedia.org/wiki/Neuro-symbolic_AI">Neuro-symbolic AI - Wikipedia</a></li><li><a href="https://bdtechtalks.com/2018/12/03/jeremy-howard-ai-deep-learning-myths/">Is deep learning overhyped? - TechTalks</a></li><li><a href="https://psychology.berkeley.edu/students/graduate-program/cognitive-neuroscience">Cognitive Neuroscience | UC Psych</a></li></ul><p>Research paper: <a href="https://arxiv.org/abs/2012.05876">https://arxiv.org/abs/2012.05876</a></p><p>An example implementation of neurosymbolic AI: <a href="https://arxiv.org/abs/1904.12584">https://arxiv.org/abs/1904.12584</a></p><p><a href="https://arxiv.org/abs/1606.04422">Logic Tensor Networks: Deep Learning and Logical Reasoning from Data and Knowledge</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8e776132c42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Hybrid Neural Network for Movie Recommendations using TensorFlow Recommenders]]></title>
            <link>https://prabhatm27.medium.com/creating-a-hybrid-neural-network-for-movie-recommendations-using-tensorflow-recommenders-fdad13aa4979?source=rss-f0451664d8fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdad13aa4979</guid>
            <category><![CDATA[movies]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Prabhat M]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 12:59:29 GMT</pubDate>
            <atom:updated>2025-10-13T16:01:18.685Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you tired of scrolling through endless lists of movies on streaming platforms, only to find nothing that piques your interest? Get ready to say goodbye to the frustration of endless browsing. Keep reading to find out how to build your hybrid neural network for movie recommendations using TensorFlow Recommenders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L29RrCaZdRo-iGVP.jpg" /></figure><p>In this article, we will be discussing how <strong>deep learning techniques</strong> can be used to build personalized recommendations. The purpose of this article is to provide a comprehensive guide on how to design and implement a deep learning-based movie recommendation system using the TensorFlow Recommenders library. We will be using a hybrid neural network model that combines <strong>deep learning</strong> with<strong> traditional collaborative filtering techniques</strong>, and the popular <a href="https://grouplens.org/datasets/movielens/">MovieLens dataset</a> to train and evaluate our model.</p><p><strong>Deep learning:</strong> Using artificial neural networks to analyze large amounts of movie data and make personalized movie recommendations based on a user’s past preferences and behaviors.</p><p><strong>Traditional Collaborative Filtering: </strong>A recommendation system that uses past interactions between users and items to make recommendations. It assumes that similar users will like similar items and generates recommendations based on the past behavior of similar users.</p><h4>Explanation of the deep learning techniques used</h4><p>We will be using deep learning techniques to build a movie recommendation system. Specifically, we will be implementing a <strong>hybrid neural network model.</strong></p><p><strong>Hybrid neural network model</strong>: Combines the power of<strong> deep learning</strong> with the efficiency of <strong>traditional collaborative filtering</strong> techniques. The model takes into account both explicit ratings given by users and implicit signals such as genres and uses a <strong>combination of neural networks and matrix factorization</strong> to make personalized movie recommendations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*_OgA1EN7gdtSi8GF.png" /><figcaption>An example of a hybrid neural network</figcaption></figure><p>The model takes into account both <strong>explicit signal</strong> ratings given by users and <strong>implicit signals</strong> such as genres. By leveraging these signals, the model adapts to the preferences and tastes of users and <strong>makes personalized recommendations</strong>.</p><p>A <strong>hybrid neural network</strong> is like having the best of both worlds! Picture a <strong>superhero who can fly and has super strength</strong>. That’s a hybrid neural network in a nutshell. It takes the accuracy of <strong>deep learning (flying) </strong>and combines it with the efficiency of <strong>traditional collaborative filtering techniques (super strength)</strong>. With this super combination, the hybrid neural network can make incredibly accurate movie recommendations based on both what you explicitly tell it (your favorite genres) and what it can infer from your past behavior (the ratings you’ve given). So next time you’re scrolling through Netflix, think of the hybrid neural network as your trusty sidekick, always there to suggest the perfect movie for you.</p><p>The movie recommendation model uses a technique called <strong>embeddings</strong> to understand the patterns and relationships in the data. Embeddings are like shortcuts that summarize big and complex information into smaller, simpler parts.</p><p>To make movie recommendations, the model uses a type of neural network that has <strong>multiple layers</strong>. The network is trained to predict how much a user would like a movie based on the embeddings of the users and movies.</p><p>To do this, the model breaks down the information about users and movies into two smaller parts, called user and movie matrices. These matrices are much easier for the model to understand and work with, which allows it to make better predictions. This technique of breaking down information is called <strong>matrix factorization</strong>.</p><p>With the help of a hybrid neural network, you can now say goodbye to scrolling through never-ending movie lists on streaming platforms. No more frustration and disappointment of finding nothing that interests you. Instead, get ready to bring the drama, the laughter, and the excitement straight to your screen! A hybrid neural network is like your very own movie personal assistant, handpicking the perfect flicks just for you, based on your preferences. So sit back, it’s time to bring the drama (and comedy) to your screen!</p><h3>Steps:</h3><ol><li><strong>Data Collection and Preprocessing</strong></li><li><strong>Building the hybrid neural network</strong></li><li><strong>Training and evaluating the neural network</strong></li><li><strong>Making personalized recommendations</strong></li></ol><h3>Step 1: Data Collection and Preprocessing</h3><h4>Description of the MovieLens dataset</h4><p>The MovieLens dataset is a widely used dataset for building recommendation systems. It contains over <strong>20 million ratings</strong> and <strong>600,000 tag</strong> applications applied to <strong>42,000 movies</strong> by <strong>280,000 users</strong>. The data was collected by the GroupLens Research group at the University of Minnesota. In this project, we will be using the latest version of the dataset, which includes both explicit ratings given by users and implicit signals such as movie genres, etc. The dataset was obtained from the GroupLens website and was <strong>preprocessed to fit the format</strong> required by TensorFlow Recommenders for training and evaluation.</p><h4>Explanation of the data preprocessing steps, such as cleaning and transforming the data</h4><p>The data preprocessing step involves cleaning and transforming the raw data to make it suitable for training the model. The MovieLens dataset, which is used in this project, requires several preprocessing steps to make it ready for training.</p><h3>Code:</h3><ol><li><strong>Importing the necessary libraries: </strong>The code imports several libraries to support the implementation of the movie recommendation system. These libraries include pandas, numpy, seaborn, matplotlib, TensorFlow, tensorflow_recommenders, and sklearn</li></ol><pre>import string # for string manipulation operations<br>import re # for regular expression operations n. <br><br>import pandas as pd #for data manipulation and analysis<br>import numpy as np #for numerical computing<br>import seaborn as sns #for data visualization<br>import matplotlib.pyplot as plt #for data visualization<br>import tensorflow as tf #for building and training deep learning models<br>import tensorflow_recommenders as tfrs #as a high-level API for building recommendation models on top of TensorFlow<br>from collections import Counter #for counting occurrences of elements in a list or other iterable<br>from typing import Dict, Text #for declaring data types in a function or module<br>from ast import literal_eval #for evaluating strings as code<br>from datetime import datetime #for working with dates and times<br>from wordcloud import WordCloud #for generating word clouds from text<br>from sklearn.preprocessing import MinMaxScaler #for feature scaling<br>from sklearn.feature_extraction.text import TfidfVectorizer #for converting text into numerical features<br>from sklearn.metrics.pairwise import cosine_similarity #for measuring similarity between two non-zero vectors of an inner product space.<br>import random #To generate random numbers to select random movies for user to rate<br><br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><p><strong>2. Importing the data: </strong>The code is loading three datasets, ”credits”, “keywords”, and “movies_metadata”, into memory.</p><pre>#Import the required datasets<br>credits = pd.read_csv(&#39;../input/the-movies-dataset/credits.csv&#39;)<br>keywords = pd.read_csv(&#39;../input/the-movies-dataset/keywords.csv&#39;)<br>movies = pd.read_csv(&#39;../input/the-movies-dataset/movies_metadata.csv&#39;).\<br>                     drop([&#39;belongs_to_collection&#39;, &#39;homepage&#39;, &#39;imdb_id&#39;, &#39;poster_path&#39;, &#39;status&#39;, &#39;title&#39;, &#39;video&#39;], axis=1).\<br>                     drop([19730, 29503, 35587]) # Incorrect data type<br><br>movies[&#39;id&#39;] = movies[&#39;id&#39;].astype(&#39;int64&#39;)<br>#Merge all the datasets together<br>df = movies.merge(keywords, on=&#39;id&#39;).merge(credits, on=&#39;id&#39;)<br>df.head()</pre><ul><li><strong>credits.csv</strong>: contains information about the cast and crew involved in the production of movies</li><li><strong>keywords.csv</strong>: contains a list of keywords or phrases associated with the movies in the dataset</li><li><strong>movies_metadata.csv</strong>: contains information about various movies, including title, release date, budget, revenue, genres, production companies, and more</li></ul><p>The movies_metadata dataset is cleaned and transformed by <strong>dropping certain columns with no useful information</strong> and removing rows with incorrect data types.</p><p>The data is then merged into a <strong>single data frame, df</strong>, using the merge() method, which combines two data frames based on a common column, in this case, “id”. Finally, the code replaces missing values with empty strings and zeros, then drops any remaining missing values from the dataset.</p><p><strong>3. Preprocessing the data: </strong>After merging, the code performs several cleaning and processing steps, such as <strong>converting data types, filling in missing values, and transforming data</strong>. This includes converting the ‘id’ column to int64, filling in missing values in columns such as original_language, runtime, and tagline, and dropping any remaining missing values. The code then applies the get_text function to several columns, such as genres, production_companies, production_countries, and cast, to extract relevant information from the columns. Finally, it creates new columns to store information from the cast column, such as characters and actors, drops the original cast column, removes duplicate entries, and resets the index.</p><pre>#Fill in the missing values<br>df[&#39;original_language&#39;] = df[&#39;original_language&#39;].fillna(&#39;&#39;)<br>df[&#39;runtime&#39;] = df[&#39;runtime&#39;].fillna(0)<br>df[&#39;tagline&#39;] = df[&#39;tagline&#39;].fillna(&#39;&#39;)<br><br>df.dropna(inplace=True)</pre><pre>#A function to extract the useful information from the columns<br>def get_text(text, obj=&#39;name&#39;):<br>    text = literal_eval(text)<br>    <br>    if len(text) == 1:<br>        for i in text:<br>            return i[obj]<br>    else:<br>        s = []<br>        for i in text:<br>            s.append(i[obj])<br>        return &#39;, &#39;.join(s)<br><br>#Applying the functions to the columns    <br>df[&#39;genres&#39;] = df[&#39;genres&#39;].apply(get_text)<br>df[&#39;production_companies&#39;] = df[&#39;production_companies&#39;].apply(get_text)<br>df[&#39;production_countries&#39;] = df[&#39;production_countries&#39;].apply(get_text)<br>df[&#39;crew&#39;] = df[&#39;crew&#39;].apply(get_text)<br>df[&#39;spoken_languages&#39;] = df[&#39;spoken_languages&#39;].apply(get_text)<br>df[&#39;keywords&#39;] = df[&#39;keywords&#39;].apply(get_text)<br><br>#Create new columns<br>df[&#39;characters&#39;] = df[&#39;cast&#39;].apply(get_text, obj=&#39;character&#39;)<br>df[&#39;actors&#39;] = df[&#39;cast&#39;].apply(get_text)<br><br>df.drop(&#39;cast&#39;, axis=1, inplace=True)<br>df = df[~df[&#39;original_title&#39;].duplicated()]<br>df = df.reset_index(drop=True)</pre><pre>#Changing the datatype of certain columns<br>df[&#39;release_date&#39;] = pd.to_datetime(df[&#39;release_date&#39;])<br>df[&#39;budget&#39;] = df[&#39;budget&#39;].astype(&#39;float64&#39;)<br>df[&#39;popularity&#39;] = df[&#39;popularity&#39;].astype(&#39;float64&#39;)</pre><pre>#Here, I am choosing movies released after 2009 and which were originally shot in English<br>df = df[df[&#39;release_date&#39;].dt.year&gt;2009]<br>df = df[df[&#39;original_language&#39;]==&#39;en&#39;]<br>df = df.reset_index()</pre><p><strong>4. Importing the datasets of the user ratings: </strong>The code is used to clean and process a movie ratings dataset. It starts by importing the “ratings” dataset using pd.read_csv(). Then, the data type of the &quot;date&quot; column is changed using the apply() method and datetime.fromtimestamp(). The original &quot;timestamp&quot; column is then dropped using drop(). The code then merges additional columns from another dataset, dfwhich includes information about the movie titles, genres, and overviews. Finally, the resulting data frame is filtered to only include non-null values for the &quot;id&quot; column, and the index is reset. The final data frame is displayed using head().</p><pre>#Importing the dataset of the ratings<br>ratings_df = pd.read_csv(&#39;../input/the-movies-dataset/ratings.csv&#39;)</pre><pre>#Changing the datatype of the &#39;date&#39; column<br>ratings_df[&#39;date&#39;] = ratings_df[&#39;timestamp&#39;].apply(lambda x: datetime.fromtimestamp(x))<br>ratings_df.drop(&#39;timestamp&#39;, axis=1, inplace=True)<br><br>#Adding the columns from the merged dataset<br>ratings_df = ratings_df.merge(df[[&#39;id&#39;, &#39;original_title&#39;, &#39;genres&#39;, &#39;overview&#39;]], left_on=&#39;movieId&#39;,right_on=&#39;id&#39;, how=&#39;left&#39;)<br>ratings_df = ratings_df[~ratings_df[&#39;id&#39;].isna()]<br>ratings_df.drop(&#39;id&#39;, axis=1, inplace=True)<br>ratings_df.reset_index(drop=True, inplace=True)<br>ratings_df.head()</pre><p><strong>5. Filtering the data for the required columns for prediction: </strong>This code is extracting information from two data frames — ‘df’ and ‘ratings_df’. The first data frame ‘df’ contains ‘id’ and ‘original_title’ columns, which are selected and renamed to ‘movie’. The second data frame ‘ratings_df’ contains ‘userId’, ‘original_title’, and ‘rating’ columns, which are also selected to form a new data frame ‘ratings_df’. Both these data frames, ‘movies_df’ and ‘ratings_df’, are then displayed using the ‘.head()’ function.</p><pre>#Selecting the id and title column of the merged dataframe<br>movies_df = df[[&#39;id&#39;, &#39;original_title&#39;]]<br>movies_df.rename(columns={&#39;id&#39;:&#39;movieId&#39;}, inplace=True)<br>movies_df.head()</pre><pre>#Selecting the UserId, title, and rating from the ratings dataframe<br>ratings_df = ratings_df[[&#39;userId&#39;, &#39;original_title&#39;, &#39;rating&#39;]]<br>ratings_df.head()</pre><p><strong>6. Resetting the index: </strong>The code is resetting the index of two data frames, movies_df and df. The index movies_df is reset using the reset_index method, which replaces the current index with a default sequential index starting from 0. After resetting the index, the head of the list movies_df is displayed. Similarly, the index of the df data frame is reset using the reset_index method, and its head is also displayed. Finally, the &#39;level_0&#39; column, which was added during the resetting of the index, is deleted from the df data frame using the del statement.</p><pre>#Resetting the index of the movies dataframe<br>movies_df = movies_df.reset_index()<br>movies_df.head()</pre><pre>#Resetting the index of the merged dataframe<br>df = df.reset_index()<br>df.head()<br>del df[&#39;level_0&#39;]</pre><p>7. <strong>Creating a new data frame sorted by popularity: </strong>The code sorts the data frame df by the column &#39;popularity&#39; in descending order. The data frame is then reset to its index and displays the first five rows using head() the method. This is to let the user rate the most popular ones according to the popularity score.</p><pre>#Sorting by popularity to let the user rate the most popular ones<br>pdf = df.sort_values(&#39;popularity&#39;, ascending=False)<br>pdf = pdf.reset_index()<br>pdf.head()</pre><p><strong>8. Asking the user to rate some of the most popular movies: </strong>This code generates a random list of 10 movie names from a sorted data frame called “pdf”. The code then prompts the user to enter their name, and for each of the 10 randomly chosen movie names, it displays the movie name, its overview, and cast, and then asks the user to rate the movie on a scale of 5. If the user doesn’t know the movie, they can enter “d,k” and the loop will continue to the next movie. The user’s ratings are then stored in a data frame called “ratings_df” as a new row with the user’s ID, movie name, and rating.</p><pre>#Random number generation for the user to rate movies out of 5<br>user_id = 270897<br>m = 3<br>randomList = []<br>for i in range(10):<br>    r=random.randint(1,10)<br>    if r not in randomList:<br>        randomList.append(r)<br>        <br>print(&quot;Welcome&quot;)<br>name = input(&quot;Enter your name:&quot;)<br>for i in randomList:<br>    movie = pdf[&#39;original_title&#39;][i]<br>    print(i)<br>    <br>    movie_row = pdf[pdf[&#39;original_title&#39;] == movie]<br>    print()<br>    print(movie)<br>    print(&quot;Overview: &quot;, pdf[pdf[&#39;original_title&#39;] == movie][&#39;overview&#39;][i])<br>    print(&quot;Cast: &quot;, pdf[pdf[&#39;original_title&#39;] == movie][&#39;actors&#39;][i])<br>    user_r = input(&#39;Enter your rating out of 5 (Enter dk if you dont know the movie)&#39;)<br>    if(user_r==&#39;dk&#39;):<br>        continue;<br>    else:<br>        user_r = int(user_r)<br>        new_row = {&#39;userId&#39;:270897, &#39;original_title&#39;:movie, &#39;rating&#39;:user_r}<br>        ratings_df = ratings_df.append(new_row, ignore_index=True)</pre><p>Here is an example of a part of the output of the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhJoyFAS3cNYN4LIrhNF-g.png" /></figure><h3>Step 2: Building the Hybrid Neural Network:</h3><h4>Introducing embeddings</h4><p>The recommendation system is built using dense embeddings of low-dimensional representations of high-dimensional data used in machine learning. They encode discrete variables like movie titles and user IDs into a continuous numerical space, capturing patterns and relationships in the data. In recommendation systems, embeddings are used to represent movies and users in a way that captures their similarities. They are then used as inputs to a model that predicts user ratings or preferences based on movie and user embeddings. Using embeddings allows for more accurate and personalized recommendations.</p><h4>The architecture of the recommendation model</h4><p>The recommendation model architecture is a deep neural network with multiple layers, designed to learn complex patterns in data. It uses matrix factorization to decompose the rating matrix into two lower-dimensional matrices representing users and movies, learning preferences, and making personalized recommendations. This technique also incorporates both explicit and implicit information, reducing data dimensionality for more efficient training and deployment.</p><h4>Discussion of the deep learning techniques used in the model, such as neural networks and collaborative filtering</h4><p><strong>Deep learning</strong> allows the model to learn complex, non-linear relationships between users and items. In the movie recommendation system we are discussing, a <strong>hybrid neural network</strong> model is used that combines both deep learning and traditional collaborative filtering techniques.</p><p><strong>Neural networks</strong> are used in the recommendation model to learn the underlying patterns and relationships in the data. The architecture of the model consists of multiple layers of interconnected neurons, each layer representing a different level of abstraction in the data. The model is trained to predict user ratings for movies based on their dense embeddings of low-dimensional representations of high-dimensional data.</p><p><strong>Collaborative filtering</strong> is a traditional technique used in recommendation systems, which makes recommendations based on the past behavior of users. In the movie recommendation system, collaborative filtering is used in conjunction with deep learning to make personalized recommendations. The model takes into account both explicit ratings given by users and implicit signals, such as movie views and clicks, and uses these signals to learn the preferences and tastes of users. By leveraging the strengths of both deep learning and collaborative filtering, the hybrid model can make more accurate and personalized recommendations.</p><h3>Code</h3><ol><li><strong>Creating the required data from the data frames for the model: T</strong>wo datasets, “ratings” and “movies”, are created from the ratings_df and movies_df data frames, respectively. The “ratings” dataset is transformed to contain only three columns: “original_title”, “userId”, and “rating”. The “movies” dataset is transformed to contain only the “original_title” column. These datasets are used as input to the recommendation model.</li></ol><pre>#Changing the datatype to string<br>ratings_df[&#39;userId&#39;] = ratings_df[&#39;userId&#39;].astype(str)<br><br>#Creating data for the model<br>ratings = tf.data.Dataset.from_tensor_slices(dict(ratings_df[[&#39;userId&#39;, &#39;original_title&#39;, &#39;rating&#39;]]))<br>movies = tf.data.Dataset.from_tensor_slices(dict(movies_df[[&#39;original_title&#39;]]))<br><br>ratings = ratings.map(lambda x: {<br>    &quot;original_title&quot;: x[&quot;original_title&quot;],<br>    &quot;userId&quot;: x[&quot;userId&quot;],<br>    &quot;rating&quot;: float(x[&quot;rating&quot;])<br>})<br><br>movies = movies.map(lambda x: x[&quot;original_title&quot;])</pre><p><strong>2. Defining the class to create the model: </strong>Defines a TensorFlow class called MovieModel, which implements a deep learning model for movie recommendation. The model is constructed with <strong>two user and movie models</strong>, which are used <strong>to produce user and movie embeddings</strong>. These embeddings are then passed through a <strong>multi-layer neural network to predict ratings</strong>. The model also defines two tasks, rating and retrieval, which correspond to the two losses that the model optimizes. The rating task is to predict the rating scores, while the retrieval task is to retrieve similar movies based on user embeddings and movie embeddings. The final loss is a weighted sum of the two task losses. The user and movie models, as well as the loss weights, are passed as parameters to the constructor of the MovieModel class.</p><pre>#Creating the TensorFlow Model<br>class MovieModel(tfrs.models.Model):<br><br>  def __init__(self, rating_weight: float, retrieval_weight: float) -&gt; None:<br>    # We take the loss weights in the constructor: this allows us to instantiate<br>    # several model objects with different loss weights.<br><br>    super().__init__()<br><br>    embedding_dimension = 64<br><br>    # User and movie models.<br>    self.movie_model: tf.keras.layers.Layer = tf.keras.Sequential([<br>      tf.keras.layers.StringLookup(<br>        vocabulary=unique_movie_titles, mask_token=None),<br>      tf.keras.layers.Embedding(len(unique_movie_titles) + 1, embedding_dimension)<br>    ])<br>    self.user_model: tf.keras.layers.Layer = tf.keras.Sequential([<br>      tf.keras.layers.StringLookup(<br>        vocabulary=unique_user_ids, mask_token=None),<br>      tf.keras.layers.Embedding(len(unique_user_ids) + 1, embedding_dimension)<br>    ])<br><br>    # A small model to take in user and movie embeddings and predict ratings.<br>    # We can make this as complicated as we want as long as we output a scalar<br>    # as our prediction.<br>    self.rating_model = tf.keras.Sequential([<br>        tf.keras.layers.Dense(256, activation=&quot;relu&quot;),<br>        tf.keras.layers.Dense(128, activation=&quot;relu&quot;),<br>        tf.keras.layers.Dense(1),<br>    ])<br><br>    # The tasks.<br>    self.rating_task: tf.keras.layers.Layer = tfrs.tasks.Ranking(<br>        loss=tf.keras.losses.MeanSquaredError(),<br>        metrics=[tf.keras.metrics.RootMeanSquaredError()],<br>    )<br>    self.retrieval_task: tf.keras.layers.Layer = tfrs.tasks.Retrieval(<br>        metrics=tfrs.metrics.FactorizedTopK(<br>            candidates=movies.batch(128).map(self.movie_model)<br>        )<br>    )<br><br>    # The loss weights.<br>    self.rating_weight = rating_weight<br>    self.retrieval_weight = retrieval_weight<br><br>  def call(self, features: Dict[Text, tf.Tensor]) -&gt; tf.Tensor:<br>    # We pick out the user features and pass them into the user model.<br>    user_embeddings = self.user_model(features[&quot;userId&quot;])<br>    # And pick out the movie features and pass them into the movie model.<br>    movie_embeddings = self.movie_model(features[&quot;original_title&quot;])<br>    <br>    return (<br>        user_embeddings,<br>        movie_embeddings,<br>        # We apply the multi-layered rating model to a concatentation of<br>        # user and movie embeddings.<br>        self.rating_model(<br>            tf.concat([user_embeddings, movie_embeddings], axis=1)<br>        ),<br>    )<br><br>  def compute_loss(self, features: Dict[Text, tf.Tensor], training=False) -&gt; tf.Tensor:<br><br>    ratings = features.pop(&quot;rating&quot;)<br><br>    user_embeddings, movie_embeddings, rating_predictions = self(features)<br><br>    # We compute the loss for each task.<br>    rating_loss = self.rating_task(labels=ratings,predictions=rating_predictions)<br>    retrieval_loss = self.retrieval_task(user_embeddings, movie_embeddings)<br><br>    # And combine them using the loss weights.<br>    return (self.rating_weight * rating_loss + self.retrieval_weight * retrieval_loss)</pre><p><strong>3. Creating a model based on the class definition:</strong> The model is compiled using the Adagrad optimizer, which is an optimization algorithm used in deep learning to update the model weights during training. The optimizer is configured with a learning rate of 0.1. The training data (train) is shuffled, grouped into batches of 1,000 instances each, and cached. The same is done for the test data (test). The model is trained by calling the fit method on the cached training data, with the number of training epochs set to 3. An epoch is a complete iteration over the entire training dataset. During each epoch, the model updates its parameters to minimize the loss function, which measures the difference between the model’s predictions and the actual training labels.</p><pre>#Creating a model based on the above Class defintion<br>model = MovieModel(rating_weight=1.0, retrieval_weight=1.0)<br>model.compile(optimizer=tf.keras.optimizers.Adagrad(0.1))<br><br>cached_train = train.shuffle(100_000).batch(1_000).cache()<br>cached_test = test.batch(1_000).cache()<br><br>model.fit(cached_train, epochs=3)</pre><h3>Step 3: Training and Evaluating the Model:</h3><h4>Description of the training process and the evaluation metrics used</h4><p>A new instance of the “MovieModel” class is created, with the rating_weight and retrieval_weight parameters set to 1.0. This instance of the class will serve as the model for the training.</p><h3>Code</h3><ol><li><strong>Evaluate the model:</strong> This code evaluates the performance of a model for movie recommendation by calculating two evaluation metrics. The first metric is “Retrieval top-100 accuracy”, which measures the accuracy of the top 100 predictions for movie ratings. The second metric is “Ranking RMSE,” which measures the root mean squared error of the predicted movie ratings. The results of the evaluation are then printed in a format showing the accuracy and the RMSE values to three decimal places.</li></ol><pre>#Evaluating the model<br>metrics = model.evaluate(cached_test, return_dict=True)<br><br>print(f&quot;\nRetrieval top-100 accuracy: {metrics[&#39;factorized_top_k/top_100_categorical_accuracy&#39;]:.3f}&quot;)<br>print(f&quot;Ranking RMSE: {metrics[&#39;root_mean_squared_error&#39;]:.3f}&quot;)</pre><h3>Step 4: Making Personalized Recommendations:</h3><h4>Explanation of how the trained model can be used to make personalized movie recommendations</h4><p>The trained model can be used to make personalized movie recommendations by <strong>querying the trained embeddings</strong>. Embeddings are dense, low-dimensional representations of high-dimensional data that capture the underlying patterns and relationships in the data. In the case of movie recommendations, the embeddings represent the movies and the users. The trained model can be used to predict user ratings for movies based on their embeddings. This is done using a technique called matrix factorization. By querying the trained embeddings, the model can identify the movies that are most similar to the ones the user has liked in the past, and recommend them to the user. Additionally, the model can also take into account other implicit signals, such as movie views and clicks, to make more personalized recommendations.</p><ol><li><strong>Functions for recommending movies to the users:</strong> This code defines two functions in Python: predict_movie and predict_rating.</li></ol><p>The predict_movie function takes in a user ID and a value for the number of recommendations (top_n) to display, and uses the trained movie recommendation model to generate movie recommendations for the user. It creates an index from the movie dataset and uses it to retrieve the top top_n recommendations for the user. The recommended movies are then printed on the console.</p><p>TheThe predict_rating function takes in a user ID and a movie title, and uses the trained movie recommendation model to predict the rating the user will give for the movie. It passes the user ID and movie title as inputs to the model, and the predicted rating is returned and printed to the console.</p><pre>#A function to recommend movies to the user<br>def predict_movie(user, top_n=3):<br>    # Create a model that takes in raw query features, and<br>    index = tfrs.layers.factorized_top_k.BruteForce(model.user_model)<br>    # recommends movies out of the entire movies dataset.<br>    index.index_from_dataset(<br>      tf.data.Dataset.zip((movies.batch(100), movies.batch(100).map(model.movie_model)))<br>    )<br><br>    # Get recommendations.<br>    _, titles = index(tf.constant([str(user)]))<br>    <br>    print(&#39;Top {} recommendations for user {}:\n&#39;.format(top_n, name))<br>    for i, title in enumerate(titles[0, :top_n].numpy()):<br>        print(&#39;{}. {}&#39;.format(i+1, title.decode(&quot;utf-8&quot;)))<br><br>#Predict the rating a user will give for a movie        <br>def predict_rating(user, movie):<br>    trained_movie_embeddings, trained_user_embeddings, predicted_rating = model({<br>          &quot;userId&quot;: np.array([str(user)]),<br>          &quot;original_title&quot;: np.array([movie])<br>      })<br>    print(&quot;Predicted rating for {}: {}&quot;.foxrmat(movie, predicted_rating.numpy()[0][0]))</pre><pre>#Predicting the movies for the users<br>predict_movie(270897, 5</pre><p><strong>Example of the output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*fNRTXbCV55QdVL9UU2wdQw.png" /></figure><p><strong>2. Displaying the data of the recommendations:</strong> The code is a recommendation system that recommends the top 5 movies to a user. The system starts by creating an index using the tfrs.layers.factorized_top_k.BruteForce method and passing the model.user_model as an argument. The index is then built from the entire movie dataset using the index_from_dataset method. The index The function is then used to recommend movies to the user. The details of the recommendations are stored in a new data frame pred_dfby merging the details of the recommended movies from the original data frame df on the &#39;original_title&#39; column. The details of the recommendations are then displayed, including the movie title, overview, genres, and cast.</p><pre>#Get meta data for recommendations<br>index = tfrs.layers.factorized_top_k.BruteForce(model.user_model)<br># recommends movies out of the entire movies dataset.<br>index.index_from_dataset(<br>  tf.data.Dataset.zip((movies.batch(100), movies.batch(100).map(model.movie_model)))<br>)<br><br>#Store the details of the recommendations in a new datafram<br>_, titles = index(tf.constant([&#39;270897&#39;]))<br>pred_movies = pd.DataFrame({&#39;original_title&#39;: [i.decode(&#39;utf-8&#39;) for i in titles[0,:5].numpy()]})<br><br>pred_df = pred_movies.merge(df[[&#39;original_title&#39;, &#39;genres&#39;, &#39;overview&#39;, &#39;actors&#39;]], on=&#39;original_title&#39;, how=&#39;left&#39;)<br>pred_df = pred_df[~pred_df[&#39;original_title&#39;].duplicated()]<br>pred_df.reset_index(drop=True, inplace=True)<br>pred_df.index = np.arange(1, len(pred_df)+1)</pre><pre>#Displaying the details of the recommendations<br>for i in range(1,6):<br>    print(&quot;Details about your recommendations:&quot;)<br>    print(&quot;Number: &quot;, i)<br>    print(&quot;Movie: &quot;, pred_df[&#39;original_title&#39;][i])<br>    print(&quot;Overview: &quot;, pred_df[&#39;overview&#39;][i])<br>    print(&quot;Genres: &quot;, pred_df[&#39;genres&#39;][i])<br>    print(&quot;Cast: &quot;, pred_df[&#39;actors&#39;][i])<br>    print()</pre><p><strong>Example of the output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Zgb6ez7QsZD4A2X0zWMhA.png" /></figure><h3>Conclusion</h3><p>Well, well, if it isn’t the movie recommendation system, giving me 5 movie predictions to watch. To be honest, I have to say I might be a bit biased when it comes to these recommendations. I did spend a ton of time working on it, so I have to give it some love. I’d say out of those 5, I’d be willing to watch 4 of them. Not gonna lie, I have high standards when it comes to movies, and I won’t settle for anything less than an amazing experience. But hey, you never know, the fifth one might surprise me and be the hidden gem in the bunch. Here’s to hoping for a movie marathon filled with laughter, tears, and all the feels!</p><h4>Summary of the steps</h4><p>The article focuses on building a movie recommendation system using deep learning techniques. The <strong>TensorFlow Recommenders (TFRS)</strong> library is used to build and train the recommendation model, and the <strong>MovieLens</strong> dataset is used to evaluate the model’s performance. The recommendation model is a hybrid neural network<strong> </strong>that <strong>combines deep learning and traditional collaborative filtering techniques</strong>. This allows the model to take into account both explicit ratings given by users as well as implicit signals such as movie views and clicks.</p><p>The deep learning techniques used in the model include the use of <strong>embeddings</strong>, which are dense, low-dimensional representations of high-dimensional data. These embeddings are used to capture the underlying relationships between different entities, such as users and movies. Additionally, <strong>neural networks</strong> model the complex relationships between users and movies. <strong>Matrix factorization</strong> is also used to decompose the rating matrix into two lower-dimensional matrices, which helps to capture the underlying patterns in the data.</p><p>Before training the model, the data must undergo preprocessing steps to ensure it is in a suitable format. These preprocessing steps involve cleaning and transforming the data, such as removing any misz§sing values or transforming categorical data into numerical data.</p><p>The results of the model show that it can provide personalized movie recommendations based on user data. These recommendations can be presented to the user in various ways, such as a ranked list of recommended movies or a personalized movie playlist.</p><h4>Discussion of the potential future developments and improvements to the model</h4><p>One potential future development is to incorporate reinforcement learning techniques into the model. This can help the model to learn from user interactions with the recommendations and make continuous improvements over time. Additionally, there is potential to integrate the model into existing movie streaming platforms or websites to provide real-time recommendations to users. These developments and improvements can help take the movie recommendation system to the next level and provide even more value to users.</p><p><strong>In conclusion</strong>, the article highlights the importance of <strong>combining deep learning and traditional collaborative filtering techniques</strong> in recommendation systems and provides a comprehensive overview of the process of building such a system. There is always room for improvement in any machine learning model, and <strong>future developments</strong> could include incorporating <strong>additional data sources</strong>, such as social media data or demographic data, to improve the model’s <strong>accuracy and personalization</strong>. Furthermore, the use of newer deep learning techniques, such as <strong>self-attention mechanisms</strong>, could also be explored to further improve the model’s performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94267f2aafaeb79e0c35a53c53198c94/href">https://medium.com/media/94267f2aafaeb79e0c35a53c53198c94/href</a></iframe><p>Credit (The original code): <a href="https://www.kaggle.com/code/mfaaris/hybrid-and-tensorflow-recommender-system">https://www.kaggle.com/code/mfaaris/hybrid-and-tensorflow-recommender-system</a> [I used this code to build the model, and I added the part about the user rating movies on top of this code]</p><p>TensorFlow Recommenders” library documentation: <a href="https://www.tensorflow.org/recommenders">https://www.tensorflow.org/recommenders</a></p><p>Original dataset: <a href="https://grouplens.org/datasets/movielens/">https://grouplens.org/datasets/movielens/</a></p><p>Dataset on Kaggle: <a href="https://www.kaggle.com/datasets/rounakbanik/the-movies-dataset">https://www.kaggle.com/datasets/rounakbanik/the-movies-dataset</a></p><p>“Deep Learning” by Ian Goodfellow, Yoshua Bengio, and Aaron Courville: <a href="http://imlab.postech.ac.kr/dkim/class/csed514_2019s/DeepLearningBook.pdf">http://imlab.postech.ac.kr/dkim/class/csed514_2019s/DeepLearningBook.pdf</a> (Combining collaborative filtering with neural networks)</p><p>GitHub code link: <a href="https://github.com/Thesavagecoder7784/DeepLearningforMovieRecommendation/blob/main/Deep%20Learning%20Movie%20Recommendation%20System.ipynb">https://github.com/Thesavagecoder7784/DeepLearningforMovieRecommendation/blob/main/Deep%20Learning%20Movie%20Recommendation%20System.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdad13aa4979" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>