<?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 Raghav Sharma on Medium]]></title>
        <description><![CDATA[Stories by Raghav Sharma on Medium]]></description>
        <link>https://medium.com/@sharmaraghav644?source=rss-fe39f9032e4d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1szcrifwrQ9t4iej-UnUgA.jpeg</url>
            <title>Stories by Raghav Sharma on Medium</title>
            <link>https://medium.com/@sharmaraghav644?source=rss-fe39f9032e4d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:13:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sharmaraghav644/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[Can Transformer Models Replace Rule-Based Systems in Real-Time Log Monitoring?]]></title>
            <link>https://medium.com/@sharmaraghav644/can-transformer-models-replace-rule-based-systems-in-real-time-log-monitoring-5416911cd47b?source=rss-fe39f9032e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5416911cd47b</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[siem]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Raghav Sharma]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 04:23:35 GMT</pubDate>
            <atom:updated>2026-01-23T04:23:35.606Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Ingestion-to-Inference Bottleneck: Why Transformers are a Semantic Layer, Not a Replacement for SIEM DFA</h4><p>In the high-velocity telemetry pipelines of modern SecOps, we are witnessing a fundamental tension between computational throughput and semantic depth. For an enterprise-scale ingestion rate of 1⁰⁵ events per second (EPS), the per-event processing budget is ≈10μs.</p><p>Traditional SIEM detection logic utilizes Deterministic Finite Automata (DFA) — specifically regex engines like Hyperscan. These operate at O(n) time complexity relative to the log length n. In contrast, even a “small” Transformer architecture (e.g., a 66M-parameter DistilBERT) introduces a complexity of O(n² · d), where n is sequence length and d is the embedding dimension.</p><pre>┌─────────────────────┬────────────────────────┬─────────────────────────────┐<br>│ Metric              │ Rule-Based (Regex)     │ Transformer (BERT-base)     │<br>├─────────────────────┼────────────────────────┼─────────────────────────────┤<br>│ Inference Latency   │ 1–10 μs                │ 10–50 ms                    │<br>├─────────────────────┼────────────────────────┼─────────────────────────────┤<br>│ Throughput          │ ~100,000 logs/sec      │ ~20–100 logs/sec            │<br>├─────────────────────┼────────────────────────┼─────────────────────────────┤<br>│ Cost per 1B Logs    │ Negligible (CPU)       │ ~$300K+/year (GPU)          │<br>├─────────────────────┼────────────────────────┼─────────────────────────────┤<br>│ Complexity          │ O(n)                   │ O(n²) attention             │<br>├─────────────────────┼────────────────────────┼─────────────────────────────┤<br>│ Predictability      │ Deterministic          │ Variable (context-dependent)│<br>└─────────────────────┴────────────────────────┴─────────────────────────────┘</pre><p>From a first-principles perspective, this represents a 3-to-4 order of magnitude latency gap. Therefore, the engineering reality isn’t about replacing rules, but about building an Epistemic Filter that triages deterministic noise from stochastic signals.</p><h3>1. From Lexical Brittleness to Semantic Manifolds</h3><p>Rule-based systems suffer from structural entropy. A minor mutation in a log’s syntax — shifting a timestamp from Unix to ISO 8601 — invalidates the DFA.</p><p>By mapping logs into a Dense Vector Space ℝᵈ, Transformers treat logs as coordinates on a semantic manifold.</p><p><strong>Attention as Weighted Focus:</strong> The Attention mechanism assigns variable weight to specific tokens based on contextual relevance. High-information tokens receive more computational focus during inference — the model learns <em>what matters</em> rather than encoding it in rigid patterns.</p><p><strong>Manifold Proximity:</strong> Consider these two log messages:</p><pre>Log A: &quot;Connection refused to 10.0.1.45:443&quot;<br>Log B: &quot;Unable to establish socket: host 10.0.1.45 port 443 unreachable&quot;</pre><p>Lexically distinct. But in a fine-tuned embedding space like SecBERT, these map to proximate vectors. A classifier operating on embeddings detects the same underlying event regardless of format variation. This enables anomaly detection that is invariant to syntax changes.</p><h3>2. The Commercial Implementation: Hybrid Triage Pipelines</h3><p>The major SIEM/XDR vendors (Splunk, CrowdStrike, Elastic) are not putting Transformers in the “Hot Path.” Instead, they utilize a Tiered Inference Architecture:</p><pre>                         ┌─────────────────┐<br>                         │   Log Stream    │<br>                         └────────┬────────┘<br>                                  │<br>                         ┌────────▼────────┐<br>                         │    Layer 1:     │  ← μs latency<br>                         │  Regex Engine   │◀─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐<br>                         └────────┬────────┘                         │<br>                                  │                                  │<br>              ┌───────────────────┼───────────────────┐              │<br>              │                   │                   │              │<br>              │ Match             │ No Match          │ No Match     │<br>              │                   │ (Low-Value)       │ (High-Value) │<br>              ▼                   ▼                   ▼              │<br>   ┌─────────────────┐   ┌─────────────────┐   ┌─────────────────┐   │<br>   │   Immediate     │   │    Storage      │   │ Filtered Stream │   │<br>   │     Alert       │   │                 │   │  → ML Queue     │   │<br>   └─────────────────┘   └─────────────────┘   └────────┬────────┘   │<br>                                                        │            │<br>                                           ┌────────────▼──────────┐ │<br>                                           │       Layer 2:        │ │<br>                                           │  Transformer Model    │ ← ms latency<br>                                           └────────────┬──────────┘ │<br>                                                        │            │<br>                                              ┌─────────┴─────────┐  │<br>                                              │                   │  │<br>                                        Anomaly                 Normal<br>                                              │                   │  │<br>                                              ▼                   ▼  │<br>                                   ┌──────────────────┐  ┌──────────────────┐<br>                                   │ Secondary Alert  │  │     Storage      │<br>                                   │ / Risk Scoring   │  │                  │<br>                                   └────────┬─────────┘  └──────────────────┘<br>                                            │            │<br>                                            ▼            │<br>                                   ┌──────────────────┐  │<br>                                   │  LLM Rule        │  │<br>                                   │  Generator       │─ ┘<br>                                   └──────────────────┘</pre><h3>A. The Semantic Search Layer (Elastic ELSER)</h3><p>Elastic’s ELSER (Elastic Learned Sparse Encoder) uses a transformer-based model to expand raw logs into a sparse feature space.</p><p>Why sparse instead of dense? Dense vector search requires computing dot products across all stored embeddings — O(d) per comparison, multiplied across trillions of events. Sparse encoding projects into a high-dimensional space where most dimensions are zero, enabling inverted index lookups instead of brute-force similarity search. This provides the semantic benefits of a Transformer without the computational cost of dense vector search at scale.</p><h3>B. The Agentic Interface (CrowdStrike &amp; Splunk)</h3><p>Vendors like CrowdStrike (Charlotte AI) and Splunk (AI Assistant) utilize Transformers as an Orchestration Layer.</p><p><strong>Symbolic Reasoning:</strong> The Transformer translates natural language intent into mathematically optimized SPL or KQL.</p><p><strong>Execution:</strong> The heavy lifting remains with the high-performance DFA engines. This uses the Transformer for what it does best — reasoning — while leaving the “brute force” to C++ based regex engines.</p><h3>3. Epistemic Filtering: Verifying Truth at the Ingestion Boundary</h3><p>Hallucination and false positives in log analysis are often input-boundary problems. Applying a pre-processing verification layer allows the system to evaluate the logical coherence and structural validity of a log sequence before it reaches a Large Language Model.</p><p>This prevents wasted compute cycles — where a model allocates excessive processing time to malformed, duplicate, or low-value data. At $0.01+ per 1K tokens on hosted inference, a well-designed input filter can reduce inference costs by 60–80% while improving detection quality by ensuring the model focuses on structurally valid, high-priority events.</p><h3>4. Optimization Techniques: Narrowing the Gap</h3><p>For a Transformer to operate at the edge of a log stream, vendors are aggressively pursuing:</p><p><strong>Low-Rank Adaptation (LoRA):</strong> Fine-tuning specific sub-matrices to minimize the parameter count required for domain-specific tasks.</p><p><strong>Knowledge Distillation:</strong> Training “Student” models on a pure cybersecurity corpus. A 10M-parameter model trained exclusively on Linux Auditd can often out-perform a general 7B-parameter LLM for specific anomaly detection tasks.</p><p><strong>Quantization to INT8/FP4:</strong> Reducing bit-precision to leverage hardware-level Tensor Core acceleration, yielding a ≈4× throughput increase at a marginal cost to precision.</p><pre>┌─────────────────────┬─────────────────────┬─────────────────────┐<br>│ Optimization        │ Throughput Gain     │ Accuracy Tradeoff   │<br>├─────────────────────┼─────────────────────┼─────────────────────┤<br>│ INT8 Quantization   │ 2–4x                │ 1–3% degradation    │<br>├─────────────────────┼─────────────────────┼─────────────────────┤<br>│ Knowledge Distill.  │ 10–100x (smaller)   │ Task-dependent      │<br>├─────────────────────┼─────────────────────┼─────────────────────┤<br>│ LoRA Fine-tuning    │ ~1x (training only) │ Often improves      │<br>└─────────────────────┴─────────────────────┴─────────────────────┘</pre><h3>Conclusion: The Synthesis of DFA and Attention</h3><p>The “Rule-Based vs. Transformer” debate is a false dichotomy. In a mathematically optimized SIEM:</p><p><strong>Rules act as the High-Pass Filter:</strong> Discarding the 99.9% of benign, high-velocity noise.</p><p><strong>Transformers act as the Integrator:</strong> Connecting disparate, low-signal events into a coherent attack narrative.</p><p>The future isn’t a “Transformer SIEM.” It is a Hybrid Inference Engine that respects computational constraints while leveraging the semantic depth of modern sequence modeling.</p><p><em>References: LogLLM (2024), Elastic ELSER documentation, IBM Research log analytics benchmarks, CrowdStrike Charlotte AI architecture.</em></p><h3>What’s Next</h3><p>I write articles that bridge mathematics and physics with practical machine learning. My approach: take complex theoretical concepts and make them intuitive through code and visualization.</p><p><strong>Follow for more</strong>: medium.com/@sharmaraghav</p><p><strong>Written by Raghav Sharma</strong><br><em>Data Scientist with a background in physics, mathematics, and AI/ML</em><br>📧 <a href="/service/mailto:sharmaraghav644@gmail.com">sharmaraghav644@gmail.com</a><br>🔗 <a href="https://www.linkedin.com/in/raghav-sharma-b7a87a142/">LinkedIn</a> | <a href="https://raghav-sharma.com/">Portfolio</a> | <a href="https://github.com/sharmaraghav644">GitHub</a> | <a href="https://medium.com/@sharmaraghav644">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5416911cd47b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Genius of Srinivasa Ramanujan]]></title>
            <link>https://ai.plainenglish.io/the-genius-of-srinivasan-ramanujan-c51744e969ab?source=rss-fe39f9032e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c51744e969ab</guid>
            <category><![CDATA[ramanujan]]></category>
            <category><![CDATA[infinity]]></category>
            <category><![CDATA[formula]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Raghav Sharma]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 06:32:12 GMT</pubDate>
            <atom:updated>2025-08-04T18:36:13.285Z</atom:updated>
            <content:encoded><![CDATA[<h4>Uncovering the Mind That Challenged Infinity</h4><p>In one of my previous articles, I quoted Galileo, who famously said, <em>“Mathematics is the language of the universe.”</em> So, what about the people who are fluent in this language? The <em>polyglots</em>, the <em>Mozarts of mathematics</em>, the <em>da Vincis of numbers</em>. They must be geniuses, right? Yes, of course. But today is about someone who went far beyond anything we have ever called genius, a man whose intelligence still defies understanding.</p><p>Someone so far ahead that the world had to stretch its imagination just to catch up, just to give him the recognition he deserved.<br> His name? <strong>Srinivasa Ramanujan</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qjrw3y5V82Awuy02JJ4i2A.png" /><figcaption>Image by ChatGPT for author</figcaption></figure><h3>Early Life</h3><p>Ramanujan was born in a small town called Erode, in the Indian state of Tamil Nadu. His father was an accountant, and his mother was a housewife. I know some of you might be wondering if you accidentally stumbled upon his Wikipedia page, but just <em>bear</em> with me, these details are necessary to understand the level of intelligence we’re about to discuss.</p><p>Ramanujan’s formal education ended quite early. He studied up to the equivalent of 11th grade but never completed a college degree. In 1904, he enrolled at the Government Arts College in Kumbakonam. However, his obsession with mathematics came at a cost. He paid little attention to other subjects, which eventually led to the loss of his scholarship.</p><p>Determined to continue, he later enrolled at Pachaiyappa’s College in Madras (now Chennai), but the outcome was similar. He failed to pass most of the non-mathematical subjects, including English, which meant he couldn’t secure a degree there either. Talk about obsession with one thing, eh?</p><h3>His Letter to G.H Hardy</h3><p>In January 1913, while working as a low-paid clerk at the Madras Port Trust, Ramanujan took a bold step that would change his life and the course of modern mathematics. He wrote a letter to G. H. Hardy, a leading British mathematician at the University of Cambridge.</p><p>At the time, Hardy was one of the most respected figures in pure mathematics, known for his work in number theory and mathematical analysis.</p><p>Ramanujan’s letter, dated January 16, introduced himself modestly. He explained that he had no formal university education and earned just £20 a year. Attached to the letter were several pages filled with more than a hundred mathematical formulas. These included identities and theorems in number theory, infinite series, and continued fractions, all written without proofs.</p><p>Some results were so unconventional and advanced that Hardy briefly considered the possibility of a hoax. But as he studied the contents more closely, he realized their depth and originality. Hardy later remarked that the formulas must be true because if they were not, no one could have had the imagination to invent them.</p><p>You can read the whole letter here: <a href="https://archive.org/details/ramanujans_letter">https://archive.org/details/ramanujans_letter</a>.</p><p>This letter marked the beginning of a historic collaboration between two very different minds: one shaped by academic tradition and the other by pure, intuitive insight.</p><p>When I first came across the letter, I was <strong>awestruck</strong> by the level of humbleness reflected in Ramanujan’s words. It does make one wonder whether being humble has something to do with the greatest of inventions and discoveries.</p><h3>From Madras to Trinity</h3><p>After Hardy recognized the brilliance in Ramanujan’s letter, he arranged for him to travel to England. Despite initial hesitation due to religious and family concerns, Ramanujan eventually agreed.</p><p>In 1914, he left Madras for Cambridge, where he began working with Hardy at Trinity College. It was here that Ramanujan’s ideas found the environment and mentorship they needed.</p><h3>Challenges at Trinity</h3><p>Ramanujan’s transition into the academic world at Cambridge was far from smooth. He was not used to the formal style of mathematical proofs that British academia demanded. His work, often based on intuition and mental calculation, lacked the step-by-step rigor expected by the scholarly community. This created friction between his natural way of thinking and the structured environment of Trinity.</p><p>On top of these academic challenges, he also struggled with the cold climate, unfamiliar food, and a deep sense of isolation. His strict vegetarian diet was difficult to maintain in wartime England and, combined with the stress of cultural displacement, it severely affected his health.</p><p>We often dismiss someone’s contributions by saying they got lucky or were just gifted. But we seldom discuss the hard work and challenges they faced in their journey to greatness.</p><h3>Mathematical Work</h3><p>Now onto the fun part. It’s not possible to explain all of Ramanujan’s work in one article. I mean, mathematicians have been trying for over a century and are still not halfway through. So what chance do I have?</p><p>But I’ve tried my best to explain parts of his world using real-life examples.</p><h4>Partition Function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*yvQwwR8nRdBQlIIEbsPKyg.png" /><figcaption>Ramanujan’s partition formula</figcaption></figure><p>For example, for <strong>n = 4</strong>, the partitions are:</p><ul><li>4</li><li>3 + 1</li><li>2 + 2</li><li>2 + 1 + 1</li><li>1 + 1 + 1 + 1</li></ul><p>So, <strong>p(4) = 5</strong>.</p><p>At first glance, this seems like a playground for counting. But as <strong>n</strong> gets larger, the number of partitions grows <em>very</em> quickly — and here’s where Ramanujan did something absurdly remarkable. He didn’t just count partitions; he discovered deep, hidden patterns within them.</p><p>For instance, Ramanujan noticed congruences like:</p><ul><li><strong>p(5n + 4) ≡ 0 mod 5</strong></li><li><strong>p(7n + 5) ≡ 0 mod 7</strong></li><li><strong>p(11n + 6) ≡ 0 mod 11</strong></li></ul><p>This means that for any non-negative integer <em>n</em>, the number of partitions of 5n + 4 is divisible by 5, and similarly for the others.</p><p>These weren’t just patterns found through brute-force computation. They were uncovered through intuition that most mathematicians at the time couldn’t begin to grasp.</p><p>Hardy later admitted that while he could prove many of Ramanujan’s results, he could never understand how Ramanujan found them.</p><h4><strong>Mock Theta Functions</strong></h4><p>These are probably one of the strangest and most mysterious things Ramanujan ever discovered.</p><p>At the time, mathematicians were obsessed with something called <strong>modular forms</strong> — special kinds of functions that behave in very predictable and symmetrical ways when you stretch or flip the complex plane. Think of modular forms as functions that still look the same even after you’re looking at them through a funhouse mirror. That mirror is math’s version of symmetry, and modular forms are the champs at obeying those rules.</p><p>Now here comes Ramanujan. On his deathbed, he sends Hardy a letter that says, essentially, “Hey, here are some new functions I’ve been thinking about. They sort of behave like modular forms… but not quite.” And then he drops formulas like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*pw-dEvMKaDEJfkYNXBncpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*HJVgBWym7u8nA3ZV95mRpQ.png" /></figure><p>To most people back then, these equations looked like gibberish. The patterns were undeniable, but nobody could explain <em>why</em> they worked or what they <em>meant</em>.</p><p>Fast forward nearly 80 years, and a mathematician named <strong>Sander Zwegers</strong> finally figures it out. These “mock theta functions” are kind of like <strong>incomplete modular forms</strong>. They behave almost like modular forms — they try to follow the same rules — but they’re missing something. Once you add in that missing piece (which turns out to be a subtle correction term), everything clicks.</p><p>Today, these strange functions show up in high-level physics including <strong>black hole thermodynamics</strong> and <strong>string theory</strong>. Ramanujan was just exploring patterns that no one else could see.</p><h4><strong>Tau Function</strong></h4><p>Next up is the <strong>Ramanujan tau function</strong>. You know how you can break numbers down into <strong>prime factors</strong> — like 12 = 2 × 2 × 3? Well, Ramanujan discovered that there are other, deeper ways to assign meaning to numbers — by hiding that meaning in the <strong>coefficients of an infinite equation</strong>.</p><p>Here’s what he came up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*YqyO85BreL84tKQCAyU9cA.png" /></figure><p>Don’t get overwhelmed by the symbols. All this says is: Ramanujan found a function built out of an infinite product on the left side. And when you expand it into a series (the right side), you get a sequence of numbers called <strong>τ(n)</strong>.</p><p>The amazing part? These numbers — τ(1), τ(2), τ(3), etc. — have all kinds of bizarre and magical properties. For example:</p><ul><li>τ(2) = -24</li><li>τ(3) = 252</li><li>τ(5) = 4830</li></ul><p>So what? It means τ(n) is not just a random number. It’s connected to how numbers are built. That insight has shown up in areas like cryptography and algebraic geometry. Again, Ramanujan didn’t use any advanced machinery. He just “saw” it.</p><h4>Modular Form</h4><p>Now let’s talk about the big umbrella that the other two topics sort of live under: <strong>modular forms</strong>.</p><p>A modular form is a special kind of function that has <strong>built-in symmetry</strong>. The full definition gets technical, but here’s a basic idea.</p><p>Imagine you have a function that lives on the complex plane — the 2D world of imaginary numbers. A modular form is a function that doesn’t freak out when you twist, invert, or stretch the complex plane in very specific ways. In fact, it behaves <em>predictably</em> when you do that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*jVyCLbqJCUYqFOPAvP1xeg.png" /></figure><p>This rule is what makes it “modular.” And if that looks like a random soup of letters, don’t worry. What matters is that this equation tells you the function <em>repeats itself under transformation</em>, kind of like a geometric pattern that still looks the same if you flip it upside down or spin it.</p><p>Ramanujan was writing functions like <strong>Δ(q)</strong> (which defines the tau function) that follow these modular rules, even though the word “modular form” hadn’t even been formally invented yet.</p><p>Today, modular forms are everywhere:</p><ul><li>They’re the key to proving <strong>Fermat’s Last Theorem</strong></li><li>They appear in <strong>elliptic curves</strong>, which are used in modern encryption</li><li>They connect to <strong>string theory</strong>, <strong>particle physics</strong>, and even the <strong>structure of space-time</strong></li></ul><p>And again, Ramanujan was messing with them <em>before the rest of the world knew they existed</em>.</p><h4><strong>The Ramanujan-Hardy Collaboration</strong></h4><p>Hardy and Ramanujan published several joint papers during their time at Cambridge. Hardy ranked mathematicians on a scale from 0 to 100 — he gave himself a 25, David Hilbert (arguably the greatest of that era) a 80, and Ramanujan a 100 as well. That tells you something about what Hardy saw in him.</p><p>But what made their collaboration work was not just mutual respect, but their complementary approaches. Hardy brought the rigor, Ramanujan brought the fire.</p><h4><strong>Return to India and Death</strong></h4><p>Unfortunately, Ramanujan’s health never fully recovered. After spending five years in England, he returned to India in 1919. He was only 32. He died the following year in 1920, from complications related to liver infection and malnutrition.</p><p>He left behind three notebooks and one “lost” notebook that has since become legendary in mathematical circles. These notes contain thousands of results, many still being explored, understood, and proven today. Some of them are expected to play a role in physics, particularly in black hole entropy and string theory.</p><h3><strong>Legacy</strong></h3><p>To say Ramanujan was a genius is insufficient. He was something else entirely, someone whose mind worked in a way we still don’t fully understand. His insights came not from standard deduction but from what he often described as visions from a goddess (<strong><em>Namagiri</em></strong>). Whether one believes that or not is beside the point. What matters is that the results were real and extraordinary.</p><p>Even now, mathematicians open Ramanujan’s notebooks and find ideas that spark new research. His influence runs across number theory, combinatorics, algebra, and theoretical physics.</p><h3><strong>Conclusion</strong></h3><p>Ramanujan once said, <em>“</em><strong><em>An equation for me has no meaning, unless it expresses a thought of God</em></strong><em>.”</em> Maybe that’s what separates him from the rest of us. For many, mathematics is logic. For Ramanujan, it was poetry.</p><p>John Littlewood once wrote to Hardy during World War I:<br><em>“Every positive integer is a personal friend of Ramanujan.”</em></p><p>Perhaps he was right. Only a true friend can understand you, no matter what the world thinks of you.</p><p>His story isn’t just about brilliance. It’s about belief, perseverance, humility, and the strange paths through which talent reaches the world.<br>He didn’t just challenge infinity. He made it personal.</p><h3>What’s Next</h3><p>I write articles that bridge mathematics and physics with practical machine learning. My approach: take complex theoretical concepts and make them intuitive through code and visualization.</p><p><strong>Follow for more</strong>: medium.com/@sharmaraghav</p><p><strong>Written by Raghav Sharma</strong><br><em>Data Scientist with a background in physics, mathematics, and AI/ML</em><br>📧 <a href="/service/mailto:sharmaraghav644@gmail.com">sharmaraghav644@gmail.com</a><br>🔗 <a href="https://www.linkedin.com/in/raghav-sharma-b7a87a142/">LinkedIn</a> | <a href="https://raghav-sharma.com/">Portfolio</a> | <a href="https://github.com/sharmaraghav644">GitHub</a> | <a href="https://medium.com/@sharmaraghav644">Medium</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏️<strong>️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c51744e969ab" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/the-genius-of-srinivasan-ramanujan-c51744e969ab">The Genius of Srinivasa Ramanujan</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Einstein’s General Relativity Explains Attention in Transformers]]></title>
            <link>https://ai.plainenglish.io/how-einsteins-general-relativity-explains-attention-in-transformers-97cbda52fa68?source=rss-fe39f9032e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/97cbda52fa68</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Raghav Sharma]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 03:48:02 GMT</pubDate>
            <atom:updated>2025-06-21T05:20:20.725Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>The Gravity of Attention: When Neural Networks Bend Information Like Light.</strong></h4><p>My introduction to the General Theory of Relativity in college was profoundly impactful. It took months to grasp the basic concept, but once I did, it completely reshaped my understanding. To say I was dumbfounded would be an understatement; it remains the most fascinating subject I’ve ever encountered. While literary figures like Dostoevsky and Jaun Elia are highly regarded, Einstein’s ideas still hold the top spot for me.</p><p>Let’s use a simple illustration to understand it better. Imagine a <strong>trampoline</strong> with a <strong>heavy medicine ball</strong> placed in its <strong>center</strong>. If you roll smaller balls across the trampoline in a <strong>particular</strong> <strong>way</strong>, they will orbit the medicine ball, which has caused the fabric to bend. Eventually, some of these smaller balls might spiral inward and make contact with the heavy ball in the middle. Now, if you shine a laser beam across the trampoline, it will follow the <strong>contour</strong> of the <strong>fabric</strong>, dipping down where the fabric is most stretched (around the heavy ball) and rising back up as the fabric levels out. It behaves as if it’s guided by the trampoline’s surface.</p><p>In reality, that heavy ball represents a massive object like a <strong>black</strong> <strong>hole</strong>, or our Sun in our solar system, which warps the fabric of <strong>spacetime</strong>. The smaller balls are analogous to planets orbiting the Sun. The laser beam represents light, which travels along the <strong>curvature</strong> of <strong>spacetime</strong> and <strong>bends</strong> when it encounters the <strong>warped</strong> region created by a massive object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2fMTPGSsgOEgZ9Ibui9Eg.png" /><figcaption>Image created by ChatGPT for author</figcaption></figure><p>Now take neural networks, especially transformers. Information does not pass linearly through them either. It twists, detours, and converges depending on which tokens are present. Some tokens act like gravitational centers. They alter how other tokens are processed. Not just metaphorically, but literally in the sense of vector transformations and attention flow. I have explained what transformers are in my previous article: <a href="https://medium.com/ai-in-plain-english/how-newton-would-have-built-chatgpt-the-mathematical-physics-of-attention-db3b7529916f">https://medium.com/ai-in-plain-english/how-newton-would-have-built-chatgpt-the-mathematical-physics-of-attention-db3b7529916f</a> which explores the commonalities between newtonian mechanics and transformers.</p><p>In this piece, I explore another idea: what if attention works like gravity? Not the applications and affects of gravity which are evident in the newtonian physics but rather, the very reasoning of gravity. In General Theory of Relativity, gravity is not a force but a<strong> manifestation of the curvature of spacetime</strong> caused by the presence of <strong>mass and energy.</strong> What if important tokens bend the space of representation, not just statistically but geometrically? What if the way information flows through a transformer looks less like a straight pipe and more like a beam of light curving through warped spacetime?</p><h3><strong>Section 1: Attention Isn’t Flat</strong></h3><p>Transformers use self-attention to decide which tokens matter most for a given word. Each token calculates a set of weights over the others. These weights change depending on the sentence, context, and model depth. If I say that “Hi, I am not well” to a few of my friends, then depending upon my importance in their eyes, their response will vary. Some might say oh take some medicine and rest while others might say, yeah you are making excuses. I know you well. Come on now!</p><p>Their understanding of the <strong>object</strong> (me) in their own mind decides the level of <strong>importance</strong> they will give to <strong>whatever</strong> I <strong>say</strong>. Similarly, transformers look at the sentence all at once and decide which word(s) they want to focus on. That will decide their action(s) and their response(s). Just FYI, the analogy between “importance in their eyes” and “understanding of the object (me) in their own mind” is just for the sake of human <strong>centricity</strong>. In the technical sense, the model learns these “understandings” through vast amounts of data.</p><p>That means there is no fixed path for information to travel. Instead, each token builds a dynamic influence map that affects how nearby representations shift. When a transformer pays more attention to a specific token, it pulls the flow of information toward it. Like a massive object bending spacetime.</p><p>Visualize a sentence like this: “The black hole consumed the surrounding matter.” The term “black hole” might act like a heavy mass, pulling extra attention from verbs like “consumed” or nouns like “matter.” This reshapes how those words are encoded downstream.</p><h3><strong>Section 2: Attention Scores as Gravitational Influence</strong></h3><p>In general relativity, <strong>mass curves spacetime</strong>. In transformers, <strong>token relevance</strong> curves the information space.</p><p>The attention scores, calculated from the dot product between query and key vectors, define how much one token affects another. These scores act like gravitational influence. The higher the score, the stronger the pull. That pull is not symmetric or linear. Just as gravitational lensing distorts light around massive stars, high attention distorts how representation vectors evolve.</p><p>Let Q and K be the query and key matrices. Attention is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*yCxwTlGZK7BxnxiWXEVoEA.png" /><figcaption>Scaled Dot-Product Attention</figcaption></figure><p>Think of this part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*60Pi4u0Gptr1yn5GO7Wj3w.png" /></figure><p>as a potential field. High values in this field pull representations in the direction of the corresponding value vectors. This is mathematically similar to potential fields in gravity, where the gradient of the potential determines the force applied.</p><h4><strong>The Geodesic Equation and Attention Dynamics</strong></h4><p>In Einstein’s theory, the bending of light by gravity is calculated using the geodesic equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*heUG4OJP1MTTCBh-fXXsEA.png" /><figcaption>Geodesic equation</figcaption></figure><p>where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/57/1*xWNWzJqtQAVO9tTQQ3SQAw.png" /></figure><p>are the <strong><em>Christoffel</em></strong> symbols representing spacetime curvature, and <strong><em>τ</em></strong> is the proper time.</p><p>The geodesic equation tells you how objects move when nothing is pushing or pulling on them except gravity. In everyday terms, it shows how things travel through space and time when they are just “falling freely” due to gravity.</p><p>In flat space, like on a sheet of paper, the straightest path between two points is a straight line. But near a massive object like a planet or a star, space and time are curved. The geodesic equation calculates the curved path that an object will follow in that kind of space.</p><p>For light, this equation explains why its path bends when it goes near something heavy like the Sun. Even though light has no mass, it still follows the curves of spacetime created by mass. The equation uses the spacetime geometry (which comes from Einstein’s field equations) to figure out exactly how that path curves.</p><h4><strong>Attention as Force Fields</strong></h4><p>Just as gravitational fields can be described by their gradients, attention creates force fields in representation space. The gradient of attention scores ∇A(Q,K) acts like a vector field that pulls token representations toward regions of high attention. This creates a natural flow of information from less attended to more attended tokens.</p><p>The deflection angle of light by a mass at a distance is approximately:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*1kik3uNkCYZCldNMBzbWtA.png" /><figcaption>gravitational deflection angle</figcaption></figure><p>This equation tells you how much a beam of light bends when it passes near something heavy, like a star or a planet.</p><p>The amount of bending depends on two things:</p><ol><li><strong>How massive the object is</strong> — a heavier object bends light more</li><li><strong>How close the light passes to it</strong> — the closer the light gets, the more it bends</li></ol><p>Analogously, attention pulls harder when a token is more contextually important.</p><h4>Multi-Head Attention as Tensor Fields</h4><p>Multi-head attention creates multiple overlapping gravitational fields, each capturing different aspects of token relationships. Like tensor fields in physics, these multiple attention heads can be combined to form a more complete picture of the information geometry. Each head h can be thought of as a separate spacetime metric g_h that describes how information flows in its particular subspace.</p><p>The combined effect of all heads creates a rich tensor field:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*SldLMJvFzwIZjNzcvkXlqQ.png" /></figure><p>where <strong><em>W_h</em></strong> are learned weights that determine how much each attention head contributes to the final representation.</p><h4>Attention Horizons and Conservation Laws</h4><p>Beyond a certain distance in sequence length, tokens effectively cannot influence each other, creating “attention horizons” similar to event horizons in black holes. This natural cutoff is partly why transformers struggle with very long sequences.</p><p>Attention weights sum to 1, analogous to energy conservation in physics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*7r3FKj-Xk4BTncDW01ECcg.png" /></figure><p>This constraint shapes how attention “mass” can be distributed. If one token receives very high attention, others must receive proportionally less, creating a zero-sum game similar to gravitational systems where total energy is conserved.</p><h4>Information Geometry and Curved Manifolds</h4><p>Attention creates curved information manifolds where the “straight line” relationships between tokens become geodesics in the curved space. High attention regions act like massive objects that warp the local geometry, forcing information to flow along curved paths rather than direct connections.</p><h4>Tidal Effects in High Attention Regions</h4><p>Very high attention scores can create “tidal effects” where nearby tokens get stretched or compressed in representation space. Just as objects near massive bodies experience different gravitational forces on their near and far sides, tokens near high-attention regions experience differential pulling forces that can distort their representations.</p><h4>Attention Dynamics Over Layers</h4><p>Attention patterns evolve through layers like particles following geodesics through time. Earlier layers might show more “local gravity” where tokens primarily attend to their immediate neighbours, while later layers develop “long-range forces” that can connect distant but semantically related tokens.</p><p>This layered evolution creates increasingly complex gravitational landscapes, where simple local interactions in early layers give rise to sophisticated global patterns in deeper layers.</p><h4>Gravitational Deflection Simulator: From Stars to Black Holes</h4><p>Real astronomical objects bend spacetime with measurable precision. For a light ray grazing the surface of the Sun, the General Relativity prediction is 1.75 arcseconds, confirmed by observations since the famous 1919 eclipse experiment. Let’s create a simulator that shows how different stellar objects bend light, then connect this to attention patterns.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.constants import G, c<br>import pandas as pd<br><br># Define stellar objects with their properties<br>stellar_objects = {<br>    &#39;Sun&#39;: {&#39;mass&#39;: 1.989e30, &#39;radius&#39;: 6.96e8, &#39;color&#39;: &#39;gold&#39;},<br>    &#39;White Dwarf&#39;: {&#39;mass&#39;: 1.1e30, &#39;radius&#39;: 6e6, &#39;color&#39;: &#39;lightblue&#39;},<br>    &#39;Neutron Star&#39;: {&#39;mass&#39;: 2.8e30, &#39;radius&#39;: 1.2e4, &#39;color&#39;: &#39;purple&#39;},<br>    &#39;Stellar Black Hole&#39;: {&#39;mass&#39;: 1.0e31, &#39;radius&#39;: 3e4, &#39;color&#39;: &#39;black&#39;},<br>    &#39;Supermassive Black Hole&#39;: {&#39;mass&#39;: 4e36, &#39;radius&#39;: 1.2e10, &#39;color&#39;: &#39;darkred&#39;}<br>}<br><br>def gravitational_deflection_angle(mass, impact_parameter):<br>    &quot;&quot;&quot;<br>    Calculate gravitational deflection angle using Einstein&#39;s formula<br>    θ = 4GM/(c²b) where b is the impact parameter<br>    &quot;&quot;&quot;<br>    return 4 * G * mass / (c**2 * impact_parameter)<br><br>def deflection_in_arcseconds(mass, impact_parameter):<br>    &quot;&quot;&quot;Convert deflection angle to arcseconds for easier comparison&quot;&quot;&quot;<br>    angle_radians = gravitational_deflection_angle(mass, impact_parameter)<br>    return angle_radians * 206265  # Convert radians to arcseconds<br><br># Create deflection comparison<br>fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))<br><br># Impact parameters (distance from object surface)<br>distances = np.logspace(0, 3, 100)  # From 1 to 1000 times the object radius<br><br># Plot 1: Deflection vs distance for different objects<br>for name, props in stellar_objects.items():<br>    if name != &#39;Supermassive Black Hole&#39;:  # Skip for scale reasons<br>        impact_params = distances * props[&#39;radius&#39;]<br>        deflections = [deflection_in_arcseconds(props[&#39;mass&#39;], b) for b in impact_params]<br>        ax1.loglog(distances, deflections, label=f&quot;{name}&quot;, color=props[&#39;color&#39;], linewidth=2)<br><br>ax1.set_xlabel(&#39;Distance (in units of object radius)&#39;)<br>ax1.set_ylabel(&#39;Deflection Angle (arcseconds)&#39;)<br>ax1.set_title(&#39;Gravitational Light Deflection by Different Stellar Objects&#39;)<br>ax1.legend()<br>ax1.grid(True, alpha=0.3)<br><br># Add Sun&#39;s measured value as reference<br>sun_measured = 1.75  # arcseconds at grazing incidence<br>ax1.axhline(y=sun_measured, color=&#39;red&#39;, linestyle=&#39;--&#39;, alpha=0.7, <br>           label=f&#39;Sun measured: {sun_measured}&quot;&#39;)<br><br># Plot 2: Deflection at grazing incidence (surface)<br>objects = list(stellar_objects.keys())<br>grazing_deflections = []<br><br>for name, props in stellar_objects.items():<br>    deflection = deflection_in_arcseconds(props[&#39;mass&#39;], props[&#39;radius&#39;])<br>    grazing_deflections.append(deflection)<br><br># Create bar plot with logarithmic scale<br>bars = ax2.bar(range(len(objects)), grazing_deflections, <br>               color=[stellar_objects[obj][&#39;color&#39;] for obj in objects])<br><br>ax2.set_yscale(&#39;log&#39;)<br>ax2.set_xlabel(&#39;Stellar Object&#39;)<br>ax2.set_ylabel(&#39;Deflection Angle (arcseconds)&#39;)<br>ax2.set_title(&#39;Light Deflection at Object Surface&#39;)<br>ax2.set_xticks(range(len(objects)))<br>ax2.set_xticklabels(objects, rotation=45)<br><br># Add value labels on bars<br>for i, (bar, deflection) in enumerate(zip(bars, grazing_deflections)):<br>    height = bar.get_height()<br>    if deflection &gt; 1:<br>        label = f&#39;{deflection:.1f}&quot;&#39;<br>    else:<br>        label = f&#39;{deflection:.3f}&quot;&#39;<br>    ax2.text(bar.get_x() + bar.get_width()/2., height * 1.1,<br>             label, ha=&#39;center&#39;, va=&#39;bottom&#39;, fontsize=9)<br><br>plt.tight_layout()<br>plt.show()<br><br># Print comparison table<br>print(&quot;\nGravitational Deflection Comparison&quot;)<br>print(&quot;=&quot; * 60)<br>print(f&quot;{&#39;Object&#39;:&lt;20} {&#39;Mass (Solar)&#39;:&lt;12} {&#39;Radius (km)&#39;:&lt;12} {&#39;Deflection&#39;:&lt;12}&quot;)<br>print(&quot;-&quot; * 60)<br><br>for name, props in stellar_objects.items():<br>    mass_solar = props[&#39;mass&#39;] / stellar_objects[&#39;Sun&#39;][&#39;mass&#39;]<br>    radius_km = props[&#39;radius&#39;] / 1000<br>    deflection = deflection_in_arcseconds(props[&#39;mass&#39;], props[&#39;radius&#39;])<br>    <br>    if deflection &gt; 1:<br>        deflection_str = f&quot;{deflection:.1f}\&quot;&quot;<br>    else:<br>        deflection_str = f&quot;{deflection:.3f}\&quot;&quot;<br>    <br>    print(f&quot;{name:&lt;20} {mass_solar:&lt;12.1f} {radius_km:&lt;12.0f} {deflection_str:&lt;12}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nwg3LWSi2EFeMy6b7fjuWw.png" /><figcaption>Image by author</figcaption></figure><pre>Gravitational Deflection Comparison<br>============================================================<br>Object               Mass (Solar) Radius (km)  Deflection  <br>------------------------------------------------------------<br>Sun                  1.0          696000       1.8&quot;        <br>White Dwarf          0.6          6000         112.3&quot;      <br>Neutron Star         1.4          12           142964.0&quot;   <br>Stellar Black Hole   5.0          30           204234.3&quot;   <br>Supermassive Black Hole 2011060.8    12000000     204234.3&quot;   </pre><p>This simulator reveals how dramatically different objects curve spacetime. Recent Hubble observations used gravitational lensing to measure the mass of a white dwarf star called LAWD 37, finding it to be 56 percent the mass of our Sun, demonstrating how these measurements are actively used in astronomy.</p><h4><strong>Python Code: Visualizing Attention Bending Toward Heavy Tokens</strong></h4><p>The following code demonstrates how attention creates gravitational-like effects by analyzing which tokens act as “massive objects” that attract attention from others.</p><pre>import torch<br>import matplotlib.pyplot as plt<br>from transformers import BertTokenizer, BertModel<br>import numpy as np<br>import string<br>import seaborn as sns<br><br># Load model and tokenizer<br>tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>model = BertModel.from_pretrained(&quot;bert-base-uncased&quot;, output_attentions=True)<br>model.eval()<br><br># Sentence with meaningful words<br>sentence = &quot;Scientists discovered a revolutionary cure for the deadly disease.&quot;<br>inputs = tokenizer(sentence, return_tensors=&quot;pt&quot;)<br>tokens = tokenizer.convert_ids_to_tokens(inputs[&quot;input_ids&quot;][0])<br><br>with torch.no_grad():<br>    outputs = model(**inputs)<br><br># Get attention from last layer, all heads<br>attentions = outputs.attentions[-1][0].numpy()  # shape: (num_heads, seq_len, seq_len)<br><br># Calculate both attention received and attention given<br>attention_received = attentions.sum(axis=0).sum(axis=0)  # Total attention received<br>attention_given = attentions.sum(axis=1).sum(axis=0)     # Total attention given<br><br># Merge subtokens for tokens and attention<br>def combine_subtokens(tokens, attn_received, attn_given):<br>    combined_tokens = []<br>    combined_received = attn_received.copy()<br>    combined_given = attn_given.copy()<br>    i = 0<br>    while i &lt; len(tokens):<br>        if tokens[i].startswith(&quot;##&quot;) and i &gt; 0:<br>            combined_tokens[-1] += tokens[i][2:]<br>            combined_received[-1] += combined_received[i]<br>            combined_given[-1] += combined_given[i]<br>            combined_received = np.delete(combined_received, i)<br>            combined_given = np.delete(combined_given, i)<br>            tokens.pop(i)<br>        else:<br>            combined_tokens.append(tokens[i])<br>            i += 1<br>    return combined_tokens, combined_received, combined_given<br><br>tokens_combined, attention_received_combined, attention_given_combined = combine_subtokens(<br>    tokens.copy(), attention_received, attention_given<br>)<br><br># Filter out special tokens and punctuation<br>punctuation = set(string.punctuation)<br>filtered_tokens = []<br>filtered_received = []<br>filtered_given = []<br><br>for t, r, g in zip(tokens_combined, attention_received_combined, attention_given_combined):<br>    if t not in (&quot;[CLS]&quot;, &quot;[SEP]&quot;) and t not in punctuation:<br>        filtered_tokens.append(t)<br>        filtered_received.append(r)<br>        filtered_given.append(g)<br><br># Normalize attention for better visualization<br>attention_received_norm = np.array(filtered_received) / np.sum(filtered_received)<br>attention_given_norm = np.array(filtered_given) / np.sum(filtered_given)<br><br># Create visualization showing both gravitational mass and attraction<br>fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(14, 12))<br><br># Plot 1: Attention received (gravitational attraction)<br>sorted_indices_received = np.argsort(attention_received_norm)<br>sorted_tokens_received = [filtered_tokens[i] for i in sorted_indices_received]<br>sorted_attention_received = attention_received_norm[sorted_indices_received]<br><br>ax1.bar(sorted_tokens_received, sorted_attention_received, color=&#39;darkred&#39;, alpha=0.7)<br>ax1.set_xlabel(&quot;Tokens&quot;)<br>ax1.set_ylabel(&quot;Normalized Attention Received&quot;)<br>ax1.set_title(&quot;Gravitational Attraction: How Much Each Token Pulls Others Toward It&quot;)<br>ax1.tick_params(axis=&#39;x&#39;, rotation=45)<br><br># Plot 2: Attention given (gravitational influence)<br>sorted_indices_given = np.argsort(attention_given_norm)<br>sorted_tokens_given = [filtered_tokens[i] for i in sorted_indices_given]<br>sorted_attention_given = attention_given_norm[sorted_indices_given]<br><br>ax2.bar(sorted_tokens_given, sorted_attention_given, color=&#39;darkblue&#39;, alpha=0.7)<br>ax2.set_xlabel(&quot;Tokens&quot;)<br>ax2.set_ylabel(&quot;Normalized Attention Given&quot;)<br>ax2.set_title(&quot;Gravitational Mass: How Much Each Token Influences Others&quot;)<br>ax2.tick_params(axis=&#39;x&#39;, rotation=45)<br><br># Plot 3: Attention field heatmap<br>attention_matrix = attentions.mean(axis=0)  # Average across heads<br>mask = np.ones_like(attention_matrix, dtype=bool)<br>for i, token in enumerate(tokens):<br>    if token in (&quot;[CLS]&quot;, &quot;[SEP]&quot;) or token in punctuation:<br>        mask[i, :] = False<br>        mask[:, i] = False<br><br>filtered_matrix = attention_matrix[mask].reshape(len(filtered_tokens), len(filtered_tokens))<br><br>im = ax3.imshow(filtered_matrix, cmap=&#39;viridis&#39;, aspect=&#39;auto&#39;)<br>ax3.set_xticks(range(len(filtered_tokens)))<br>ax3.set_yticks(range(len(filtered_tokens)))<br>ax3.set_xticklabels(filtered_tokens, rotation=45)<br>ax3.set_yticklabels(filtered_tokens)<br>ax3.set_xlabel(&quot;Key Tokens&quot;)<br>ax3.set_ylabel(&quot;Query Tokens&quot;)<br>ax3.set_title(&quot;Attention Gravitational Field: Strength of Influence Between Token Pairs&quot;)<br><br># Add colorbar<br>plt.colorbar(im, ax=ax3, label=&#39;Attention Weight&#39;)<br><br>plt.tight_layout()<br>plt.show()<br><br># Calculate and display attention &quot;masses&quot; and &quot;attractions&quot;<br>print(&quot;Token Gravitational Properties:&quot;)<br>print(&quot;=&quot; * 50)<br>for i, token in enumerate(filtered_tokens):<br>    mass = attention_given_norm[i]<br>    attraction = attention_received_norm[i]<br>    print(f&quot;{token:15} | Mass: {mass:.3f} | Attraction: {attraction:.3f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jk2LALORryQq_mC2x3kk9Q.png" /><figcaption>Image by author</figcaption></figure><pre>Token Gravitational Properties:<br>==================================================<br>scientists      | Mass: 0.128 | Attraction: 0.128<br>discovered      | Mass: 0.131 | Attraction: 0.131<br>a               | Mass: 0.126 | Attraction: 0.126<br>revolutionary   | Mass: 0.112 | Attraction: 0.112<br>cure            | Mass: 0.103 | Attraction: 0.103<br>for             | Mass: 0.090 | Attraction: 0.090<br>the             | Mass: 0.102 | Attraction: 0.102<br>deadly          | Mass: 0.093 | Attraction: 0.093<br>disease         | Mass: 0.114 | Attraction: 0.114</pre><h4>The Mathematical Similarity</h4><p><strong>Space Physics:</strong></p><pre>Deflection Angle = 4GM/(c²b)<br>↑                    ↑<br>How much           How massive<br>light bends        the object is</pre><p><strong>Transformer Attention:</strong></p><pre>Attention Score = softmax(QK^T/√d_k)<br>↑                         ↑<br>How much               How important/relevant<br>meaning flows          the word relationship is</pre><p>Deflection angle measures how much a massive object bends light passing by it, while attention score measures how much one word pulls meaning/focus from other words toward itself — both measure the “pulling power” or influence strength, but deflection shows the effect on something passing by, while attention shows the effect of drawing things toward you.</p><p>The analogy is:</p><ul><li><strong>High deflection angle</strong> = <strong>High attention received</strong> (both show strong pulling power)</li><li>A massive star that deflects light by 1000° is like a word that receives high attention (0.8) — both are “gravity wells” that strongly influence their surroundings.</li></ul><h4>Emergent Phenomena in Attention Gravity</h4><p>Just as complex orbital mechanics emerge from simple gravitational laws, sophisticated linguistic behaviours emerge from basic attention mechanisms. Tokens can form “orbital” relationships where function words orbit around content words, or create “binary systems” where two related concepts mutually attend to each other with high intensity.</p><p>These emergent patterns demonstrate how the simple mathematical operation of scaled dot-product attention can give rise to complex information dynamics that mirror the rich behaviours we observe in gravitational systems throughout the universe.</p><h4>Section 3: Geodesics and the Flow of Meaning</h4><p>In curved spacetime, objects follow geodesics — paths that are locally straight but globally curved. A photon traveling past the Sun doesn’t “know” about gravity; it simply follows the straightest possible path through the curved spacetime around the Sun.</p><p>Similarly, in transformers, token representations don’t “know” about context in advance. They evolve through layers by following the paths of steepest gradient descent through a landscape shaped by attention weights. The attention mechanism curves the representation space, and tokens naturally flow along the resulting geodesics.</p><p>This geometric perspective explains contextual word meaning. Consider the word “bank”:</p><ul><li>In “river bank,” surrounding tokens like “river,” “water,” and “shore” create attention patterns that curve the representation space toward geographical meanings</li><li>In “bank account,” tokens like “money,” “deposit,” and “savings” create different curvature patterns that guide the representation toward financial meanings</li></ul><p>The same starting representation follows different geodesics through differently curved spaces, arriving at distinct semantic destinations. This isn’t magical disambiguation, it’s the natural result of representations flowing along the paths of least resistance through attention-curved space.</p><h4>Mathematical Foundation: Curvature and Representation Evolution</h4><p>In Riemannian geometry, the Riemann curvature tensor <strong>R</strong> measures how parallel transport fails in curved space. When you move a vector along different paths in curved space, it ends up pointing in different directions.</p><p>In transformers, we can observe analogous behaviour. Token representations that start similar can diverge significantly as they flow through attention-curved layers. The “curvature” induced by attention patterns determines how much and in what direction these representations separate.</p><p>For example, in the sentence “The lead singer and lead guitar created heavy metal music,” the two instances of “lead” start with identical representations but follow different geodesics:</p><ul><li>“lead singer” curves toward person/role meanings</li><li>“lead guitar” curves toward object/instrument meanings</li></ul><p>The attention weights from context words create different local curvatures, causing the representations to follow divergent paths through the network.</p><h3><strong>Section 4: Can We Measure This Curvature?</strong></h3><p>If attention truly curves representation space, we should be able to measure this curvature and use it to understand model behaviour. Several approaches can quantify the geometric properties of attention patterns.</p><h4>Gradient-Based Curvature Analysis</h4><p>The most direct approach examines how token representations change as we move through the attention landscape. High curvature regions show rapid changes in representation for small changes in input.</p><p>We can measure this by computing the Hessian (second derivatives) of the loss function with respect to token positions in attention space. Regions with high eigenvalues in the Hessian matrix correspond to high curvature areas where small perturbations cause large representation changes.</p><h4>Graph-Theoretic Curvature Measures</h4><p>We can treat attention matrices as weighted graphs and apply discrete curvature measures. The Ollivier-Ricci curvature adapted for attention graphs provides meaningful insights:</p><p><strong>Ollivier-Ricci Curvature Formula:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*lMjS-YBaTtKOZIGHIVrR3Q.png" /></figure><p>Where:</p><ul><li><strong>μᵢ</strong> is the probability distribution of attention weights from token i to all other tokens</li><li><strong>μⱼ</strong> is the probability distribution of attention weights from token j to all other tokens</li><li><strong>W₁(μᵢ, μⱼ)</strong> is the Wasserstein-1 distance between these distributions</li><li><strong>d(i, j)</strong> is the graph distance between tokens i and j</li></ul><h4>Interpreting Curvature Values</h4><p><strong>Positive curvature (κ &gt; 0):</strong></p><ul><li>Attention distributions are similar between neighboring tokens</li><li>Information is concentrating or converging</li><li>Often found around content words that serve as semantic anchors</li><li>Example: In “The cat sat,” high positive curvature between “cat” and “sat” indicates focused subject-verb attention</li></ul><p><strong>Negative curvature (κ &lt; 0):</strong></p><ul><li>Attention distributions diverge between neighbouring tokens</li><li>Information is spreading or exploring multiple possibilities</li><li>Often found in ambiguous regions or between semantically distant concepts</li><li>Example: In “Time flies like an arrow,” negative curvature around “flies” reflects multiple possible parse structures</li></ul><p><strong>Near-zero curvature (κ ≈ 0):</strong></p><ul><li>Flat attention landscape</li><li>Uniform or predictable information flow</li><li>Often found in function words or routine syntactic patterns</li></ul><h4>Practical Applications of Curvature Analysis</h4><p><strong>Model Interpretability:</strong></p><ul><li>High curvature regions indicate where the model is making critical decisions</li><li>Curvature maps can reveal which tokens serve as “information hubs”</li><li>Negative curvature areas may indicate where the model is uncertain</li></ul><p><strong>Attention Optimization:</strong></p><ul><li>Training can be regularized to encourage appropriate curvature patterns</li><li>Avoiding excessive negative curvature can improve model stability</li><li>Promoting positive curvature around key content words can improve performance</li></ul><p><strong>Robustness Analysis:</strong></p><ul><li>High curvature regions are more sensitive to adversarial perturbations</li><li>Curvature analysis can identify vulnerable parts of the attention landscape</li><li>Flattening excessive curvature can improve robustness</li></ul><h3>Conclusion: Geometry as the Language of Intelligence</h3><p>The geometric perspective on transformers reveals something profound about how intelligent systems process information. Rather than viewing neural networks as static function approximators, we can understand them as dynamic systems that actively reshape the geometry of information space during computation.</p><h4>Beyond Function Approximation</h4><p>Traditional machine learning focuses on mapping inputs to outputs through learned functions. The geometric view suggests something richer: <strong>intelligent systems create and navigate curved information manifolds where meaning emerges from spatial relationships</strong>.</p><p>This isn’t just metaphor. The mathematical tools of differential geometry — geodesics, curvature tensors, parallel transport as they might provide precise ways to analyze and understand transformer behavior. Attention weights literally define a metric tensor that determines distances and angles in representation space.</p><h4>Implications for AI Research</h4><p><strong>Architecture Design:</strong> Instead of designing attention mechanisms purely for performance, we can design them to create beneficial geometric properties. What kind of curvature patterns support robust reasoning? How should information manifolds be structured for compositional understanding?</p><p><strong>Training Objectives:</strong> Current training focuses on prediction accuracy. Geometric insights suggest additional objectives: encouraging appropriate curvature patterns, maintaining geodesic stability, or optimizing information flow geometry.</p><p><strong>Interpretability:</strong> Rather than asking “What is this network computing?” we can ask “What kind of space is this network creating?” Curvature analysis, geodesic visualization, and manifold mapping provide new tools for understanding model behaviour.</p><h4>The Deeper Principle</h4><p>Einstein’s key insight was that gravity isn’t a force, it’s the curvature of spacetime itself. Objects follow geodesics not because they’re being pushed or pulled, but because they’re taking the straightest possible paths through curved space.</p><p>Similarly, attention in transformers might not be “selecting” information in the traditional sense. Instead, attention curves the representation space, and information naturally flows along the resulting geodesics. Complex linguistic phenomena like disambiguation, inference, and understanding emerge from this geometric structure rather than being explicitly programmed.</p><h3>Looking Forward</h3><p>Some existing work has explored geometric ideas in neural networks, but this perspective outlines concrete directions that remain underdeveloped and could benefit from a unified geometric approach:</p><ul><li><strong>Curvature-based regularization:</strong> Although Ricci and other curvature measures have been used in graph and latent space models, there is room to go further by directly controlling curvature during training. In transformers, for example, curvature could reflect how information compresses or expands within layers.</li><li><strong>Geodesic analysis:</strong> Analyzing geodesic paths through representation space may offer insights into how meaning shifts across layers or token positions. Unlike simple interpolation, geodesics account for the geometry of the space and could align more closely with actual semantic transitions.</li><li><strong>Manifold engineering:</strong> While curved spaces like hyperbolic and spherical geometries have been applied in specific tasks, this framework points toward designing manifolds that reflect the structure of the task or data. Adjusting curvature and metric properties could help encode relational or hierarchical information more effectively.</li><li><strong>Topological invariants:</strong> Persistent homology has been used to study learned representations, but its application to track stability across training or detect structural changes within models is still largely unexplored. This could reveal stable features or sudden shifts that mark key stages in learning.</li></ul><p>The mathematics of curved spaces, developed to understand the cosmos, may hold keys to understanding minds — both artificial and natural. Information, like light, follows paths through spaces that are far from flat. And in those curved trajectories, meaning itself might emerge.</p><p>Just as Einstein’s geometric insights revolutionized physics, thinking geometrically about intelligence might transform how we build and understand artificial minds. The universe of information, like the physical universe, appears to be fundamentally curved.</p><h3>What’s Next</h3><p>I write articles that bridge mathematics and physics with practical machine learning. My approach: take complex theoretical concepts and make them intuitive through code and visualization.</p><p><strong>Follow for more</strong>: medium.com/@sharmaraghav</p><p><strong>Written by Raghav Sharma</strong><br><em>Data Scientist with a background in physics, mathematics, and AI/ML</em><br>📧 <a href="/service/mailto:sharmaraghav644@gmail.com">sharmaraghav644@gmail.com</a><br>🔗 <a href="https://www.linkedin.com/in/raghav-sharma-b7a87a142/">LinkedIn</a> | <a href="https://raghav-sharma.com/">Portfolio</a> | <a href="https://github.com/sharmaraghav644">GitHub</a> | <a href="https://medium.com/@sharmaraghav644">Medium</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97cbda52fa68" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/how-einsteins-general-relativity-explains-attention-in-transformers-97cbda52fa68">How Einstein’s General Relativity Explains Attention in Transformers</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Newton Would Have Built ChatGPT: The Mathematical Physics of Attention]]></title>
            <link>https://ai.plainenglish.io/how-newton-would-have-built-chatgpt-the-mathematical-physics-of-attention-db3b7529916f?source=rss-fe39f9032e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/db3b7529916f</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Raghav Sharma]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 07:37:04 GMT</pubDate>
            <atom:updated>2025-06-14T07:37:04.226Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What if Sir Isaac Newton had to invent transformers? He’d probably start with F=ma and end up with something remarkably similar to modern attention mechanisms.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ScqY03cTd02J3G0GX_yeg.png" /><figcaption>Image by Author</figcaption></figure><h3>The Apple That Started It All: From Gravity to Information</h3><p>Picture Newton under his apple tree in 1666. As the apple falls, he realizes the same force pulling fruit earthward keeps the moon orbiting Earth. But what if Newton had lived to see ChatGPT? He might have had another revelation: the same mathematical principles governing celestial mechanics could explain how machines understand language.</p><p>The key insight is this: just as Newton showed that complex planetary motion emerges from simple force laws, transformer attention emerges from simple mathematical operations that mirror classical physics.</p><p>This piece reimagines attention through the lens of Newtonian physics — not as a metaphor, but as a structural parallel grounded in math.</p><h3>What Is Attention in Transformers?</h3><p><strong>Attention</strong> is the core mechanism that allows transformer models like ChatGPT to process and generate human-like text. It’s a method by which the model decides which parts of the input are most relevant to focus on at each step of processing. Instead of processing words in a strict left-to-right order like older sequence models (e.g., RNNs), attention gives the model the flexibility to dynamically “look at” any other word in the sentence — regardless of position — based on its learned relevance.</p><h4>Basic Idea</h4><p>At its core, attention computes <strong>weighted combinations</strong> of input data. Each word (or token) in the input sends and receives “signals” from other tokens to decide how much it should focus on them. These signals are computed via three components for each token:</p><ul><li><strong>Query (Q)</strong>: What the word is <em>looking for</em></li><li><strong>Key (K)</strong>: What the other words <em>offer</em></li><li><strong>Value (V)</strong>: What information the other words <em>contain</em></li></ul><p>The attention score between word A and word B is calculated as a dot product between A’s query and B’s key. This score determines how much influence B’s value will have on A’s updated representation.</p><h4>The Attention Formula</h4><p>The scaled dot-product attention is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*OhOFuaiOGVMzF71DzwIteg.png" /><figcaption>Scaled Dot-Product Attention</figcaption></figure><h4>Why It Matters</h4><p>This mechanism allows the model to:</p><ul><li>Capture long-range dependencies in text</li><li>Handle variable-length inputs efficiently</li><li>Compute in parallel (unlike RNNs which are sequential)</li></ul><p>In practice, <strong>multi-head attention</strong> is used: multiple attention mechanisms run in parallel with different learned projections, and their outputs are concatenated. This allows the model to capture different types of relationships at once (syntax, semantics, etc.).</p><h3>The Paper That Started It All</h3><p>The original 2017 paper that introduced this mechanism is titled:</p><p><strong>“Attention Is All You Need”</strong><br>By Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, and Illia Polosukhin.</p><p>You can read the full paper here (PDF):<br><a href="https://arxiv.org/pdf/1706.03762.pdf">https://arxiv.org/pdf/1706.03762.pdf</a></p><p>This paper introduced the <strong>transformer architecture</strong>, which entirely replaced recurrence and convolution with attention-based operations, and laid the foundation for models like BERT, GPT, and eventually ChatGPT.</p><h3>The Universal Law of Semantic Gravitation</h3><p>Newton’s law of universal gravitation states that every particle attracts every other particle with a force proportional to their masses and inversely proportional to the square of the distance between them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*iGiU2zkb-gWzJSyew-Pdjw.png" /><figcaption>Gravitational force formula</figcaption></figure><p>Now imagine each word in a sentence as a massive body in semantic space. The “gravitational force” between words would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*MhCqPjIHCpB9gfJgJtB50w.png" /><figcaption>Semantic Force Formula (Analogy)</figcaption></figure><p>This is remarkably close to how transformers actually work. But instead of calculating distances in 3D space, we work in high-dimensional embedding space, and instead of the inverse square law, we use dot products for computational efficiency.</p><h3>Words as Vectors in Semantic Space</h3><p>In Newtonian mechanics, we represent position with vectors <strong>r</strong> = (x, y, z). Similarly, each word gets represented as a high-dimensional vector in embedding space. Think of these as coordinates that capture meaning:</p><pre>import numpy as np<br><br># Each word is a position vector in high-dimensional space<br># Dimensions represent abstract concepts like [physics_relatedness, time_concept, action, mass_concept]<br>word_embeddings = {<br>    &#39;newton&#39;: np.array([0.9, 0.2, 0.1, 0.3]),    <br>    &#39;apple&#39;: np.array([0.3, 0.1, 0.0, 0.4]),     <br>    &#39;falls&#39;: np.array([0.4, 0.1, 0.9, 0.2]),    <br>    &#39;tree&#39;: np.array([0.1, 0.3, 0.0, 0.6]),      <br>    &#39;quickly&#39;: np.array([0.2, 0.8, 0.7, 0.0])   <br>}</pre><p>The beauty is that words with similar meanings cluster together in this space, just like planets in a solar system naturally group by their orbital characteristics.</p><h3>The Three-Body Problem: Why We Need Q, K, and V</h3><p>Newton struggled with the three-body problem: how do you predict the motion of three interacting celestial bodies? It turns out this same challenge led to the transformer’s Q, K, V design.</p><p>Here’s the key insight: when word <strong>A</strong> wants to “pay attention” to word <strong>B</strong>, we need to consider three different aspects:</p><ol><li><strong>Query (Q)</strong>: What is word A looking for? (Like asking “what gravitational influences am I sensitive to?”)</li><li><strong>Key (K)</strong>: What does word B offer? (Like stating “here’s the gravitational field I generate”)</li><li><strong>Value (V)</strong>: What information does word B actually contain? (Like the actual mass and properties that get transferred)</li></ol><p>Think of it this way: if “Newton” (the query) is looking for physics-related concepts, and “apple” has a key that says “I’m somewhat physics-related,” then the value of “apple” (its actual meaning about fruit, falling, etc.) gets transferred to “Newton” with a strength proportional to their compatibility.</p><pre>def create_qkv_from_embeddings(embeddings, d_model=4):<br>    &quot;&quot;&quot;<br>    Transform raw embeddings into Q, K, V vectors<br>    This is like transforming position coordinates into different reference frames<br>    &quot;&quot;&quot;<br>    # These transformation matrices are learned during training<br>    # Think of them as coordinate transformation matrices in physics<br>    np.random.seed(42)<br>    W_q = np.random.randn(d_model, d_model) * 0.1  # Query transformation<br>    W_k = np.random.randn(d_model, d_model) * 0.1  # Key transformation<br>    W_v = np.random.randn(d_model, d_model) * 0.1  # Value transformation<br>    <br>    words = list(embeddings.keys())<br>    X = np.array([embeddings[word] for word in words])<br>    <br>    # Apply transformations (like changing coordinate systems)<br>    Q = X @ W_q  # What each word seeks<br>    K = X @ W_k  # What each word broadcasts  <br>    V = X @ W_v  # What each word contains<br>    <br>    return Q, K, V, words<br><br>Q, K, V, words = create_qkv_from_embeddings(word_embeddings)<br>print(&quot;Words:&quot;, words)<br>print(&quot;Query matrix shape:&quot;, Q.shape)<br>print(&quot;Each word&#39;s query vector represents what it&#39;s &#39;looking for&#39;&quot;)</pre><p>Words: [‘newton’, ‘apple’, ‘falls’, ‘tree’, ‘quickly’]</p><p>Query matrix shape: (5, 4)</p><p>Each word’s query vector represents what it’s ‘looking for’</p><h3>The Dot Product as Gravitational Work</h3><p>In physics, work is defined as <strong>W = F·d</strong>, the dot product of force and displacement vectors. The attention mechanism uses this exact same mathematical operation.</p><p>When we calculate <strong>Q_i · K_j</strong> (the dot product between a query and a key), we’re essentially calculating how much “work” key j can do on query i. A large positive dot product means they’re aligned and will interact strongly, just like a force in the same direction as motion does maximum work.</p><pre>def calculate_attention_forces(Q, K, V):<br>    &quot;&quot;&quot;<br>    Calculate attention using the physics of dot products<br>    &quot;&quot;&quot;<br>    # Step 1: Calculate &quot;work&quot; - how much each key affects each query<br>    # This is exactly like W =F·d in mechanics<br>    force_matrix = Q @ K.T<br>    <br>    print(&quot;Force Matrix (Q·K^T):&quot;)<br>    print(&quot;Rows = queries (what each word seeks)&quot;)<br>    print(&quot;Columns = keys (what each word offers)&quot;)<br>    <br>    # Show the actual values with word labels<br>    for i, query_word in enumerate(words):<br>        for j, key_word in enumerate(words):<br>            force = force_matrix[i, j]<br>            print(f&quot;{query_word} seeking from {key_word}: {force:.3f}&quot;)<br>        print()<br>    <br>    return force_matrix<br><br>force_matrix = calculate_attention_forces(Q, K, V)</pre><pre>Force Matrix (Q·K^T):<br>Rows = queries (what each word seeks)<br>Columns = keys (what each word offers)<br><br>newton seeking from newton: -0.021<br>newton seeking from apple: -0.001<br>newton seeking from falls: -0.010<br>newton seeking from tree: 0.007<br>newton seeking from quickly: -0.016<br><br>apple seeking from newton: -0.002<br>apple seeking from apple: 0.002<br>apple seeking from falls: 0.002<br>apple seeking from tree: 0.005<br>apple seeking from quickly: 0.001<br><br>falls seeking from newton: 0.004<br>falls seeking from apple: 0.003<br>falls seeking from falls: 0.007<br>falls seeking from tree: 0.002<br>falls seeking from quickly: 0.000<br><br>tree seeking from newton: 0.002<br>tree seeking from apple: 0.003<br>tree seeking from falls: 0.005<br>tree seeking from tree: 0.005<br>tree seeking from quickly: 0.005<br><br>quickly seeking from newton: -0.014<br>quickly seeking from apple: -0.003<br>quickly seeking from falls: -0.012<br>quickly seeking from tree: -0.002<br>quickly seeking from quickly: -0.019</pre><p>In simpler terms, this numerical value represents the amount of <strong>relevance</strong> each words finds with the other respective one.</p><h3>The Softmax: Boltzmann Distribution in Disguise</h3><p>Here’s where it gets really interesting. The softmax function used in attention is actually the Boltzmann distribution from statistical mechanics!</p><p>In physics, when particles are in thermal equilibrium, the probability of finding a particle in a state with energy E is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*fHYh8uZwnbaAxeRD0ui8NA.png" /><figcaption><strong>Boltzmann Distribution</strong> or <strong>Gibbs-Boltzmann distribution</strong></figcaption></figure><p>Where k is Boltzmann’s constant, T is temperature, and Z is the partition function.</p><p>The softmax function is identical:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*EIW8BWf8gE1Gl6abO6_5_A.png" /><figcaption>Softmax function</figcaption></figure><p>This means attention weights represent the equilibrium distribution of “semantic energy” in the system!</p><pre>def softmax_as_boltzmann(force_matrix, temperature=1.0):<br>    &quot;&quot;&quot;<br>    Softmax is actually the Boltzmann distribution from statistical mechanics<br>    &quot;&quot;&quot;<br>    # Scale by temperature (like thermal energy kT)<br>    scaled_forces = force_matrix / np.sqrt(Q.shape[-1]) / temperature<br>    <br>    # Boltzmann distribution: P(i) = exp(-E_i/kT) / Z<br>    def softmax(x):<br>        # Subtract max for numerical stability (doesn&#39;t change relative probabilities)<br>        exp_x = np.exp(x - np.max(x, axis=-1, keepdims=True))<br>        return exp_x / np.sum(exp_x, axis=-1, keepdims=True)<br>    <br>    attention_weights = softmax(scaled_forces)<br>    <br>    print(&quot;Attention weights (Boltzmann probabilities):&quot;)<br>    for i, query_word in enumerate(words):<br>        print(f&quot;{query_word} pays attention to:&quot;)<br>        for j, key_word in enumerate(words):<br>            prob = attention_weights[i, j]<br>            print(f&quot;  {key_word}: {prob:.3f}&quot;)<br>        print()<br>    <br>    return attention_weights<br>attention_weights = softmax_as_boltzmann(force_matrix, temperature=0.8)</pre><pre>Attention weights (Boltzmann probabilities):<br><br>newton pays attention to:<br>  newton: 0.198<br>  apple: 0.201<br>  falls: 0.200<br>  tree: 0.202<br>  quickly: 0.199<br><br>apple pays attention to:<br>  newton: 0.200<br>  apple: 0.200<br>  falls: 0.200<br>  tree: 0.200<br>  quickly: 0.200<br><br>falls pays attention to:<br>  newton: 0.200<br>  apple: 0.200<br>  falls: 0.200<br>  tree: 0.200<br>  quickly: 0.200<br><br>tree pays attention to:<br>  newton: 0.200<br>  apple: 0.200<br>  falls: 0.200<br>  tree: 0.200<br>  quickly: 0.200<br><br>quickly pays attention to:<br>  newton: 0.200<br>  apple: 0.201<br>  falls: 0.200<br>  tree: 0.201<br>  quickly: 0.199</pre><p>Similar to previous results, the numerical values here represent the amount of <strong>attention</strong> each word provides to another respective one.</p><h3>Center of Mass: The Final Output</h3><p>The final step in attention is computing the weighted average of all value vectors. This is exactly the center of mass calculation from mechanics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*IhjLrp3wcxl04uZY7lcGpQ.png" /><figcaption>center of mass equation</figcaption></figure><p>In attention:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*xPogNBQlQeOLwjpvk9zOWA.png" /><figcaption>output equation</figcaption></figure><p>Each word’s final representation becomes the center of mass of all other words’ values, weighted by their attention probabilities.</p><pre>def compute_center_of_mass_output(attention_weights, V):<br>    &quot;&quot;&quot;<br>    Final attention output = center of mass calculation<br>    &quot;&quot;&quot;<br>    # This is exactly the center of mass formula from mechanics<br>    attention_output = attention_weights @ V<br>    <br>    print(&quot;Final attention output (center of mass):&quot;)<br>    for i, word in enumerate(words):<br>        print(f&quot;{word} final representation: {attention_output[i].round(3)}&quot;)<br>        <br>        # Show which words contributed most<br>        contributors = []<br>        for j, contributor in enumerate(words):<br>            weight = attention_weights[i, j]<br>            if weight &gt; 0.15:  # Only show significant contributors<br>                contributors.append(f&quot;{contributor}({weight:.2f})&quot;)<br>        <br>        print(f&quot;  Main influences: {&#39;, &#39;.join(contributors)}&quot;)<br>        print()<br>    <br>    return attention_output<br><br>final_output = compute_center_of_mass_output(attention_weights, V)</pre><pre>Final attention output (center of mass):<br><br>newton final representation: [-0.014 -0.115 -0.026 -0.019]<br>  Main influences: newton(0.20), apple(0.20), falls(0.20), tree(0.20), quickly(0.20)<br><br>apple final representation: [-0.014 -0.115 -0.026 -0.019]<br>  Main influences: newton(0.20), apple(0.20), falls(0.20), tree(0.20), quickly(0.20)<br><br>falls final representation: [-0.013 -0.115 -0.026 -0.019]<br>  Main influences: newton(0.20), apple(0.20), falls(0.20), tree(0.20), quickly(0.20)<br><br>tree final representation: [-0.013 -0.115 -0.026 -0.019]<br>  Main influences: newton(0.20), apple(0.20), falls(0.20), tree(0.20), quickly(0.20)<br><br>quickly final representation: [-0.014 -0.115 -0.026 -0.019]<br>  Main influences: newton(0.20), apple(0.20), falls(0.20), tree(0.20), quickly(0.20)The &quot;final representation&quot; for each word is its new, enriched meaning that now includes context absorbed from all the other words, much like finding the central point of influence (center of mass) from all its connections.</pre><p>The “final representation” for each word is its <strong>new, enriched meaning</strong> that now includes context absorbed from all the other words, much like finding the central point of influence (center of mass) from all its connections.</p><h3>Multiple Heads: Parallel Physics</h3><p>Newton wondered what would happen if the gravitational constant G had different values. Multi-head attention explores exactly this: what if we run multiple physics simulations with different parameters?</p><p>Each attention head is like a parallel universe with its own physics constants. One head might be sensitive to grammatical relationships (like electromagnetic force), another to semantic similarity (like gravitational force), and another to positional relationships (like nuclear force).</p><pre>def multi_head_as_parallel_physics(X, num_heads=3):<br>    &quot;&quot;&quot;<br>    Multi-head attention = multiple physics simulations running in parallel<br>    &quot;&quot;&quot;<br>    head_outputs = []<br>    <br>    for head in range(num_heads):<br>        print(f&quot;\n--- Physics Simulation {head + 1} ---&quot;)<br>        <br>        # Each head has different &quot;physics constants&quot;<br>        np.random.seed(42 + head)<br>        head_dim = X.shape[-1] // num_heads<br>        <br>        # Different transformation matrices = different physical laws<br>        W_q = np.random.randn(X.shape[-1], head_dim) * (0.1 + head * 0.03)<br>        W_k = np.random.randn(X.shape[-1], head_dim) * (0.1 + head * 0.03)<br>        W_v = np.random.randn(X.shape[-1], head_dim) * (0.1 + head * 0.03)<br>        <br>        # Run physics simulation in this universe<br>        Q_h = X @ W_q<br>        K_h = X @ W_k  <br>        V_h = X @ W_v<br>        <br>        # Different temperature for each universe<br>        temperature = 0.5 + head * 0.2<br>        force_h = Q_h @ K_h.T<br>        attention_h = softmax_as_boltzmann(force_h, temperature)<br>        output_h = attention_h @ V_h<br>        <br>        head_outputs.append(output_h)<br>        print(f&quot;Universe {head + 1} dominant attention pattern:&quot;)<br>        <br>        # Show the strongest connection in this universe<br>        max_idx = np.unravel_index(np.argmax(attention_h), attention_h.shape)<br>        print(f&quot;Strongest force: {words[max_idx[0]]} → {words[max_idx[1]]} ({attention_h[max_idx]:.3f})&quot;)<br>    <br>    # Combine all parallel universes (like measuring multiple physical phenomena)<br>    combined_output = np.concatenate(head_outputs, axis=-1)<br>    print(f&quot;\nCombined multi-universe output shape: {combined_output.shape}&quot;)<br>    <br>    return combined_output<br><br># Convert embeddings to matrix for multi-head processing<br>X = np.array([word_embeddings[word] for word in words])<br>multi_head_output = multi_head_as_parallel_physics(X, num_heads=2)</pre><pre>--- Physics Simulation 1 ---<br>Attention weights (Boltzmann probabilities):<br>newton pays attention to:<br>  newton: 0.200<br>  apple: 0.200<br>  falls: 0.200<br>  tree: 0.199<br>  quickly: 0.200<br><br>apple pays attention to:<br>  newton: 0.200<br>  apple: 0.200<br>  falls: 0.200<br>  tree: 0.199<br>  quickly: 0.200<br><br>falls pays attention to:<br>  newton: 0.200<br>  apple: 0.200<br>  falls: 0.200<br>  tree: 0.200<br>  quickly: 0.200<br><br>tree pays attention to:<br>  newton: 0.201<br>  apple: 0.201<br>  falls: 0.199<br>  tree: 0.199<br>  quickly: 0.200<br><br>quickly pays attention to:<br>  newton: 0.201<br>  apple: 0.201<br>  falls: 0.198<br>  tree: 0.200<br>  quickly: 0.199<br><br>Universe 1 dominant attention pattern:<br>Strongest force: quickly → newton (0.201)<br><br>--- Physics Simulation 2 ---<br>Attention weights (Boltzmann probabilities):<br>newton pays attention to:<br>  newton: 0.201<br>  apple: 0.200<br>  falls: 0.200<br>  tree: 0.200<br>  quickly: 0.199<br><br>apple pays attention to:<br>  newton: 0.201<br>  apple: 0.201<br>  falls: 0.199<br>  tree: 0.201<br>  quickly: 0.199<br><br>falls pays attention to:<br>  newton: 0.203<br>  apple: 0.201<br>  falls: 0.199<br>  tree: 0.200<br>  quickly: 0.197<br><br>tree pays attention to:<br>  newton: 0.200<br>  apple: 0.201<br>  falls: 0.198<br>  tree: 0.201<br>  quickly: 0.199<br><br>quickly pays attention to:<br>  newton: 0.201<br>  apple: 0.200<br>  falls: 0.200<br>  tree: 0.199<br>  quickly: 0.199<br><br>Universe 2 dominant attention pattern:<br>Strongest force: falls → newton (0.203)<br><br>Combined multi-universe output shape: (5, 4)</pre><p>This shows the model is using <strong>multiple independent “perspectives”</strong> (like different ways of thinking) to analyze how words relate, but in this early stage, each perspective is still paying roughly equal attention to all words.</p><h3>Conservation Laws: Residual Connections</h3><p>Newton’s laws conserve energy and momentum. Transformers have their own conservation principle through residual connections: information can never be completely lost, only transformed.</p><pre>def apply_conservation_law(original_state, transformed_state):<br>    &quot;&quot;&quot;<br>    Residual connections implement conservation of information<br>    Like conservation of energy: initial + change = final<br>    &quot;&quot;&quot;<br>    print(&quot;Conservation Law in Action:&quot;)<br>    print(f&quot;Original state norm: {np.linalg.norm(original_state):.3f}&quot;)<br>    print(f&quot;Transformed state norm: {np.linalg.norm(transformed_state):.3f}&quot;)<br>    <br>    # Residual connection: maintain original information<br>    conserved_state = original_state + transformed_state[:, :original_state.shape[-1]]<br>    <br>    print(f&quot;Conserved state norm: {np.linalg.norm(conserved_state):.3f}&quot;)<br>    print(&quot;Information preserved through transformation!&quot;)<br>    <br>    return conserved_state<br><br>conserved_output = apply_conservation_law(X, multi_head_output)</pre><pre>Conservation Law in Action:<br>Original state norm: 1.965<br>Transformed state norm: 0.417<br>Conserved state norm: 1.990<br>Information preserved through transformation!</pre><p>Whilst I was drafting this part, I realized that this also connects directly with the information theory in mathematics. In information theory, we are indeed concerned primarily with quantifying, storing, and communicating information. This is like trying to copy a picture many times — each copy can lose a bit of quality (pixels, some minute details etc.) and similar can be said for when words with specific meanings attached to them are passed through neural networks.</p><p>The “Conservation Law in Action” (residual connections) acts as a <strong>safety net</strong>. It creates a direct “bypass lane” for the original information to flow alongside the newly transformed information. This means:</p><ul><li><strong>No Information Bottleneck:</strong> The model avoids a situation where important details are accidentally squeezed out or forgotten.</li><li><strong>Maximizing Usefulness:</strong> It ensures that even deep in the network, the model always has access to the <em>original, untainted information</em>, preventing “information degradation” and making sure the most useful features are preserved.</li></ul><p>So, it’s about making sure that the essential “signal” from your input isn’t diluted or destroyed, maintaining its information content throughout the complex processing. If you’re new to information theory and want to explore this connection further, here are some great resources:</p><ul><li><em>Information Theory, Inference and Learning Algorithms</em> by David MacKay (free full text): <a href="http://www.inference.org.uk/mackay/itila/book.html">www.inference.org.uk/mackay/itila/book.html</a></li><li>The “Information Theory” chapter in the Deep Learning Book by Ian Goodfellow et al.: <a href="http://www.deeplearningbook.org/">www.deeplearningbook.org</a></li><li>Visual intro to entropy by Khan Academy (YouTube): <a href="http://www.youtube.com/watch?v=2s3aJfRr9gE">www.youtube.com/watch?v=2s3aJfRr9gE</a></li></ul><h3>The Grand Unified Theory: From F=ma to Attention</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uu6mu52DkfJOV4kHpvtrww.png" /><figcaption>Image by Author</figcaption></figure><p>Let’s explicitly trace the mathematical parallels from Newton’s second law to the attention mechanism.</p><p><strong>Here’s how Physics Concepts relate to the Attention Mechanism:</strong></p><ul><li><strong>Newton’s Second Law (Force causes acceleration)</strong> is like the fundamental principle of interaction in attention.</li><li><strong>Gravitational Force (Particles attract based on mass and distance)</strong> is similar to how words “attract” or “influence” each other through <strong>Semantic Interaction</strong>. Here, a word’s “query” (what it seeks) interacts with another word’s “key” (what it offers) via a dot product to determine their raw “force.”</li><li><strong>Superposition (Total force is the sum of all individual forces)</strong> means all individual word-to-word “semantic forces” are combined.</li><li><strong>Thermal Equilibrium (Governed by the Boltzmann distribution)</strong> leads to <strong>Softmax Normalization</strong>, which converts raw forces into clear <strong>attention probabilities</strong> (how much focus each word gets).</li><li><strong>Center of Mass (Final position is the weighted average of all positions)</strong> becomes the <strong>Final Word Representation</strong>, where a word’s <strong>new, context-rich meaning</strong> is formed by a weighted average of the information from all other words.</li></ul><p>The underlying mathematical structure is strikingly similar. In essence, we’ve replaced:</p><ul><li><strong>Mass</strong> with the <strong>magnitude of an embedding</strong> (a word’s initial “substance”).</li><li><strong>Distance</strong> with <strong>Semantic Similarity</strong> (how close meanings are).</li><li><strong>Position</strong> with <strong>Information Content</strong> (the actual “value” a word carries).</li><li><strong>Temperature</strong> with a <strong>scaling parameter</strong> (how “sharp” or “spread out” the attention is).</li></ul><p>This framework allows the attention mechanism to model dynamic, context-aware relationships between words, much like forces govern interactions in the physical world.</p><h3>Why This Matters: Physics as the Foundation of Intelligence</h3><p>This isn’t just a cute analogy. The mathematical equivalence suggests something profound: the same principles that govern physical reality might also govern information processing and intelligence itself.</p><p>Newton showed that complex celestial motion emerges from simple force laws. Transformers show that complex language understanding emerges from the same mathematical principles applied to semantic space.</p><p>Perhaps intelligence, whether artificial or natural, follows universal mathematical laws just as fundamental as Newton’s equations. The attention mechanism might be as inevitable and universal as gravity itself.</p><p>When you interact with ChatGPT, you’re witnessing Newton’s laws in action, translated from the motion of planets to the flow of meaning through semantic space. The apple that fell on Newton’s head has become the foundation for artificial minds that can think, reason, and understand.</p><p>In Newton’s universe, every particle influences every other particle through gravitational force. In the transformer’s universe, every word influences every other word through attention. Both create order from chaos, meaning from mechanism, and understanding from the patient application of mathematical law.</p><p>So, maybe Newton would have published “Gravitational force is all you need”.</p><h3>What’s Next</h3><p>I write articles that bridge mathematics and physics with practical machine learning. My approach: take complex theoretical concepts and make them intuitive through code and visualization.</p><p><strong>Follow for more</strong>: medium.com/@sharmaraghav</p><p><strong>Written by Raghav Sharma</strong><br><em>Data Scientist with a background in physics, mathematics, and AI/ML</em><br>📧 <a href="/service/mailto:sharmaraghav644@gmail.com">sharmaraghav644@gmail.com</a><br>🔗 <a href="https://www.linkedin.com/in/raghav-sharma-b7a87a142/">LinkedIn</a> | <a href="https://raghav-sharma.com/">Portfolio</a> | <a href="https://github.com/sharmaraghav644">GitHub</a> | <a href="https://medium.com/@sharmaraghav644">Medium</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db3b7529916f" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/how-newton-would-have-built-chatgpt-the-mathematical-physics-of-attention-db3b7529916f">How Newton Would Have Built ChatGPT: The Mathematical Physics of Attention</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantum Mechanics for Data Scientists]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://ai.plainenglish.io/quantum-mechanics-for-data-scientists-8aa17956cc6a?source=rss-fe39f9032e4d------2"><img src="https://cdn-images-1.medium.com/max/1024/1*Lv76OyPb1iJ_769DXtiGzQ.png" width="1024"></a></p><p class="medium-feed-snippet">Quantum Computing Meets Machine Learning: Real Use Cases and Intuition</p><p class="medium-feed-link"><a href="https://ai.plainenglish.io/quantum-mechanics-for-data-scientists-8aa17956cc6a?source=rss-fe39f9032e4d------2">Continue reading on Artificial Intelligence in Plain English »</a></p></div>]]></description>
            <link>https://ai.plainenglish.io/quantum-mechanics-for-data-scientists-8aa17956cc6a?source=rss-fe39f9032e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aa17956cc6a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Raghav Sharma]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 02:58:39 GMT</pubDate>
            <atom:updated>2025-06-11T07:13:29.958Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The Physics of Neural Networks]]></title>
            <link>https://ai.plainenglish.io/the-physics-of-neural-networks-d6472957694f?source=rss-fe39f9032e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6472957694f</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Raghav Sharma]]></dc:creator>
            <pubDate>Sun, 25 May 2025 23:10:55 GMT</pubDate>
            <atom:updated>2025-06-11T07:57:37.343Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why your deep learning model is basically a particle physics simulation in disguise</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*egbLxfoMgiKpiWg3rZ615w.png" /></figure><p>A few years ago, I came across a quote: “<em>If you understand the secret of one thing, you will understand the secret of everything</em>.” I am not sure whether it is from Lao Tzu or Paulo Coelho, but the idea stayed with me. I kept returning to it and questioning it. Over time, I reached a more grounded conclusion. We probably cannot understand everything about everything. But we can start by observing the patterns and phenomena we see around us and use those to understand something in depth.</p><p>Today, that something is neural networks.</p><p>They are often treated as abstract mathematical tools, but they are also physical systems. The same equations that describe how planets move or how electrons flow can also explain how your transformer model learns to generate text. Maybe not poetry, but certainly something structured and meaningful.</p><p>And this is not just a metaphor. The mathematics is exactly the same. Let me show you how.</p><h3>What Are Neural Networks?</h3><p>Before we dive into the physics, let’s strip away the mystique. A neural network is fundamentally a mathematical function that takes inputs and produces outputs. Think of it as a black box that learns to map questions to answers like pixels to object labels, text to translations, moves to chess strategies.</p><p>But here’s what makes them special: they’re <strong>universal function approximators</strong>. Given enough neurons and the right training, they can learn to approximate any continuous function. The network consists of layers of interconnected nodes (neurons), each performing simple mathematical operations. The magic happens through two processes: <strong>forward propagation</strong> (making predictions) and <strong>backpropagation</strong> (learning from mistakes).</p><p>The “<strong>learning</strong>” part is where it gets interesting. The network has millions of adjustable parameters (<strong>weights and biases</strong>) that determine its behavior. Training means finding the right values for these parameters so the network produces correct outputs. This is typically done by showing the network thousands or millions of examples and gradually adjusting the parameters to minimize prediction errors.</p><p>Now, here’s where physics enters the picture. Those “adjustable parameters” and “minimizing errors” aren’t just computational concepts. They are describing a physical system in motion.</p><h3>Neural Networks Are Energy Landscapes</h3><p>Here’s the first mind-bending connection: every neural network is essentially a map of hills and valleys in mathematical space.</p><p>Imagine you’re looking at a view from above. Hills represent high error, which means bad predictions, and valleys represent low error, or good predictions. Your neural network’s job is to find the deepest valley. This landscape is defined by one equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*cDeStDyf0wu7ow6o5FVcFg.png" /><figcaption>Loss Function / Hamiltonian Energy</figcaption></figure><p>This isn’t just a “loss function”. It is the <strong>Hamiltonian energy</strong> from physics. <em>θ</em> represents every single weight and bias in your network (could be millions of them), and <em>E(θ)</em> tells you how much “energy” the system has at any configuration.</p><p>Now here’s where physics kicks in. In the real world, a ball always rolls downhill toward the lowest point. Neural networks do exactly the same thing through gradient descent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*iV-ApZD4wyXM27meIZm_rg.png" /><figcaption>Hamilton’s Equation of Motion</figcaption></figure><p>This is <strong>Hamilton’s equation</strong> — the fundamental law governing how particles move in physics. Your neural network is literally a particle (in millions of dimensions) sliding down an energy landscape. The negative sign means it always moves toward lower energy (better predictions).</p><p><strong>The connection</strong>: These two equations are partners. The first defines the landscape, the second describes how to navigate it. Just like a ball rolling downhill, your network naturally flows toward configurations that minimize error.</p><h3>Forward Propagation: Information as Force</h3><p>Now let’s see what happens when you actually feed data into your network. Each layer transforms the input according to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*RKp-_bwdmp71nQ3fXBQDAg.png" /><figcaption>Layer Activation Function</figcaption></figure><p>This innocent looking equation is actually describing wave propagation. Think of it like sound waves traveling through different materials such as air, water, or glass. Each material changes the wave’s properties.</p><p>In your network:</p><ul><li>The input data is like a wave</li><li>Each layer is like a different material the wave passes through</li><li>The weights <em>W^l</em> determine how much the “material” affects the wave</li><li>The bias <em>b^l</em> is like an external force pushing the wave</li><li>The activation function <em>σ</em> is like the material’s response to the wave</li></ul><p><strong>Why this matters</strong>: Information flowing through your network follows the same conservation laws as energy in physics. Nothing gets created or destroyed, only transformed. This is why techniques like skip connections (ResNet) work so well. They preserve information flow, just like conservation of energy.</p><h3>Backpropagation: Newton’s Third Law in Action</h3><p>Here’s where things get really elegant. When your network makes a wrong prediction, it needs to figure out which weight(s) to blame. This happens through backpropagation:</p><p>When your network makes a prediction error, that error creates a “force” at the output layer. This force propagates backward through the network according to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*3e-F_nOVB-Up-mJHVJeCWg.png" /><figcaption>Error Gradient Propagation Equation</figcaption></figure><p>This equation embodies <strong>Newton’s third law</strong>: for every action, there’s an equal and opposite reaction.</p><p><strong>Here’s how</strong>: During forward propagation, layer <em>l</em> pushed information forward to layer <em>l+1</em>. Now, during backpropagation, layer <em>l+1</em> pushes blame backward to layer <em>l</em> with equal force but opposite direction. That transpose symbol <em>(T)</em> is the mathematical way of saying “equal and opposite.”</p><p>The error signal <em>δ</em> is like a force that travels backward through your network, telling each weight exactly how much it contributed to the mistake.</p><p><strong>The deeper connection</strong>: This connects to the chain rule from calculus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*BKDf5tor4yXGvI2E3gEtjw.png" /><figcaption>Chain Rule / Principle of Virtual Work</figcaption></figure><p>In physics, this is called the <strong>principle of virtual work. </strong>If you make a tiny change to any part of a system, the total work is the sum of work done at each step in the chain. Same math, different context.</p><h3>Boltzmann: The Statistical Mechanics Connection</h3><p>Ludwig Boltzmann figured out how chaos at the microscopic level (molecules bouncing around randomly) creates order at the macroscopic level (the behavior of gases, liquids, solids).</p><p>Neural networks follow the same principle through the <strong>Boltzmann distribution</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*Pk2-8UaAnr3etoEprOygAw.png" /><figcaption>Boltzmann Distribution</figcaption></figure><p>This equation says: the probability of finding your system in state s depends on two things:</p><ol><li><strong>Energy E(s)</strong>: Lower energy states are more likely (your network prefers good solutions)</li><li><strong>Temperature T</strong>: High temperature means more randomness, low temperature means settling into the best solution</li></ol><p><strong>What this means for neural networks</strong>: During training, your network doesn’t just find one solution. It samples from many possible solutions. The “temperature” is controlled by your learning rate and batch size. Start hot (high learning rate) to explore many possibilities, then cool down (reduce learning rate) to settle on the best one.</p><p>This is why learning rate scheduling works. It is literally simulated annealing, a technique borrowed directly from physics.</p><p>The Boltzmann distribution leads us to something beautiful. The <strong>partition function</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*IugDJqwEjxa9-az2X5LEjQ.png" /><figcaption>Partition Function</figcaption></figure><p>This Z stands for the total sum over all possible configurations your network can take, with each one weighted by its probability. In physics, this same equation appears in quantum mechanics as the path integral, where you calculate the total by summing over every path a particle might follow.</p><p><strong>The profound implication</strong>: Your neural network navigates a space of possible configurations much like quantum particles. In both cases, the behavior is governed by summing over all possible paths, each weighted by its likelihood.</p><h3>Phase Transitions in Neural Networks</h3><p>Neural networks undergo phase transitions during training, just like water turning into ice.</p><p>You can detect these transitions by watching the <strong>order parameter</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*C8AbhnMaiz68y_gqo19HTw.png" /><figcaption>Order Parameter</figcaption></figure><p>This measures how much your gradients are fluctuating. When this number suddenly spikes, your network is likely about to go through a qualitative change, such as shifting from underfitting to fitting, or from fitting to overfitting.</p><p><strong>What this shows</strong> is that these transitions occur at critical points that are universal. They depend only on the fundamental structure of your problem and not on the specific details of your architecture. This is why scaling laws remain consistent across different model sizes.</p><h3>Why This All Connects</h3><p>Each equation builds on the previous ones:</p><ol><li><strong>Energy landscape</strong> (Hamiltonian) defines the problem space</li><li><strong>Motion equation</strong> (Hamilton’s) describes how to navigate that space</li><li><strong>Forward propagation</strong> shows how information flows like waves</li><li><strong>Backpropagation</strong> shows how error flows back like forces</li><li><strong>Boltzmann statistics</strong> explains why randomness helps learning</li><li><strong>Partition function</strong> connects to quantum mechanics</li><li><strong>Order parameter</strong> detects when fundamental changes occur</li></ol><p>The beautiful thing is that all of these are different aspects of the same underlying physics. Your neural network is not just inspired by physical systems; it is a physical system, operating under the same mathematical laws that govern everything from atoms to galaxies.</p><h3>Why This Matters for Everyone</h3><p>Understanding neural networks as physical systems isn’t just intellectually cool — it has practical implications:</p><p><strong>For AI developers</strong>: Physical intuition suggests new architectures and training methods. Conservation laws tell you what information to preserve. Thermodynamics tells you the fundamental limits of learning efficiency.</p><p><strong>For everyone else</strong>: This perspective helps us understand AI’s limitations. Just as you can’t build a perpetual motion machine that violates thermodynamics, you can’t build an AI that violates the fundamental constraints of information theory and statistical mechanics.</p><p>The universe computes. Every physical process is a form of computation, and every computation must follow physical law. Neural networks are not only inspired by biology; they are also bound by the same physics that governs everything else in existence.</p><p>That realization is both humbling and profound. Your smartphone running ChatGPT is performing the same type of calculations that dictate how stars take shape, how crystals grow, and how life emerges from disorder.</p><p>Maybe we do not need to understand everything. Maybe understanding how a network learns, how information moves, reacts, and finds balance, is enough to catch a glimpse of how the universe learns as well.</p><h3>What’s Next?</h3><p>I write articles that bridge mathematics and physics with practical machine learning. My approach: take complex theoretical concepts and make them intuitive through code and visualization.</p><p>In the next article, “<strong>Convex vs Non-Convex: Why Some Problems Are Easy and Others Break AI Models</strong>,” I explore why some problems yield to optimization easily, while others cause AI systems to struggle, fail, or get stuck entirely.</p><p><strong>Follow for more</strong>: medium.com/@sharmaraghav</p><p><strong>Written by Raghav Sharma</strong><br><em>Data Scientist with a background in physics, mathematics, and AI/ML</em><br>📧 <a href="/service/mailto:sharmaraghav644@gmail.com">sharmaraghav644@gmail.com</a><br>🔗 <a href="https://www.linkedin.com/in/raghav-sharma-b7a87a142/">LinkedIn</a> | <a href="https://raghav-sharma.com/">Portfolio</a> | <a href="https://github.com/sharmaraghav644">GitHub</a> | <a href="https://medium.com/@sharmaraghav644">Medium</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6472957694f" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/the-physics-of-neural-networks-d6472957694f">The Physics of Neural Networks</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Algebra For Machine Learning — Explained Visually]]></title>
            <link>https://ai.plainenglish.io/linear-algebra-for-machine-learning-explained-visually-54a5c6a7be85?source=rss-fe39f9032e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/54a5c6a7be85</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Raghav Sharma]]></dc:creator>
            <pubDate>Thu, 22 May 2025 02:42:15 GMT</pubDate>
            <atom:updated>2025-06-11T07:58:02.684Z</atom:updated>
            <content:encoded><![CDATA[<h3>Linear Algebra For Machine Learning — Explained Visually</h3><p>Understanding the math behind SVD, PCA, and eigenvectors with intuition and code.</p><p>Galileo once said that <em>mathematics is the language of the universe</em>. True. But what about the different frameworks <strong>within</strong> the universe? Shouldn’t mathematics be able to describe them too? The answer is yes — or at least, we <strong>think</strong> it’s yes. But honestly, who knows?</p><p>In machine learning, <strong>linear algebra</strong> is that language. It’s the scaffolding behind high-dimensional data, embeddings, PCA, and even neural networks. But let’s be real, it can feel abstract, distant, even unnecessary especially when the code still runs without understanding a single eigenvector.</p><p>Which brings us to the real question:<br> <strong>Why, in this day and age, should we care about linear algebra when training models?</strong></p><p>Today, an LLM can build end-to-end pipelines without requiring you to understand what’s under the hood. And it works right up until you need something more: customization, scalability, real integration with your system. Then it breaks. And what do we do?</p><p>We ask the same LLM to write a <strong>decorator function</strong> to log where our function is failing.</p><p>To debug code that we didn’t really understand in the first place. I call this <em>vibe decoding</em> and it’s easily 10x more painful than the joy we get from <em>vibe coding</em>.</p><p><strong>Ironical, isn’t it?</strong></p><h3>🚩 Why Does Linear Algebra Even Matter?</h3><p>In machine learning, everything is a number. Text, images, audio are all transformed into arrays of numbers. We work with <strong>vectors</strong> (like a single row of data) and <strong>matrices</strong> (like datasets or transformations) every day, often without realizing it.</p><p>Here are just a few examples:</p><ul><li><strong>Recommendation systems</strong> use SVD to reduce huge user-item matrices.</li><li><strong>PCA</strong> is used to compress high-dimensional data before training models.</li><li><strong>Neural networks</strong> use matrix multiplication to compute outputs.</li><li><strong>Computer vision</strong> models handle image data as large 3D matrices.</li></ul><p>So understanding <em>how</em> linear algebra manipulates and transforms data is essential to improving your models and even debugging them when things go wrong.</p><p>Let’s begin with a concept you already know — vectors and build from there.</p><h3>🧭 Vectors and Matrices: The Language of Data</h3><p>Think of a vector as a list of numbers: [4, 3]. If we plot this in 2D space, it’s just an arrow pointing to a location. But there’s more in ML, a vector often represents an observation or a feature embedding.</p><p>Now, what is a matrix?</p><p>A matrix isn’t just a table of numbers. It’s more powerful than that. In linear algebra, a matrix is a transformation that acts on vectors. It can rotate, scale, flip, or squash them.</p><p>Let’s see this visually by creating a simple transformation and watching how it moves our vector:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br>A = np.array([[2, 1],<br>              [1, 3]])<br>v = np.array([2, 1])<br>transformed_v = A @ v<br>plt.quiver(0, 0, v[0], v[1], angles=&#39;xy&#39;, scale_units=&#39;xy&#39;, scale=1, color=&#39;blue&#39;, label=&#39;Original v&#39;)<br>plt.quiver(0, 0, transformed_v[0], transformed_v[1], angles=&#39;xy&#39;, scale_units=&#39;xy&#39;, scale=1, color=&#39;red&#39;, label=&#39;A * v&#39;)<br>plt.xlim(-1, 8)<br>plt.ylim(-1, 8)<br>plt.grid()<br>plt.legend()<br>plt.title(&quot;Matrix as a Transformation&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*OrncWiqZY38JxIo6OyIf3Q.png" /><figcaption>Image by Author</figcaption></figure><p>This visualization shows how multiplying a vector by a matrix can literally move it somewhere else in space. The blue vector [2, 1] is your original data. The red vector [5, 5] is the transformed data which might represent a projection, rotation, or feature extraction in ML.</p><p>Notice how the matrix A didn’t just scale the vector, it also changed its direction. This is the power of linear transformations.</p><h3>🔍 Eigenvectors and Eigenvalues — The Anchors of Transformation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWUqx8t0mFutEEiauq794w.png" /><figcaption>Image by Author</figcaption></figure><p>Here’s the key question: Are there vectors that don’t change direction when we apply a matrix transformation?</p><p>Yes and they’re called <strong>eigenvectors</strong>.</p><p>Eigenvectors are special because even after a transformation, they stay pointing in the same direction. They may be <strong>stretched</strong> or <strong>compressed</strong>, but they don’t rotate.</p><p>Think of eigenvectors as the “<strong>true axes</strong>” of a transformation.</p><p>They come with an eigenvalue, which tells you how much that eigenvector is stretched.</p><h3>🔬 Why Should You Care?</h3><p>Let’s see eigenvectors in action. Remember our transformation matrix from earlier? Let’s find its eigenvectors:</p><p>Here’s how you’d compute them:</p><pre>A = np.array([[2, 1],<br>              [1, 3]])<br><br>eigvals, eigvecs = np.linalg.eig(A)<br>print(&quot;Eigenvalues:&quot;, eigvals)<br>print(&quot;Eigenvectors:\n&quot;, eigvecs)</pre><p>Eigenvalues: [1.38196601 3.61803399]</p><p>Eigenvectors: [[-0.85065081 -0.52573111] [ 0.52573111 -0.85065081]]</p><p>What does this tell us? The eigenvector [-0.85, 0.53] gets stretched by a factor of 1.38 when we apply matrix A. The eigenvector [-0.53, -0.85] gets stretched by 3.62. These are the &quot;natural directions&quot; this transformation prefers.</p><p><strong>This concept is everywhere in ML:</strong></p><ul><li><strong>PCA</strong> uses eigenvectors of covariance matrices to find directions of maximum variance</li><li><strong>PageRank</strong> finds the dominant eigenvector of web link matrices</li><li><strong>Markov chains</strong> use eigenvectors to find steady states</li><li><strong>Neural networks</strong> leverage Eigen decomposition for optimization and stability</li></ul><p>Understanding eigenvectors means understanding the fundamental structure hidden in your data transformations.</p><h3>📉 Principal Component Analysis (PCA) — Dimensionality Reduction with Style</h3><p>Now let’s see eigenvectors do their magic in one of the most common ML applications.</p><p>Imagine your data exists in 50 dimensions, but most of the variance is really happening along just 2 or 3 directions. That’s where PCA comes in.</p><p>PCA finds the principal components which are the directions (eigenvectors) where variance is highest and projects your data onto them. Here’s the key insight: <strong>the principal components ARE the eigenvectors of your data’s covariance matrix</strong>.</p><p>This allows you to:</p><ul><li>Visualize high-dimensional data</li><li>Reduce noise and redundancy</li><li>Train models faster with less overfitting</li></ul><p>Let’s see this with the classic Iris dataset. We’ll compress 4 flower measurements into 2 dimensions:</p><h3>Let’s do it with real code:</h3><pre>from sklearn.decomposition import PCA<br>from sklearn.datasets import load_iris<br>import matplotlib.pyplot as plt<br><br>data = load_iris()<br>X = data.data<br>y = data.target<br>pca = PCA(n_components=2)<br>X_pca = pca.fit_transform(X)<br>plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y)<br>plt.title(&quot;Iris Dataset After PCA&quot;)<br>plt.xlabel(&quot;PC1&quot;)<br>plt.ylabel(&quot;PC2&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*yMWcw2JblhN3R093FHtXxw.png" /><figcaption>Image by Author</figcaption></figure><h3>🧪 What’s going on in that PCA plot?</h3><ul><li>You have <strong>150 flowers</strong>, from <strong>3 species</strong>.</li><li>Each flower has 4 measurements: petal length, petal width, sepal length, sepal width.</li><li>These 4D points are squished into 2D using <strong>PCA</strong>, so we can <strong>see</strong> them.</li></ul><p>Now, in this scatter plot:</p><ul><li>Each point = one flower</li><li>Each color = the actual species it belongs to</li><li>Position = how the PCA compressed all 4 features into 2 axes (PC1 and PC2)</li></ul><p>🎯 What do the colors mean?</p><ul><li>🟣 <strong>Purple</strong> = Setosa (clearly separates out)</li><li>🟡 <strong>Yellow</strong> = Versicolor (somewhat overlaps)</li><li>🟢 <strong>Green</strong> = Virginica (similar to Versicolor)</li></ul><p>The clear separation tells us something profound: <strong>the eigenvectors found by PCA revealed hidden structure in the data</strong>. What seemed like 4 separate measurements actually contained patterns that naturally separate the species.</p><p>You just took 4D data and squeezed it down to 2D, preserving as much variance as possible. This is eigenvectors in action.</p><h3>📦 Singular Value Decomposition (SVD): The Swiss Army Knife</h3><p>Here’s where things get interesting. What if your data matrix isn’t square? What if you have 1000 users and 10000 movies in a recommendation system? Eigen decomposition only works on square matrices, but SVD works on any matrix.</p><p><strong>SVD is like eigenvectors’ more versatile cousin.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*6jMvAKnF4Z-jo1q-zYVq0g.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*T2V2JWb8GgqBqj1zrSajmA.png" /></figure><p>SVD is used in:</p><ul><li>Recommender systems (e.g., Netflix matrix factorization)</li><li>Latent Semantic Analysis (text embeddings)</li><li>Image compression (keeping top singular values)</li></ul><pre>U, S, VT = np.linalg.svd(A)<br>print(&quot;Singular values:&quot;, S)</pre><p>Singular values: [3.61803399 1.38196601]</p><p>Notice something? These singular values are exactly the eigenvalues we computed earlier! That’s because for symmetric matrices, SVD and Eigen decomposition are closely related.</p><h3>🎯 Why SVD Matters in ML</h3><p><strong>SVD is used everywhere:</strong></p><ul><li><strong>Recommender systems</strong>: Netflix uses SVD to find latent factors connecting users and movies</li><li><strong>Latent Semantic Analysis</strong>: Finding hidden topics in text by decomposing word-document matrices</li><li><strong>Image compression</strong>: Keep only the top singular values to compress images with minimal quality loss</li></ul><p>Want to compress an image? Keep only the top 50 singular values. You’ll retain most of the structure and lose a lot of noise.</p><p>The beauty of SVD is that it generalizes the “find important directions” concept to any data matrix, not just square ones.</p><h3>🎯 Real-World Examples: Connecting the Dots</h3><p>Now you can see how these concepts flow together in practice:</p><p><strong>Concept: Eigenvectors</strong></p><ul><li>ML Use Case: PCA (eigenvectors of covariance matrices), Spectral clustering, PageRank algorithm</li></ul><p><strong>Concept: SVD</strong></p><ul><li>ML Use Case: Collaborative filtering (Netflix recommendations), Latent Semantic Analysis (text similarity), Image compression</li></ul><p><strong>Concept: Matrix transformations</strong></p><ul><li>ML Use Case: Neural network layers (each layer is a matrix transformation), Attention mechanisms in transformers</li></ul><p><strong>Concept: Projections</strong></p><ul><li>ML Use Case: Dimensionality reduction, Feature selection, Data visualization</li></ul><p>Each technique is finding structure in your data by understanding how transformations act on it.</p><h3>✅ Wrapping Up</h3><p>Linear algebra isn’t just math homework. It’s the lens through which machine learning sees the world.</p><p>You now know that:</p><ul><li>Matrices transform vectors, and understanding these transformations reveals data structure</li><li>Eigenvectors and eigenvalues reveal fundamental directions where transformations “prefer” to act</li><li>PCA uses eigenvectors to find the most informative directions in your data</li><li>SVD generalizes this concept to work with any data matrix, not just square ones</li></ul><p>The next time you see PCA compressing data, or SVD powering a recommendation system, you’ll understand what’s really happening: <strong>mathematics finding the hidden structure in chaos</strong>.</p><p>Want to get better at ML? Don’t just memorize but also visualize. Internalize how these transformations act on data. Then use them to your advantage.</p><h3>Try This Yourself</h3><p>Ready to put this into practice? Here’s your homework:</p><ol><li><strong>Run PCA on your own dataset</strong> — Start with something simple (like the Boston housing data) and see which features contribute most to the first principal component.</li><li><strong>Visualize eigenvector transformations</strong> — Take the matrix A from this article and plot how it transforms a grid of vectors.</li><li><strong>Try SVD image compression</strong> — Load an image, apply SVD, and reconstruct it using only the top 50 singular values. You’ll be amazed by how much structure you can preserve.</li><li><strong>Explore the math-physics connection</strong> — Linear algebra appears everywhere from quantum mechanics to optimization landscapes.</li></ol><h3>What’s Next?</h3><p>I write articles that bridge mathematics and physics with practical machine learning. My approach: take complex theoretical concepts and make them intuitive through code and visualization.</p><p>The next article <strong>“The Physics of Neural Networks: Energy Landscapes and Boltzmann Machines”</strong> explores how concepts from statistical physics — energy functions, phase transitions, and thermodynamic equilibrium — provide deep insights into how neural networks learn and optimize.</p><p><strong>Follow for more</strong>: medium.com/@sharmaraghav</p><p><strong>Written by Raghav Sharma</strong><br> <em>Data Scientist with a background in physics, mathematics, and AI/ML</em><br> 📧 <a href="/service/mailto:sharmaraghav644@gmail.com">sharmaraghav644@gmail.com</a><br> 🔗 <a href="https://www.linkedin.com/in/raghav-sharma-b7a87a142/">LinkedIn</a> | <a href="https://raghav-sharma.com/">Portfolio</a> | <a href="https://github.com/sharmaraghav644">GitHub</a> | <a href="https://medium.com/@sharmaraghav644">Medium</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54a5c6a7be85" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/linear-algebra-for-machine-learning-explained-visually-54a5c6a7be85">Linear Algebra For Machine Learning — Explained Visually</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Cost Savings: How Mathematical Optimization Transforms AI Deployments]]></title>
            <link>https://medium.com/@sharmaraghav644/unlocking-cost-savings-how-mathematical-optimization-transforms-ai-deployments-dc855abfa511?source=rss-fe39f9032e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc855abfa511</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Raghav Sharma]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 23:13:49 GMT</pubDate>
            <atom:updated>2025-04-29T23:13:49.153Z</atom:updated>
            <content:encoded><![CDATA[<h4>Practical Strategies to Slash AWS Bills and Improve AI Efficiency</h4><h3>Introduction</h3><p>AI deployments often entail substantial costs, including computational expenses, cloud service fees, and ongoing model maintenance. As the demand for AI applications grows, businesses seek effective strategies to <strong>optimize</strong> <strong>resources</strong> without <strong>compromising accuracy</strong> or <strong>performance</strong>. <strong>Mathematical optimization</strong> is instrumental in reducing deployment costs by enhancing efficiency in model selection, training, and resource utilization.</p><p>Deploying AI is expensive and requires a lot of effort, but the results aren’t always guaranteed. Let’s explore how to make it worthwhile before the finance team takes a look at the bill and, in true <strong>Chandler</strong> style, asks, ‘<strong><em>Could you BE any more expensive</em></strong>?’.</p><h3>Problem Overview</h3><p>AI models often present businesses with several challenges:</p><ul><li><strong>Expensive Cloud Costs</strong>: Cloud services like AWS, Google Cloud, and Azure charge based on compute time, storage, and bandwidth. These costs can quickly spiral out of control when using resource-hungry models like GPT-3 or large-scale convolutional neural networks (CNNs). Unoptimized AI workloads can lead to significant resource inefficiencies. Microsoft’s research indicates that optimizing resource allocation can substantially reduce computational waste in cloud environments.</li><li><strong>Inefficient Models</strong>: Using models that are too complex for the problem at hand results in wasted computational resources. Businesses often rely on heavyweight models without considering if smaller alternatives could offer the same performance. Facebook’s engineering team developed a matrix factorization-based collaborative filtering system capable of efficiently handling massive datasets, thereby reducing computational costs while maintaining real-time recommendation performance.</li><li><strong>Overfitting</strong>: AI models that overfit to training data may require constant re-training, leading to unnecessary resource usage. This not only extends training time but also increases costs associated with cloud compute and storage. Zillow employs Bayesian statistical methods to enhance their data science methodologies, particularly in measuring business outcomes.</li><li><strong>Wasted Resources</strong>: Poorly optimized data pipelines can result in redundant computations, such as repeatedly processing the same data across different stages of the machine learning lifecycle, which leads to inefficiencies and inflated costs. Uber’s Michelangelo platform enables efficient feature preprocessing and scalable training architecture, contributing to reduced training overhead and inference time.</li><li><strong>Suboptimal Resource Allocation</strong>: Without mathematical optimization of infrastructure resources, businesses often over-provision to ensure performance, leading to idle capacity and wasted spend. Google developed machine learning methods to discover new optimizers for training deep neural networks, leading to faster convergence and reduced training time.</li></ul><p>For instance, training a complex model like <strong>BERT</strong> can cost upwards of <strong>$1000 per day</strong> in cloud resources due to its size and the time required for fine-tuning. These kinds of costs are unsustainable for most businesses. However, companies implementing mathematical optimization techniques have demonstrated the ability to achieve comparable performance with 30–70% lower cloud costs across various AI applications.The Role of Mathematical Optimization</p><p>Mathematical optimization seeks to find the best possible solution to a problem by adjusting variables subject to constraints. In the context of AI, optimization techniques enhance both <strong>algorithmic performance</strong> and <strong>resource utilization</strong>, leading to significant cost reductions. Key optimization methods include:</p><ol><li><strong>Linear Programming (LP)</strong>: LP is used to optimize decision variables under constraints. In AI, LP can optimize resource allocation, ensuring computational tasks are completed with minimal cost.</li><li><strong>Convex Optimization</strong>: This method is particularly useful for minimizing loss functions in machine learning algorithms. It ensures that model parameters are optimized in a way that balances performance with resource constraints.</li><li><strong>Gradient Descent</strong>: An iterative method to minimize error by adjusting model parameters. By optimizing the learning rate and convergence criteria, businesses can reduce the number of iterations required for training, cutting down on compute costs.</li><li><strong>Mixed Integer Programming (MIP)</strong>: A powerful optimization technique for problems with both continuous and discrete variables. MIP is particularly valuable for resource allocation and scheduling problems in AI infrastructure.</li><li><strong>Bayesian Optimization</strong>: A probabilistic approach for optimizing black-box functions, especially useful for hyperparameter tuning.</li></ol><p>These mathematical optimization techniques don’t just improve model performance — they directly translate to substantial cloud cost savings by reducing computation time, memory usage, and storage requirements. Companies implementing these approaches typically see 20–50% reductions in their AI infrastructure costs while maintaining or improving model accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IciSRn-0WGv6hcV_Wha-qg.png" /><figcaption>Image by author</figcaption></figure><h3>Practical Use Cases for Cost Reduction</h3><ol><li><strong>AI Model Selection</strong><br> Choosing the right model is critical for reducing AI deployment costs. For instance, replacing a large model like <strong>BERT</strong> with a smaller version like <strong>DistilBERT</strong> can lead to a <strong>40% reduction in inference time</strong> and <strong>30% fewer computational resources</strong> while maintaining 95% of the performance for NLP tasks.</li><li><strong>Mathematical Impact</strong>:<br> Let’s say we replace BERT (parameter count = 110 million) with DistilBERT (parameter count = 66 million). By using the smaller model, we reduce the memory and CPU usage significantly. For a model inference task that costs $0.10 per 1 million operations, this translates into a 30% savings per inference request.</li><li><strong>Hyperparameter Optimization</strong><br> Using optimization techniques like <strong>grid search</strong> and <strong>random search</strong>, businesses can fine-tune hyperparameters to reduce training time and hardware usage. <strong>Bayesian optimization</strong> (a probabilistic model-based approach) helps in minimizing the number of trials needed to achieve an optimal configuration.</li><li><strong>Mathematical Impact</strong>:<br> Assume a neural network’s training time is T=1000 hours. By applying optimized hyperparameters, the time can be reduced to T=600, yielding a <strong>40% reduction in computational cost</strong>.</li><li><strong>Data Selection and Feature Engineering</strong><br> Selecting only the most relevant data features or using <strong>feature selection algorithms</strong> (e.g., <strong>L1 regularization</strong> or <strong>recursive feature elimination</strong>) reduces unnecessary computation and improves training speed.</li><li><strong>Mathematical Impact</strong>:<br> If a dataset with 1000 features can be reduced to 200 features through optimization, the number of training steps reduces proportionally. For example, a training process that takes 100 CPU hours with 1000 features may be reduced to 60 CPU hours by reducing the dataset, a <strong>40% reduction</strong> in resource consumption.</li></ol><p>By applying these optimization techniques in real-world scenarios, businesses can see firsthand how mathematical optimization not only improves model performance but also directly contributes to significant reductions in both time and costs — ensuring that AI deployments are as efficient as they are effective.</p><h3>Impact on Cloud Costs and Infrastructure</h3><p>Optimizing the use of cloud resources can result in significant savings. Several strategies include:</p><ol><li><strong>Optimized Compute Usage</strong>: Using cloud services like <strong>AWS EC2 Spot Instances</strong> or <strong>Google Cloud Preemptible VMs</strong> can provide up to <strong>90%</strong> savings compared to on-demand instances by utilizing excess computing capacity.</li><li><strong>Storage Management</strong>: Efficient model storage, including <strong>model quantization</strong> (reducing the precision of weights) and <strong>model pruning</strong>, can decrease the size of models by up to <strong>50%</strong>. This directly impacts cloud storage costs.</li><li><strong>Bandwidth Optimization</strong>: By minimizing the amount of data transferred between cloud regions and reducing data duplication, businesses can optimize bandwidth usage and reduce costs by <strong>20%</strong>.</li></ol><h3>Real World Examples</h3><h4>Uber’s Route Matching Optimization with Scalable ML Infrastructure</h4><p>Uber’s Michelangelo platform supports scalable machine learning infrastructure, facilitating efficient deployment of models for applications such as driver-rider matching, with optimizations in inference latency and training costs.</p><p>This reflects the broader goal of <strong>mathematical and systems-level optimization</strong>: minimizing cost while maintaining service quality in large-scale deployments.</p><blockquote><strong><em>Optimization Methods:</em></strong><em> Feature preprocessing pipelines, scalable training architecture, distributed model deployment<br> </em><strong><em>Impact:</em></strong><em> Reduction in training overhead and inference time for high-frequency, latency-sensitive services</em></blockquote><p><strong>Source:</strong> Uber Engineering — Michelangelo: ML Platform</p><h4>Facebook’s Scalable Recommendation System Using Matrix Factorization</h4><p>Facebook developed a matrix factorization-based collaborative filtering system capable of efficiently handling massive datasets, thereby reducing computational costs while maintaining real-time recommendation performance. They optimized for scalability by using <strong>embeddings and matrix multiplications</strong>, which are highly parallelizable and compute-efficient.</p><p>These techniques allowed them to <strong>cut computational costs</strong> while maintaining real-time recommendation performance.</p><blockquote><strong><em>Optimization Methods:</em></strong><em> Matrix factorization, model compression, sparse embedding tables<br> </em><strong><em>Impact:</em></strong><em> Efficient real-time inference and reduced training/infrastructure load</em></blockquote><p><strong>Source:</strong> <a href="https://engineering.fb.com/2015/06/02/core-infra/recommending-items-to-more-than-a-billion-people/">Facebook Engineering — Recommending Items to a Billion People</a></p><h4>Google’s Learned Optimizers for Neural Network Training</h4><p>Google introduced a method using reinforcement learning to discover new <strong>optimization</strong> algorithms for training deep neural networks, <strong>resulting in faster convergence and reduced training time</strong>. These optimizers generalize across tasks and <strong>converge faster</strong>, helping reduce training time and infrastructure usage.</p><p>By applying <strong>reinforcement learning and meta-optimization</strong>, Google has shown that <strong>automatically selected optimizers</strong> can outperform traditional hand-crafted ones.</p><blockquote><strong><em>Optimization Methods:</em></strong><em> Meta-learning, reinforcement learning for optimizer discovery<br> </em><strong><em>Impact:</em></strong><em> Shorter training cycles, reduced compute cost at scale</em></blockquote><p><strong>Source:</strong> <a href="https://research.google/blog/using-machine-learning-to-discover-neural-network-optimizers/">Google AI Blog — Discovering Optimizers with ML</a></p><h4>Microsoft’s Optimization for Cloud Resource Allocation</h4><p>Microsoft’s CORE Optimization Toolkit employs mixed-integer programming to address large-scale resource allocation challenges in cloud environments, enhancing efficiency and performance. Though not limited to Azure, the toolkit is aimed at <strong>solving large-scale optimization problems</strong> in enterprise and cloud settings.</p><p>By using MIP and constraint solvers, Microsoft enables <strong>fine-grained control over resource placement and utilization</strong>, helping reduce the overhead in managing compute resources across datacenters.</p><blockquote><strong><em>Optimization Methods:</em></strong><em> Mixed-Integer Programming, constraint-based optimization<br> </em><strong><em>Impact:</em></strong><em> Efficient scheduling and resource use, improved performance per dollar</em></blockquote><p><strong>Source:</strong> <a href="https://www.microsoft.com/en-us/research/uploads/prod/2023/02/CORE-Toolkit_external.pdf">Microsoft Research — CORE Optimization Toolkit</a></p><h3>How Businesses Can Implement Optimization Today</h3><p>To implement these optimization techniques, businesses can:</p><ol><li><strong>Use Automated Hyperparameter Tuning:</strong> Tools like Optuna, Hyperopt, and Ray Tune can automate the process of finding the best parameters, reducing the time and resources spent on manual tuning.</li><li><strong>Apply Model Pruning and Quantization:</strong> Techniques such as neural network pruning can remove unnecessary model parameters, improving both the speed and efficiency of the AI model. Quantization reduces numerical precision without sacrificing accuracy.</li><li><strong>Leverage Cloud Cost Optimization Tools:</strong> Cloud providers offer auto-scaling and spot instances to dynamically allocate resources based on need, helping to reduce costs for non-critical workloads and variable traffic patterns.</li><li><strong>Implement Mathematical Solver Libraries:</strong> Libraries like CPLEX, Gurobi, and Google OR-Tools provide ready-to-use implementations of linear programming and convex optimization algorithms, which can be applied to infrastructure allocation problems.</li><li><strong>Adopt Feature Store Technology:</strong> Feature stores like Feast, Tecton, and Hopsworks enable feature reuse across models, reducing redundant computation and storage, ultimately lowering overall infrastructure costs.</li><li><strong>Utilize Distributed Training Optimization:</strong> Frameworks like Horovod and DeepSpeed optimize distributed training through mathematically optimal communication patterns, reducing training time and associated cloud costs through efficient parameter sharing and gradient aggregation.</li></ol><h3>Conclusion</h3><p>Mathematical optimization is a powerful tool that can directly reduce AI deployment costs. Through smart model selection, hyperparameter optimization, and resource management, businesses can cut costs by up to <strong>30% or more</strong>. By applying these techniques and leveraging the right tools, companies can build scalable and cost-effective AI systems that deliver high performance without draining resources. The key to sustainable AI lies in optimization — the smarter you are about your resources, the more efficient and profitable your AI deployment will be.</p><h3>What’s Next?</h3><p>In the upcoming article,<strong> <em>From Physics to Profits: Building Decision-Making Engines for Businesses</em></strong>, I’ll explore how principles from physics — such as modeling and system dynamics — are applied to create data-driven decision-making tools that help businesses improve efficiency, predict outcomes, and drive growth.</p><p><strong>Follow for more</strong>: <a href="https://medium.com/@sharmaraghav">medium.com/@sharmaraghav</a></p><p>LinkedIn: <a href="https://www.linkedin.com/in/raghav-sharma-b7a87a142/">https://www.linkedin.com/in/raghav-sharma-b7a87a142/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc855abfa511" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistical Analysis with Python — Part 8 — Forecasting]]></title>
            <link>https://ai.plainenglish.io/statistical-analysis-with-python-part-8-forecasting-7bc36ff38fcf?source=rss-fe39f9032e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bc36ff38fcf</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[forecast]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <dc:creator><![CDATA[Raghav Sharma]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 21:37:47 GMT</pubDate>
            <atom:updated>2025-06-11T07:58:26.074Z</atom:updated>
            <content:encoded><![CDATA[<h3>Statistical Analysis with Python — Part 8 — Forecasting</h3><p>In my last post, we discussed anomaly detection — spotting the outliers in a sea of regular patterns. Today, let’s dive into something equally fascinating but much more practical: forecasting.</p><p>Forecasting is what helps teams plan ahead, whether it’s how much stock to order, how many employees to schedule, or how much revenue to expect. It’s also why your favorite streaming service knows exactly when to recommend your comfort shows. And it’s behind every business decision that might seem like a lucky guess, but isn’t.</p><p>At its core, forecasting is about learning from the past. For example, if you’ve sold more ice cream every July for the past five years, chances are you’ll sell a lot this July too. Forecasting identifies these patterns — daily trends, seasonal spikes, and subtle shifts — and turns them into predictions you can actually use.</p><p>It’s about analyzing the numbers instead of just guessing, much like Michael Scott’s infamous “guessing game” when planning next quarter’s budget in <em>The Office</em>.</p><p>Forecasting is a skill that gets better with practice. Start with something simple — like sales, web traffic, or electricity usage — and soon you’ll be forecasting trends that actually make an impact.</p><p>So the next time someone asks, “What do you think next quarter will look like?” you won’t have to guess. You’ll already know.</p><h3><strong>What is Forecasting?</strong></h3><p>Forecasting is the process of making predictions about future events based on historical data and trend analysis. It involves using past and present information to estimate future outcomes, often through statistical models, machine learning algorithms, or expert judgment.</p><p>It answers a question that many of us find ourselves asking at different stages in life: <strong><em>What’s next?</em></strong></p><h3>Types of Forecasting</h3><p>Forecasting can be further categorized, but the parameters for categorization may vary. For the sake of simplicity and clarity, I have differentiated it further based on three parameters: time horizon, methodologies, and the nature of the data.</p><h4>1. Based on Methodology:</h4><p><strong>a. Qualitative Forecasting</strong></p><ul><li>Used when there’s little to no historical data.</li><li>Relies on expert opinions, intuition, and market research.</li><li>Examples:</li><li>Delphi method (expert consensus)</li><li>Market research/surveys</li><li>Focus groups</li></ul><p><strong>b. Quantitative Forecasting</strong></p><ul><li>Based on historical data and mathematical models.</li><li>Objective and data-driven.</li><li>Examples:</li><li>Time series forecasting (like ARIMA, Exponential Smoothing)</li><li>Causal models (like regression analysis, econometric models)</li></ul><h4>2. Based on Time Horizon:</h4><p><strong>a. Short-term Forecasting</strong></p><ul><li>Covers the immediate future (hours, days, weeks, a few months).</li><li>Typically used for operations (inventory, staffing, scheduling).</li></ul><p><strong>b. Medium-term Forecasting</strong></p><ul><li>Covers months to a couple of years.</li><li>Used for budgeting, marketing planning, and supply chain management.</li></ul><p><strong>c. Long-term Forecasting</strong></p><ul><li>Covers several years into the future.</li><li>Used for strategic planning (capacity planning, major investments, R&amp;D direction).</li></ul><h4>3. Based on Nature of Data:</h4><p><strong>a. Time Series Forecasting</strong></p><ul><li>Predicts future values based only on past patterns (trends, seasonality, cycles).</li><li>Assumes patterns will continue.</li></ul><p><strong>b. Causal Forecasting</strong></p><ul><li>Assumes that the forecasted variable is influenced by other factors (independent variables).</li><li>Example: Predicting sales based on advertising spend and economic indicators.</li></ul><p>See the tree diagram below for a visual overview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F7JawM7UvdR92nT3pfKn9A.png" /><figcaption>Image by author</figcaption></figure><h3><strong>Use Case</strong></h3><p>A retail company wants to accurately forecast the demand for its top-selling products over the next six months to optimize inventory levels, reduce stock outs, and minimize overstocking. The company seeks to combine different forecasting methods — including expert opinion for new products, historical sales data modeling, and external market indicators — to achieve better decision-making across operations, marketing, and supply chain departments.</p><p>Firstly, let’s visualize the approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*y6nuJ6Sp-eAwi6mfNxjhDg.png" /><figcaption>Image by author</figcaption></figure><h4>Step 1: Prepare a Sample Dataset</h4><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from statsmodels.tsa.holtwinters import ExponentialSmoothing<br>from statsmodels.tsa.arima.model import ARIMA<br>from sklearn.linear_model import LinearRegression<br>from sklearn.model_selection import train_test_split<br>import statsmodels.api as sm<br><br><br>np.random.seed(42)<br>months = pd.date_range(&#39;2020-01-01&#39;, periods=24, freq=&#39;M&#39;)<br>sales_data = np.random.normal(loc=200, scale=50, size=len(months)) + np.sin(np.linspace(0, 10, len(months))) * 20<br><br>data = pd.DataFrame({&#39;Date&#39;: months, &#39;Sales&#39;: sales_data})<br><br><br>plt.figure(figsize=(10, 6))<br>plt.plot(data[&#39;Date&#39;], data[&#39;Sales&#39;], label=&#39;Actual Sales&#39;)<br>plt.title(&#39;Retail Sales Data (24 Months)&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Sales&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*T2fhuYB9csWNyIlpqpjodA.png" /><figcaption>Image by author</figcaption></figure><h4>Based on Methodologies</h4><p><strong>Qualitative Forecasting</strong></p><p>Qualitative forecasting relies on subjective judgment, intuition, and expert opinions when there is limited or no historical data.</p><p><strong>Quantitative Forecasting</strong></p><p><strong>ARIMA</strong> (AutoRegressive Integrated Moving Average) is used to forecast future sales based on the past trends in data.</p><pre>arima_model = ARIMA(data[&#39;Sales&#39;], order=(5, 1, 0))  # ARIMA(p, d, q)<br>arima_fit = arima_model.fit()<br><br><br>arima_forecast = arima_fit.forecast(steps=6)<br><br><br>plt.figure(figsize=(10, 6))<br>plt.plot(data[&#39;Date&#39;], data[&#39;Sales&#39;], label=&#39;Actual Sales&#39;)<br>plt.plot(data[&#39;Date&#39;][-6:], arima_forecast, label=&#39;ARIMA Forecast&#39;, linestyle=&#39;--&#39;)<br>plt.title(&#39;Sales Forecast with ARIMA Model&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Sales&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*xy8YeC0qxTZOSNLVCoO_3Q.png" /><figcaption>Image by author</figcaption></figure><h4>Time Horizon Based Forecasting</h4><p><strong>Short Term Forecasting</strong></p><p><strong>Exponential Smoothing</strong> is used for short-term forecasting, especially helpful for operations and inventory management.</p><pre>exp_model = ExponentialSmoothing(data[&#39;Sales&#39;], trend=&#39;add&#39;, seasonal=&#39;add&#39;, seasonal_periods=12).fit()<br>exp_forecast_short = exp_model.forecast(steps=3)<br><br><br>plt.plot(data[&#39;Date&#39;], data[&#39;Sales&#39;], label=&#39;Actual Sales&#39;)<br>plt.plot(data[&#39;Date&#39;][-3:], exp_forecast_short, label=&#39;Short-Term Forecast&#39;, linestyle=&#39;--&#39;)<br>plt.title(&#39;Short-Term Sales Forecasting (3 Months)&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Sales&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*AuPi0MOJANo1s3O0tG-M_A.png" /><figcaption>Image by author</figcaption></figure><p><strong>Medium Term Forecasting</strong></p><p><strong>Linear Regression</strong> is applied for medium-term forecasting, showing how sales might evolve based on the trend.</p><pre>X = np.array(range(len(data))).reshape(-1, 1)  # Time steps (months)<br>y = data[&#39;Sales&#39;]<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)<br>model = LinearRegression().fit(X_train, y_train)<br><br># Predict next 12 months (medium term)<br>medium_term_forecast = model.predict(X_test)<br>plt.plot(data[&#39;Date&#39;], data[&#39;Sales&#39;], label=&#39;Actual Sales&#39;)<br>plt.plot(data[&#39;Date&#39;][len(data)-len(medium_term_forecast):], medium_term_forecast, label=&#39;Medium-Term Forecast&#39;, linestyle=&#39;--&#39;)<br>plt.title(&#39;Medium-Term Sales Forecasting (Linear Regression)&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Sales&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*KACbwZYONx6GmILhmjSkow.png" /><figcaption>Image by author</figcaption></figure><p><strong>Long Term Forecasting</strong></p><p>Polynomial Regression is used for long-term forecasting, capturing non-linear trends and providing a more flexible model for predicting sales over several years, making it suitable for strategic planning and capacity expansion</p><pre>poly_model = np.poly1d(np.polyfit(X.flatten(), y, 3))  # Degree 3 Polynomial for trend<br>long_term_forecast = poly_model(X.flatten())<br><br><br>plt.plot(data[&#39;Date&#39;], data[&#39;Sales&#39;], label=&#39;Actual Sales&#39;)<br>plt.plot(data[&#39;Date&#39;], long_term_forecast, label=&#39;Long-Term Forecast (Polynomial)&#39;, linestyle=&#39;--&#39;)<br>plt.title(&#39;Long-Term Sales Forecasting (Polynomial Regression)&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Sales&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*PPQWs1H7RQYVMKTJK4qkDg.png" /><figcaption>Image by author</figcaption></figure><h4>Nature of Data Based Forecasting</h4><p><strong>Time Series Forecasting</strong></p><p>Already demonstrated with ARIMA and Exponential Smoothing methods above.</p><p><strong>Causal Forecasting</strong></p><p>We used <strong>marketing spend</strong> as an independent variable (feature) to predict sales, illustrating causal relationships in business.</p><pre>marketing_spend = np.random.normal(5000, 1000, len(data))  # Simulated marketing spend data<br>X_causal = np.column_stack([marketing_spend, X.flatten()])<br>y_causal = data[&#39;Sales&#39;]<br><br># Fit a Linear Regression model<br>causal_model = LinearRegression().fit(X_causal, y_causal)<br><br># Forecasting sales based on marketing spend for the next 6 months<br>new_marketing_spend = np.random.normal(5000, 1000, 6)  # Simulate next 6 months&#39; marketing spend<br>causal_forecast = causal_model.predict(np.column_stack([new_marketing_spend, np.arange(len(data), len(data) + 6)]))<br><br># Plot causal forecast<br>plt.plot(data[&#39;Date&#39;], data[&#39;Sales&#39;], label=&#39;Actual Sales&#39;)<br>plt.plot(data[&#39;Date&#39;][-6:], causal_forecast, label=&#39;Causal Forecast (Marketing Spend)&#39;, linestyle=&#39;--&#39;)<br>plt.title(&#39;Causal Forecasting (Sales vs. Marketing Spend)&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Sales&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*1AqkMYBX-OnAO2wHi6sfcA.png" /><figcaption>Image by author</figcaption></figure><p><strong>To Summarize:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8t3-KQs-hb2pTJToNt4iw.png" /><figcaption>Image by Author</figcaption></figure><h3>Key Business Decisions from Data</h3><ul><li><strong>Inventory Optimization</strong>: The short-term forecasting model (Exponential Smoothing) suggests steady sales for the next three months, indicating the need for the company to optimize its current inventory levels and avoid overstocking.</li><li><strong>Marketing Strategy Adjustment</strong>: The medium-term forecast (Linear Regression) predicts a gradual increase in sales. This signals the need for marketing campaigns to boost sales and capitalize on the expected growth.</li><li><strong>Long-Term Strategic Planning</strong>: The polynomial regression model shows a steady upward trend in sales over the long term, which highlights the importance of investing in capacity expansion and supply chain optimization to meet future demand.</li><li><strong>Forecasting Accuracy Improvement</strong>: The ARIMA model provides accurate predictions for the next six months, suggesting that the company can rely on ARIMA-like models for more precise operational decisions in the near future.</li></ul><h3>From Sample to Real-Life Data: The Power of Visualization</h3><p>For demonstration purposes, I’ve used a sample dataset. In real-life scenarios, datasets are typically ready for analysis. Visualization is essential for uncovering trends and insights in data. I’d like to highlight <a href="https://plotsalot.slashml.com/"><strong>PlotsAlot</strong></a><strong> by SlashML</strong>, a tool that allows you to upload your dataset and ask questions in natural language. It then generates the corresponding visualizations, making data analysis more accessible without the need for coding.</p><h3>Key Takeaways</h3><ul><li><strong>Understanding Forecasting</strong>: Forecasting helps businesses predict future trends based on historical data, enabling better decision-making in areas like inventory management, staffing, and strategic planning.</li><li><strong>Different Types of Forecasting</strong>: Forecasting can be classified based on methodology (qualitative vs. quantitative), time horizon (short-term, medium-term, long-term), and the nature of data (time series vs. causal). Each approach serves a specific purpose in addressing business needs.</li><li><strong>Popular Forecasting Methods</strong>:</li><li><strong>ARIMA</strong>: A powerful quantitative model used for time series forecasting, ideal for predicting future sales based on historical data.</li><li><strong>Exponential Smoothing</strong>: Best suited for short-term forecasting, especially for operational needs like inventory and staffing.</li><li><strong>Linear Regression</strong>: Applied for medium-term forecasting, predicting trends based on historical data.</li><li><strong>Polynomial Regression</strong>: Useful for long-term forecasting, especially when there are non-linear trends.</li><li><strong>Causal Forecasting</strong>: Incorporating external variables, such as marketing spend, into the forecasting model can provide insights into how other factors influence outcomes, offering a more nuanced prediction.</li><li><strong>Real-Life Use Case</strong>: A retail company can combine different forecasting methods — ARIMA for short-term, Linear Regression for medium-term, and Polynomial Regression for long-term forecasting — to optimize inventory, marketing strategies, and long-term capacity planning.</li><li><strong>Importance of Visualization</strong>: Data visualization is crucial for understanding and communicating forecasting results. It helps businesses see trends, compare actual vs. forecasted values, and make data-driven decisions.</li><li><strong>Simplifying Visualization with PlotsAlot</strong>: Tools like <strong>PlotsAlot by SlashML</strong> make it easy to visualize data by allowing users to upload datasets and generate visualizations and insights through natural language queries, without requiring coding skills.</li></ul><h3>Next Up?</h3><p>This article concludes our series on <strong>Statistical Analysis with Python</strong>. You can explore the full series here: <a href="https://medium.com/@sharmaraghav644">https://medium.com/@sharmaraghav644</a>.</p><p>Moving forward, I will focus on areas like the challenges faced by companies working with image-based data, NLP, speech recognition, and more. I’ll be sharing insights on these topics soon — stay tuned!</p><p><strong>Follow for more</strong>: <a href="https://medium.com/@sharmaraghav">medium.com/@sharmaraghav</a></p><p>LinkedIn: <a href="https://www.linkedin.com/in/raghav-sharma-b7a87a142/">https://www.linkedin.com/in/raghav-sharma-b7a87a142/</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bc36ff38fcf" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/statistical-analysis-with-python-part-8-forecasting-7bc36ff38fcf">Statistical Analysis with Python — Part 8 — Forecasting</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Paradoxical Nature of Humans Will Prevent AI from Taking Over the World]]></title>
            <link>https://medium.com/@sharmaraghav644/the-paradoxical-nature-of-humans-will-prevent-ai-from-taking-over-the-world-e60fa072965b?source=rss-fe39f9032e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e60fa072965b</guid>
            <category><![CDATA[consciousness]]></category>
            <category><![CDATA[paradox]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[philosophy]]></category>
            <dc:creator><![CDATA[Raghav Sharma]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 19:28:25 GMT</pubDate>
            <atom:updated>2025-04-16T19:28:25.769Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSiX8FAKqQ55xwsPnrglJA.png" /></figure><p>With rapid advancements in Artificial Intelligence, it’s become trendy — almost expected — to speculate about machines overtaking humanity. Bold claims fill the airwaves: “<em>AI will replace us,</em>” “<em>AI will control society</em>,” and so on.</p><p>But how much of that is grounded in reality?</p><p>The answer, I believe, lies in a paradox: the difference between how AI affects us <strong>as individuals</strong> versus how it affects us <strong>as a society</strong>.</p><p>As a data scientist and an avid reader of philosophy, I’ve spent a lot of time thinking about what it truly means to “know” something — and whether machines ever could.</p><p>Here are my two cents.</p><h3>We Are Paradoxical Creatures</h3><p>Humans are deeply contradictory beings. We operate through a blend of logic and emotion, certainty and ambiguity. More importantly, we’re not even fully aware of our own consciousness. And here’s a truth that often gets ignored: something can only be <em>accurately</em> taught when the teacher understands it fully.</p><p>We don’t understand consciousness. Not even close. So how do we expect to transfer it into a machine?</p><p>We are driven by intangible variables: love, faith, anger, grief, lust. These are not numbers you can plug into a formula or feed into a model — at least not with any real fidelity. Sure, AI can mimic or simulate these patterns, but that’s not the same as experiencing them. What’s the difference between <em>calculated love</em> and <em>infinite love</em>? Maybe Shakespeare or Ghalib would have an answer. But good luck measuring it with a loss function.</p><p>Take faith. Is it a product of past experiences? Knowledge? Hope? Or something else entirely? Religious texts speak of its power, but they don’t define it in a way an algorithm could learn.</p><p>And luck? Try tracing the steps of a lottery winner, model their daily habits, assign weights to each decision — then hope your model outputs another winner. Dijkstra’s algorithm can find the shortest path in a graph. It can’t chart the role of cosmic chance in human lives.</p><p>Dostoyevsky once wrote, “<em>Man is a mystery. It needs to be unraveled, and if you spend your whole life unraveling it, don’t say that you’ve wasted time.</em>”</p><p>That mystery isn’t just literary flourish — it’s a recognition of how elusive our inner workings truly are. If even the great minds of literature and philosophy grappled with understanding the human spirit, how can we expect machines to capture it in a few million lines of code?</p><h3>The Buddha Analogy</h3><p>I once heard a powerful story.</p><p>A woman grieving the loss of her child asked Buddha, “Can you bring my son back to life?”</p><p>He replied, “Yes. But first, bring me a grain of rice from a household where no death has occurred.”</p><p>She couldn’t find one.</p><p>That story doesn’t answer the question <em>“Will AI take over?”</em> directly — but it hints at something deeper. Just as death is universal and unavoidable, so is human contradiction, uncertainty, and the tendency to ask questions we ourselves cannot answer. AI is a tool. A powerful one. But it doesn’t seek. It doesn’t wonder. It doesn’t grieve.</p><h3>The Power of “I Don’t Know”</h3><p>As long as there are people willing to say, honestly and humbly, <em>“I don’t know”</em> — AI won’t fully take over. Because AI thrives on clearly defined objectives. On measurable inputs. On patterns it can optimize.</p><p>But humanity is not a clean dataset.</p><p>Nietzsche famously challenged the foundations of morality and knowledge itself, reminding us that the pursuit of truth often leads to more questions than answers. And Viktor Frankl, in <em>Man’s Search for Meaning</em>, emphasized that the will to meaning — our need to find purpose even in suffering — is what defines us most deeply.</p><p>AI can model behavior, predict outcomes, even imitate compassion. But it cannot suffer meaningfully. It cannot choose to find hope in despair. It cannot rebel against nihilism or embrace ambiguity with courage</p><p>Yes, many will say, <em>“One person can’t know everything, but a collective of people can know almost everything.”</em> And that’s fair. But the word <strong>almost</strong> matters.</p><p>If there’s something that no one in the collective knows — then that knowledge simply doesn’t exist for AI to learn from. In that silence, that unknown, lies the edge that machines cannot reach. Because what we don’t know, we can’t encode. And what we can’t encode, AI can’t compute.</p><h3>Meaning Beyond Machines</h3><p>Frankl observed that those who survived the worst of humanity — the concentration camps — did so not through strength, but through meaning. That meaning wasn’t logical. It wasn’t data-driven. It came from love, from faith, from inner resolve.</p><p>Sure, machines can optimize faster, process more, learn quicker. They can outperform us in almost every measurable task. In many ways, they can <em>do everything better than humans</em>.</p><p>But can you go through life without truly surviving it? Without suffering, without stumbling, without meaning?</p><p>And if not — can you teach a machine how to survive something it was never alive for? Can you teach AI how to suffer and still choose to keep going?</p><p>AI has no inner world. It doesn’t long, it doesn’t search. It doesn’t suffer for purpose. And until it does, it can never truly <em>be</em> one of us — let alone <em>replace</em> us.</p><h3>Final Thoughts</h3><p>AI may reshape industries, optimize logistics, write music, generate art, and even mimic empathy. But to truly “take over” requires more than intelligence — it requires the ability to not know, to feel without definition, to act without optimization.</p><p>Until machines can say <em>“I don’t know”</em> — and mean it — they remain imitators, not successors.<br> And even if they do say it, what then?<br> A machine that admits it doesn’t know — what power does it have to take over a species defined by uncertainty?</p><p>That’s the paradox they’ll never solve.</p><p>Because to truly take over humanity, you’d have to become human.<br> And that… would make you no longer a machine.</p><h3>Stay Connected</h3><p>If this sparked something in you, I write regularly about AI, data, and the human condition.</p><ul><li>📝 <a href="https://medium.com/@sharmaraghav644">medium.com/@sharmaraghav</a></li><li>🔗 <a href="https://www.linkedin.com/in/raghav-sharma-b7a87a142/">Connect with me on LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e60fa072965b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>