<?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 Vishal Lakshmi Narayanan on Medium]]></title>
        <description><![CDATA[Stories by Vishal Lakshmi Narayanan on Medium]]></description>
        <link>https://medium.com/@lvishal1607?source=rss-668cf5ab8335------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZESR1OLlx6m1RSfly7pyhA.jpeg</url>
            <title>Stories by Vishal Lakshmi Narayanan on Medium</title>
            <link>https://medium.com/@lvishal1607?source=rss-668cf5ab8335------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:22:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lvishal1607/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The End of the Black Box: Why Glass-Box Modeling is the Future of Responsible AI]]></title>
            <link>https://medium.com/@lvishal1607/the-end-of-the-black-box-why-glass-box-modeling-is-the-future-of-responsible-ai-75c716f5049f?source=rss-668cf5ab8335------2</link>
            <guid isPermaLink="false">https://medium.com/p/75c716f5049f</guid>
            <category><![CDATA[blackbox-ai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vishal Lakshmi Narayanan]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 17:04:22 GMT</pubDate>
            <atom:updated>2026-01-25T17:04:22.273Z</atom:updated>
            <content:encoded><![CDATA[<p>Bridging the gap between Deep Learning performance and human-level interpretability with Neural Additive Models (NAMs).</p><p><em>For years, the field of Machine Learning has been haunted by a “Great Trade-off.”</em></p><p><em>On one side, we have Linear Models. They are simple, transparent, and easy to explain to a regulator or a customer. However, they are often “too dumb” to catch the complex, non-linear patterns hidden in modern big data.</em></p><p><em>On the other side, we have Deep Learning. These “Black Boxes” are incredibly powerful, capable of superhuman accuracy. But they have a fatal flaw: they cannot explain why they made a decision. In high-stakes industries like banking, healthcare, and law, this lack of transparency isn’t just a technical hurdle, it’s a legal and ethical liability.</em></p><p><em>Enter the Glass-Box Model: a paradigm shift in architecture that proves we no longer have to choose between a model that works and a model we understand.</em></p><h4>The Anatomy of a Glass-Box</h4><p><em>In a traditional Neural Network, all variables are thrown into a “hidden layer”. They are multiplied and mixed together until their individual signals are lost. This “entanglement” is what creates the Black Box.</em></p><p><em>A Neural Additive Model (NAM) fundamentally changes this by building a colony of specialists. Instead of one large network processing all data points at once, a NAM builds a dedicated Expert Network (a sub-neural network) for every single input feature.</em></p><ul><li><em>Expert A only sees Feature A.</em></li><li><em>Expert B only sees Feature B.</em></li><li><em>Expert C only sees Feature C.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5LzJ7JEOWFdbdB7RCsmNw.jpeg" /><figcaption>Image Source: <a href="https://arxiv.org/pdf/2004.13912">https://arxiv.org/pdf/2004.13912</a></figcaption></figure><p><em>Because these experts are physically separated within the architecture, they can never “pollute” each other’s logic. Each expert learns the most complex version of its own specific world, and their individual insights are simply added together at the final stage to produce the final prediction.</em></p><p><em>The most exciting part of Glass-Box modeling is that we can literally graph the model’s brain. By plotting the input of a feature against its specific expert-network output, we get a Shape Plot.</em></p><p><em>Imagine a model predicting a medical outcome or a physical phenomenon. A Shape Plot allows a scientist to see the exact “curve” of the relationship. They can see where a variable’s impact plateaus, where it spikes, and where it drops. If the graph shows a chaotic or nonsensical zig-zag, the scientist can “debug” that specific feature network without having to scrap the entire model.</em></p><h4>Why we Need Glass-Box AI Now</h4><p><em>As AI moves from experimental labs into the “Real World,” the demand for Accountable AI is skyrocketing for three reasons:</em></p><ol><li><strong><em>Safety-Critical Reliability:</em></strong><em> In fields like medicine or autonomous systems, “trusting the machine” isn’t enough. We need to verify that the model is using logical correlations rather than “hallucinating” patterns in noise.</em></li><li><strong><em>Debugging at Scale:</em></strong><em> In a Black Box, a small error in one variable can corrupt the entire output. In a NAM, you can isolate, fine-tune, or even override a single feature network without retraining the rest of the system.</em></li><li><strong><em>The “Right to Explanation”:</em></strong><em> As algorithms begin to affect human lives from insurance to hiring transparency is becoming a legal requirement. Glass-box models provide a clear audit trail for every decision made.</em></li></ol><p><em>The era of “Accuracy at any cost” is ending. As we move through 2026, the most valuable models won’t just be the ones that are the most accurate they will be the ones that are the most auditable.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75c716f5049f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Modern LLMs Understand Context: Inside RMSNorm, SwiGLU, RoPE & Next-Gen Attention]]></title>
            <link>https://medium.com/@lvishal1607/how-modern-llms-understand-context-inside-rmsnorm-swiglu-rope-next-gen-attention-3b3eea7789db?source=rss-668cf5ab8335------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b3eea7789db</guid>
            <category><![CDATA[rmsnorm]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Vishal Lakshmi Narayanan]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 16:28:53 GMT</pubDate>
            <atom:updated>2025-12-05T16:28:53.600Z</atom:updated>
            <content:encoded><![CDATA[<p><em>We often talk about large language models as if they understand.<br>We say they follow context.<br>We say they remember previous conversation.<br>But beneath that smooth illusion of intelligence lies a sequence of operations that convert text into vectors, vectors into relationships, and relationships into reasoning.</em></p><p><em>Most state of the art models today such as LLaMA 3, Mistral, Gemma, Mixtral and DeepSeek V2 process information through the same backbone:</em></p><p><em>RMSNorm → SwiGLU → RoPE → Advanced KV Cache Attention (GQA or MLA)</em></p><p><em>This is the path that turns raw text into structured thought.<br>Let us walk through each component clearly and practically.</em></p><h4>RMSNorm: The Stability Layer</h4><p><em>Deep models collapse when internal numbers explode or shrink toward zero.<br>RMSNorm (Root Mean Square Normalization) prevents that failure.</em></p><p><em>Instead of subtracting the mean like LayerNorm, RMSNorm simply rescales the vector magnitude using RMS. This provides stability while reducing computation cost.</em></p><p><em>Why modern models prefer it:</em></p><ul><li><em>keeps activations balanced across hundreds of layers</em></li><li><em>improves gradient flow for large depth</em></li><li><em>reduces compute because mean subtraction is removed</em></li><li><em>essential for long context inference</em></li></ul><p><em>Think of RMSNorm as volume control for the entire thought.<br>No matter how loud or chaotic the raw signal is, RMSNorm brings it back to a safe and usable level.</em></p><h4>SwiGLU: The Meaning Expansion Stage</h4><p><em>Each token embedding contains many potential interpretations.<br>SwiGLU (Swish Gated Linear Unit) expands and filters those signals.</em></p><p><em>The mechanism works by splitting a token into two paths.<br>One creates a transformed version of the embedding.<br>The other applies a Swish activation to determine which features are useful.<br>The output is the product of both paths.</em></p><p><em>Why this matters:</em></p><ul><li><em>extracts richer features from each word</em></li><li><em>disambiguates meaning based on context</em></li><li><em>more expressive and efficient than GELU or ReLU</em></li><li><em>now standard in mainstream and research models</em></li></ul><h4>RoPE: The Positional Backbone</h4><p><em>Transformers have no natural sense of order.<br>RoPE (Rotary Positional Embeddings) provides it in an elegant geometric way.</em></p><p><em>Instead of adding positional vectors to tokens, RoPE rotates the Query and Key vectors based on token index. Distance is encoded as an angle.<br>Relationships decay naturally as tokens move farther apart in the sequence.</em></p><p><em>Benefits:</em></p><p><em>• enables very long context windows<br>• expresses relative distance, not absolute index<br>• scales more naturally than sinusoidal embeddings<br>• now the standard for long sequence reasoning</em></p><p><em>Order becomes geometry.<br>The word sat can recognize that cat came shortly before it, because their embeddings rotate into compatible alignment.</em></p><h4>Advanced KV Cache Attention (GQA and MLA)</h4><p><em>Attention is where tokens finally interact.<br>Each token produces:</em></p><p><em>• Query: what I need<br>• Key: what I contain<br>• Value: what I can contribute</em></p><p><em>Attention calculates relevance between Q and K, then retrieves information from V based on that relevance.</em></p><p><em>The real challenge is efficiency.<br>Storing the Key Value cache becomes expensive when context grows past tens or hundreds of thousands of tokens.<br>Modern models use two major solutions.</em></p><p><strong><em>A. GQA (Grouped Query Attention)</em></strong></p><p><em>• More Query heads for richer views<br>• Fewer Key and Value heads to reduce cache size<br>• Maintains performance while lowering memory footprint</em></p><p><em>Used in LLaMA 3, Mistral and Gemma.</em></p><p><strong><em>B. MLA (Multi Head Latent Attention)</em></strong></p><p><em>• Compresses the Key Value cache into a latent space<br>• Reduces memory load by more than 90 percent<br>• Enables extremely long context inference</em></p><p><em>Used in DeepSeek V2.<br>With MLA, a conversation spanning 100 pages can still retrieve relevant past information instantly.</em></p><h4>Advancement: MoE (Mixture of Experts)</h4><p><em>MoE is becoming the next major growth direction.<br>Instead of one giant feed forward network, MoE uses multiple experts and activates only a few for each token.</em></p><p><em>Advantages:</em></p><p><em>• huge model capacity without huge inference cost<br>• allows training larger brains without slower runtime<br>• used in Mixtral and DeepSeek for training scale</em></p><p><em>LLMs can now be both smarter and faster.</em></p><p><em>Modern LLMs do not think, but they process information in a way that looks like thought.<br>Text becomes vectors.<br>Vectors gain structure.<br>Structure forms relationships.<br>Relationships create context.</em></p><p><em>This four stage system is the foundation of nearly every frontier model in 2025.<br>RMSNorm stabilizes, SwiGLU enriches, RoPE anchors time, and attention binds everything into meaning.</em></p><p><em>Understanding this pipeline is understanding the mind of a transformer.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b3eea7789db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TOON in Practice: A Real Benchmark Across JSON, YAML, CSV, and a New LLM-Friendly Format]]></title>
            <link>https://medium.com/@lvishal1607/toon-in-practice-a-real-benchmark-across-json-yaml-csv-and-a-new-llm-friendly-format-67abef240ef7?source=rss-668cf5ab8335------2</link>
            <guid isPermaLink="false">https://medium.com/p/67abef240ef7</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[toon]]></category>
            <dc:creator><![CDATA[Vishal Lakshmi Narayanan]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 15:32:21 GMT</pubDate>
            <atom:updated>2025-11-16T15:32:21.126Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Over the last week, TOON (Token-Oriented Object Notation) has been circulating heavily across X, Reddit, Discords, and AI engineering groups.<br>Most conversations focus on the idea behind it, but very few show how it behaves on a real task.</em></p><p><em>So instead of posting about the concept, I decided to actually test it.</em></p><p><em>I generated the same structured dataset across multiple formats:<br>Standard JSON, Minified JSON, YAML, CSV, and TOON.</em></p><p><em>Here is what I learned.</em></p><h4>Why I Wanted to Test TOON</h4><p><em>TOON is not positioned as a human-facing format.<br>It is lightweight, pattern-driven, and meant to reduce unnecessary structural overhead.</em></p><p><em>That made me curious.</em></p><p><em>Does an LLM genuinely produce TOON more cleanly than traditional formats?<br>Does it reduce errors?<br>Does compactness come with trade-offs?</em></p><p><em>I wanted to understand its behavior, not just its definition.</em></p><h4>The Benchmark Setup</h4><p><em>I used the same structured generation task for every test:</em></p><p><em>Dataset:<br>20 realistic F1 driver records<br>Fields: number, name, team, points<br>Format outputs: JSON, YAML, CSV, TOON</em></p><p><em>Environment:<br>Gemini 2.5 Flash<br>Python-based benchmark<br>Identical prompt for all formats (only the output instruction changed)</em></p><p><em>This made the comparison fair and consistent.</em></p><h4>How Each Format Behaved</h4><p><strong><em>JSON (Standard + Minified)</em></strong></p><p><em>JSON behaved as expected: reliable but verbose.<br>Standard JSON added layers of indentation and brackets.<br>Minified JSON removed whitespace but still repeated keys and quotes for every object.</em></p><p><em>Common behavior:<br>Occasional missing commas or slight formatting drift.</em></p><p><strong><em>YAML</em></strong></p><p><em>YAML produced a readable structure, but indentation inconsistencies appeared occasionally.<br>It was clean, but not always stable across all 20 items.</em></p><p><strong><em>CSV</em></strong></p><p><em>CSV was the most compact format, but extremely limited.<br>There is no schema, no object boundaries, and no clear differentiation if the dataset grows in complexity.</em></p><p><em>CSV worked only because the task was simple.</em></p><p><strong><em>TOON</em></strong></p><p><strong><em>TOON </em></strong><em>was where things became interesting.</em></p><p><em>Even though it is not an official AI-platform feature or product, TOON behaved like a format the model naturally understood.</em></p><p><em>Key patterns I noticed:</em></p><p><strong><em>1. More consistent structure</em></strong></p><p><em>The model avoided common formatting mistakes that showed up in JSON and YAML.</em></p><p><strong><em>2. Minimal but expressive layout</em></strong></p><p><em>One header line defines the schema.<br>The rest is pure data.<br>No repeated keys, brackets, or nested layers.</em></p><p><strong><em>3. Outputs stayed stable even with more records</em></strong></p><p><em>Where YAML and JSON sometimes drifted slightly, TOON held its form throughout the dataset.</em></p><p><strong><em>4. The model followed the TOON pattern very naturally</em></strong></p><p><em>It required less prompting and less corrective steering.</em></p><p><em>This suggests that TOON aligns well with how LLMs internally plan structured output.</em></p><h4>A Realistic Trade-Off: Efficiency vs Time</h4><p><em>A subtle finding emerged:</em></p><p><em>TOON is extremely compact in bytes, but that does not always make it the fastest to generate.</em></p><p><em>The model sometimes took marginally more time to assemble the compact structure, compared to simpler formats like CSV or minified JSON.</em></p><p><em>This trade-off is important:</em></p><ul><li><em>TOON wins on structure and compactness</em></li><li><em>TOON does not always win on generation speed</em></li></ul><p><em>Size efficiency and runtime efficiency do not always go hand in hand.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*-IPRcNagShGrf9P9giv4eA.png" /><figcaption>Benchmark Results</figcaption></figure><h4>What This Benchmark Suggests</h4><p><em>After running all formats side by side, three observations stood out:</em></p><p><em>1. TOON feels LLM-friendly</em></p><p><em>The model adhered to its structure more reliably than JSON or YAML.</em></p><p><em>2. It removes the noise without losing clarity</em></p><p><em>No repeated keys.<br>No deep nesting.<br>No unnecessary punctuation.</em></p><p><em>3. It has genuine strengths and real limitations</em></p><p><em>Compact and stable, yes.<br>Always the fastest, no.</em></p><p><em>TOON seems especially useful for:</em></p><ul><li><em>agent-to-agent messaging</em></li><li><em>multi-step workflows</em></li><li><em>dense structured output</em></li><li><em>reducing overhead in API calls</em></li><li><em>predictable formatting across many items</em></li></ul><p><em>But JSON/YAML still have advantages where schema validation, human readability, or deep structural nesting are required.</em></p><h4>Final Thoughts</h4><p><em>The hype around TOON makes more sense after testing it on a realistic task.<br>It is not just “another compact format.”<br>It has unique behaviors that show up only when you benchmark it on larger, multi-record outputs.</em></p><p><em>TOON is small, clean, predictable, and surprisingly LLM-aligned.<br>At the same time, it introduces real trade-offs around generation time.</em></p><p><em>It feels like an interesting step toward formats that are optimized not for humans, but for how models actually think.</em></p><p><em>I am sharing my benchmark code below for anyone interested in trying it themselves. Would love to hear how TOON behaves in different structures and domains.</em></p><p><a href="https://github.com/VishalLakshmiNarayanan/TOONvsJSON">GitHub - VishalLakshmiNarayanan/TOONvsJSON</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67abef240ef7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tail Risk: A Loss-at-Risk Driven Framework for Improving
Catastrophic Claim Severity Models]]></title>
            <link>https://medium.com/@lvishal1607/tail-risk-a-loss-at-risk-driven-framework-for-improving-catastrophic-claim-severity-models-81669725ebb1?source=rss-668cf5ab8335------2</link>
            <guid isPermaLink="false">https://medium.com/p/81669725ebb1</guid>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vishal Lakshmi Narayanan]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 15:42:37 GMT</pubDate>
            <atom:updated>2025-11-14T15:42:37.751Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In my earlier article, I explored a fundamental issue in insurance modeling. Traditional regression pipelines optimized for Mean Squared Error tend to perform well on typical claims but systematically underestimate catastrophic ones. The result is not a forecasting failure, but a structural one. The loss function itself encourages the model to prioritize what is common rather than what is financially consequential.</em></p><p><em>This follow up article moves beyond identifying the problem. It introduces TailRisk, a risk aware modeling framework designed to evaluate, stress test, and improve model behavior in the extreme upper tail of insurance loss distributions. The goal here is not to produce a perfect claim predictor. Instead TailRisk serves as a structured approach for understanding how different models behave under heavy tailed conditions and how their sensitivity to catastrophic loss can be enhanced through tail weighting, CVaR based diagnostics, and meta learning strategies.</em></p><p><em>Over the past weeks I developed and tested multiple components of this framework including Loss at Risk weighting, Conditional Value at Risk analysis, traditional ensembles, CVaR weighted ensembles, quantile meta learning, and a hybrid tail sensitive mechanism. Each component has one purpose to understand and reduce catastrophic underestimation without treating the problem as a generic forecasting task.</em></p><p><em>If you are interested in how modeling frameworks can become more honest about tail behaviour rather than more accurate on average TailRisk is the next step in that journey.</em></p><h4>Traditional Ensembles Under Tail Evaluation: What Breaks First</h4><p><em>After establishing Loss at Risk and CVaR as the core diagnostic tools in TailRisk, the next step was to test whether traditional ensemble models could inherently handle catastrophic tail behavior. Random Forests, Gradient Boosting, and XGBoost are strong performers on structured tabular data. They often win competitions, deliver low MSE, and handle complex interactions better than linear methods.</em></p><p><em>But performance on the average case is not what TailRisk is designed to measure.<br>So the question becomes:</em></p><p><em>How do ensemble models behave when evaluated only on the catastrophic tail the top 1 percent of insurance losses?</em></p><p><em>To explore this, I trained three ensemble models using default but reasonable hyperparameters:</em></p><p><em>• Random Forest (100 trees, depth 10)<br>• Gradient Boosting (100 estimators, depth 5, lr = 0.1)<br>• XGBoost (100 trees, depth 5, lr = 0.1)</em></p><p><em>Below are their test set results pulled directly from the TailRisk paper:</em></p><pre>| Model                          | MSE (Overall)    |<br>| ------------------------------ | ---------------- |<br>| Random Forest                  | **3,424,326.36** |<br>| Gradient Boosting              | **3,016,616.06** |<br>| XGBoost                        | **3,255,261.56** |<br>| LaR Weighted Linear Regression | **2,815,523.76** |</pre><p><em>At first glance, ensembles look competitive. Gradient Boosting even achieves lower overall MSE than the baseline linear model.</em></p><p><em>But when TailRisk shifts attention to the catastrophic zone, a different story emerges.</em></p><h4>Catastrophic Tail Weakness</h4><p><em>The paper evaluates catastrophic errors using:</em></p><p><em>• MSE in the Extreme Tail (≥99th percentile)<br>• CVaR(95%) Loss, which measures the average squared error in the worst 5% of predictions</em></p><p><em>When examined through this lens, traditional ensembles showed no meaningful improvement.</em></p><pre>| Model                  | MSE (Extreme Tail) | CVaR Loss (95%)   |<br>| ---------------------- | ------------------ | ----------------- |<br>| Voting Ensemble        | **261,342,966.66** | **54,449,217.86** |<br>| Stacking Ensemble      | **266,652,848.74** | **55,987,445.18** |<br>| CVaR Weighted Ensemble | **260,757,138.35** | **54,281,855.57** |</pre><p><em>Even though stacking had one of the best overall MSE values, it actually performed worst in the catastrophic tail with the highest CVaR.<br>This highlights a core issue:</em></p><p><em>Ensembles trained under standard objectives behave like average optimizers, not risk optimizers.</em></p><p><em>They learn the “middle” exceptionally well, but since catastrophic losses represent only one percent of the dataset, those patterns barely influence the learned structure of the trees.</em></p><p><em>Random Forests tend to vote near the median.<br>Gradient Boosting minimizes typical residuals.<br>XGBoost aggressively fits the densest region of the distribution.</em></p><p><em>None of these choices inherently reflect catastrophic risk.</em></p><h4>Why This Matters for a Risk Aware Framework</h4><p><em>TailRisk is not trying to forecast future claims. Its purpose is to evaluate how models behave under heavy-tailed stress and to design methods that improve robustness in that region.</em></p><p><em>The ensemble results show three important findings:</em></p><ul><li><em>Good overall metrics do not translate to tail reliability</em></li><li><em>Standard ensembling amplifies central patterns but leaves the tail untreated</em></li><li><em>Even ensembles with strong performance still underpredict catastrophic claims</em></li></ul><p><em>This naturally leads to the first modification inside the TailRisk framework:</em></p><p><em>If models differ in how catastrophically they fail, then their ensemble weights should reflect that difference.</em></p><p><em>This is where the CVaR-weighted ensemble comes in.</em></p><h4>CVaR Weighted Ensembling: Prioritizing Models That Fail Less in Catastrophic Scenarios</h4><p><em>Once it became clear that traditional ensembles still suffered from catastrophic underestimation, the next question in the TailRisk framework was simple:</em></p><p><em>If individual models differ in how badly they fail during extreme events, why give them equal or MSE-based weights?</em></p><p><em>A model that behaves well on the rare catastrophic claims should naturally have more influence, and a model that collapses under extreme residuals should contribute less.</em></p><p><em>This motivated a new ensemble design:<br>an ensemble where each model is weighted inversely proportional to its CVaR, so that models with safer tail behavior have higher influence.</em></p><h4>How the CVaR Weighting Works</h4><p><em>First compute residuals for each model:</em></p><p><em>Residual:<br>L = y_true — y_pred</em></p><p><em>Next compute its CVaR at 95 percent:</em></p><p><em>CVaR_95 = average of residuals that exceed the 95th percentile residual</em></p><p><em>Then compute model weights:</em></p><p><em>Raw weight = 1 / CVaR_95</em></p><p><em>Normalize the raw weights so they sum to 1:</em></p><p><em>Final weight = Raw weight / Sum of all raw weights</em></p><p><em>That’s the entire weighting mechanism — clean, interpretable, and directly tied to catastrophic performance.</em></p><h4>Actual CVaR(95%) Residuals From the Models</h4><pre>| Model                          | CVaR(95%)    |<br>| ------------------------------ | ------------ |<br>| Random Forest                  | 3,167.87     |<br>| Gradient Boosting              | 3,167.95     |<br>| XGBoost                        | 3,165.83     |<br>| LaR Weighted Linear Regression | **3,085.73** |</pre><p><em>The LaR-weighted regression is the most conservative model in catastrophic cases, so it deserves a slightly higher weight.</em></p><h4>Final Ensemble Weights (Normalized)</h4><pre>| Model                          | Weight    |<br>| ------------------------------ | --------- |<br>| Random Forest                  | 0.248     |<br>| Gradient Boosting              | 0.248     |<br>| XGBoost                        | 0.248     |<br>| LaR Weighted Linear Regression | **0.255** |</pre><p><em>These numbers are subtle but important:</em></p><ul><li><em>all tree models behave similarly in the tail</em></li><li><em>the LaR model does noticeably better</em></li><li><em>the ensemble automatically reflects this difference</em></li></ul><p><em>This is the first time the TailRisk framework bakes catastrophic behavior into the model weights themselves.</em></p><h4>Performance of the CVaR-Weighted Ensemble</h4><pre>| Metric                  | Value              |<br>| ----------------------- | ------------------ |<br>| MSE (Overall)           | 2,964,293.03       |<br>| MSE (Extreme Tail ≥99%) | **260,757,138.35** |<br>| CVaR Loss (95%)         | **54,281,855.57**  |</pre><p>Compared to Voting and Stacking ensembles:</p><p>✓ Lowest catastrophic tail MSE<br>✓ Lowest CVaR loss<br>✓ More stable behavior on the top 1 percent most expensive claims</p><p>Even if overall MSE is slightly higher than the stacking ensemble, it is far safer in the catastrophic region, which is the entire goal of the TailRisk framework.</p><h4>Meta Learning in TailRisk: Using Model Predictions as Features to Learn Tail Behavior</h4><p><em>Traditional ensembles combine predictions, but they do not learn how different models behave across the claim distribution. Meta learning changes that. Instead of blending predictions directly, TailRisk treats each model’s output as an input feature and trains a second-level learner that can explicitly understand tail structure.</em></p><p><em>This approach is especially valuable in heavy-tailed insurance data because different models fail in different ways. A meta learner can capture those differences and produce a representation that is more sensitive to catastrophic losses.</em></p><h4>How the Meta Features Were Created</h4><p><em>The process used a standard out-of-fold stacking setup:</em></p><ul><li><em>Split training data into 5 folds.</em></li><li><em>For each base model (Random Forest, Gradient Boosting, XGBoost, LaR Regression), train on 4 folds and predict the held-out fold.</em></li><li><em>Collect predictions from all models.</em></li><li><em>These predictions become 4 new features for the meta learner.</em></li></ul><p><em>The final meta feature matrix had:</em></p><p><em>• 55,167 rows x 4 features for training<br>• 13,792 rows x 4 features for testing</em></p><p><em>Each row contains the predictions of the four base models for that sample.</em></p><h4>Correlation of Meta Features With True Claim Severity</h4><pre>| Meta Feature                       | Correlation With Claim Cost |<br>| ---------------------------------- | --------------------------- |<br>| Random Forest Prediction           | 0.0502                      |<br>| Gradient Boosting Prediction       | 0.0599                      |<br>| XGBoost Prediction                 | 0.0483                      |<br>| LaR Weighted Regression Prediction | **0.1521**                  |</pre><p><em>The key insight is clear:</em></p><p><em>The LaR-weighted regression carries far more tail information than any tree model.</em></p><p><em>This higher correlation makes it a crucial feature in the meta learning stage the meta learner now has a way to “see” the tail structure that tree models tend to smooth over.</em></p><h4>TailRisk Meta-Learner 1: Quantile Regression (95th Percentile)</h4><p><em>The first meta learner trains directly on the upper conditional distribution using quantile regression at the 95th percentile.</em></p><p><em>Objective: predict the high-end conditional value of the claim using the four meta features.</em></p><p><em>Loss function:<br>Quantile (pinball) loss with quantile = 0.95.</em></p><p><em>This forces the model to favor conservative, high-end predictions and reduces catastrophic underestimation.</em></p><pre>| Metric                  | Value              |<br>| ----------------------- | ------------------ |<br>| MSE (Overall)           | 5,123,723.49       |<br>| MSE (Extreme Tail ≥99%) | **235,122,968.16** |<br>| CVaR (95%)              | **47,726,774.98**  |</pre><p><em>Although overall MSE increases (expected for a high-quantile model), extreme-tail metrics dramatically improve, especially the CVaR.</em></p><p><em>This demonstrates that quantile regression learns a more cautious, tail-aligned mapping than any ordinary ensemble.</em></p><h4>TailRisk Meta-Learner 2: LaR-Weighted Meta Regression</h4><p><em>This meta learner uses the same four meta features but trains with Loss-at-Risk weighting, meaning samples with large true claim values receive heavier weight.</em></p><p><em>Weight formula (Medium friendly):<br>w = 1 + alpha * (claim_cost / max_claim_cost)<br>with alpha = 2.0</em></p><p><em>This encourages the meta learner to minimize large underprediction errors.</em></p><pre>| Metric                  | Value              |<br>| ----------------------- | ------------------ |<br>| MSE (Overall)           | **2,815,648.85**   |<br>| MSE (Extreme Tail ≥99%) | **259,101,161.14** |<br>| CVaR (95%)              | **53,855,764.63**  |</pre><p><em>This model balances two goals well:</em></p><ul><li><em>strong overall accuracy</em></li><li><em>respectable behavior in the catastrophic tail</em></li></ul><p><em>It does not outperform the quantile model in pure tail conservatism, but it is much more stable across the rest of the distribution.</em></p><h4>Why Meta Learning Matters for TailRisk</h4><p><em>Meta learning:</em></p><ul><li><em>captures diverse model behaviors</em></li><li><em>strengthens tail awareness</em></li><li><em>allows risk-oriented optimization at the second stage</em></li><li><em>produces the strongest candidates for hybridization</em></li></ul><p><em>After analyzing both meta learners, the next step in the TailRisk framework was to combine their complementary strengths.</em></p><p><em>This leads to the final component: the Hybrid TailRisk Model.</em></p><h4>Hybrid Model Selection: Combining Quantile Conservatism with LaR Stability</h4><p><em>The meta-learning stage produced two very different strengths.</em></p><ul><li><em>The 95th-Quantile Meta Learner was the most conservative model in the catastrophic region. It delivered the lowest CVaR and the safest extreme-tail behavior.</em></li><li><em>The LaR-Weighted Meta Learner preserved strong overall accuracy and remained more balanced across the full distribution.</em></li></ul><p><em>Neither model dominated the other.<br>One was safer.<br>One was more accurate.</em></p><p><em>A natural idea emerged:</em></p><p><em>Why not combine them?</em></p><p><em>This became the final step of the TailRisk framework — constructing a hybrid model that blends both perspectives.</em></p><h4>Hybrid Ensemble Formula</h4><p><em>Let:</em></p><p><em>Q = prediction from the quantile meta learner<br>L = prediction from the LaR meta learner<br>lambda = blend parameter between 0 and 1</em></p><p><em>Hybrid prediction:</em></p><p><em>y_hybrid = lambda * Q + (1 — lambda) * L</em></p><p><em>To choose lambda, a composite score was created that emphasizes tail safety:</em></p><p><em>Composite Score = 0.3 * (overall MSE normalized) + 0.7 * (CVaR normalized)</em></p><p><em>This means:</em></p><ul><li><em>30 percent weight on overall accuracy</em></li><li><em>70 percent weight on catastrophic performance</em></li></ul><p><em>That weighting reflects the purpose of the TailRisk framework — prioritizing performance where financial consequences are largest.</em></p><h4>Optimal Blend: lambda = 0.25</h4><p><em>After evaluating multiple values of lambda, the best score was achieved at:</em></p><p><em>lambda = 0.25</em></p><p><em>Meaning the hybrid model uses:</em></p><ul><li><em>25 percent quantile meta learner</em></li><li><em>75 percent LaR meta learner</em></li></ul><p><em>This blend retains the caution of the quantile model without losing the stability and accuracy provided by the LaR meta learner.</em></p><h4>Performance of the Hybrid TailRisk Model</h4><pre>| Metric                  | Value              |<br>| ----------------------- | ------------------ |<br>| MSE (Overall)           | **2,979,449.56**   |<br>| MSE (Extreme Tail ≥99%) | **252,549,888.54** |<br>| CVaR (95%)              | **52,038,832.04**  |</pre><p><em>These numbers are important because the hybrid model:</em></p><p><em>✓ Achieves the lowest catastrophic-tail MSE among all models<br>✓ Achieves a 10.25 percent reduction in CVaR(95%) compared to the baseline<br>✓ Substantially improves detection of high-severity claims<br>✓ Retains strong overall stability across the distribution</em></p><p><em>This makes it the best-performing component in the entire TailRisk framework.</em></p><h4>Why the Hybrid Model Works</h4><p><em>The hybrid model succeeds for three reasons:</em></p><ul><li><em>The quantile learner provides upward pressure<br>It corrects chronic underestimation of large losses.</em></li><li><em>The LaR learner provides structure and stability<br>It keeps predictions reasonable in non-catastrophic regions.</em></li><li><em>The optimized blend captures the best of both<br>The final model is tail conservative without overreacting.</em></li></ul><p><em>This structure also shows the broader message of TailRisk:</em></p><p><em>Tail-aware modeling does not require discarding accuracy.<br>It requires shifting the optimization target.</em></p><h4>Comprehensive Results: Comparing All Models in the TailRisk Framework</h4><p><em>After completing the baseline analysis, tail weighting, CVaR diagnostics, ensembling, meta learning, and hybrid blending, the final step was to compare every model side by side. This gives a complete picture of how each modeling choice behaves in both the average and the catastrophic regions of the distribution.</em></p><p><em>The following table summarizes every major model evaluated in TailRisk.<br>All numbers come directly from the final TailRisk paper.</em></p><pre>| Model                                     | MSE (Overall)    | MSE (Extreme Tail ≥99%) | CVaR (95%)        |<br>| ----------------------------------------- | ---------------- | ----------------------- | ----------------- |<br>| **Baseline Models**                       |                  |                         |                   |<br>| Linear Regression (MSE baseline)          | 2,808,590.91     | 260,918,452.66          | 54,351,581.35     |<br>| LaR Weighted Linear Regression            | 2,815,523.76     | 259,123,206.25          | 53,861,768.98     |<br>| **Traditional Ensembles**                 |                  |                         |                   |<br>| Voting Ensemble                           | 3,086,548.69     | 261,342,966.66          | 54,449,217.86     |<br>| Stacking Ensemble                         | 2,866,240.41     | 266,652,848.74          | 55,987,445.18     |<br>| CVaR Weighted Ensemble                    | 2,964,293.03     | 260,757,138.35          | 54,281,855.57     |<br>| **Tail-Focused Meta Learners**            |                  |                         |                   |<br>| Quantile Meta Learner (95th)              | 5,123,723.49     | 235,122,968.16          | 47,726,774.98     |<br>| Loss-at-Risk Meta Learner                 | 2,815,648.85     | 259,101,161.14          | 53,855,764.63     |<br>| **Hybrid TailRisk Model (lambda = 0.25)** | **2,979,449.56** | **252,549,888.54**      | **52,038,832.04** |</pre><p><em>1. Baseline models perform reasonably in aggregate, but poorly in the catastrophic tail.</em></p><p><em>They achieve low overall MSE but consistently underestimate high-severity events.</em></p><p><em>2. Traditional ensembles improve overall accuracy but worsen tail behavior.</em></p><p><em>Both stacking and voting appear strong on average, yet struggle even more in the top 1 percent losses.</em></p><p><em>3. The quantile meta learner is the safest model in pure tail conservatism.</em></p><p><em>It has the lowest CVaR and significantly better extreme-tail MSE, but sacrifices overall performance.</em></p><p><em>4. The LaR meta learner strikes a balance.</em></p><p><em>It retains strong overall MSE while still improving tail sensitivity.</em></p><p><em>5. The Hybrid TailRisk Model is the best overall candidate.</em></p><p><em>It achieves:</em></p><p><em>• Lowest catastrophic MSE<br>• Significant reduction in CVaR<br>• Improved recognition of extreme-loss patterns<br>• Strong overall stability</em></p><p><em>The hybrid is not the most accurate on average (that honor goes to standard stacking), nor the most conservative in isolation (the quantile meta learner wins that).<br>But it is the best compromise, prioritizing catastrophic reliability without collapsing elsewhere.</em></p><h4>Why These Results Matter</h4><p><em>The TailRisk framework is not built for forecasting future claims.<br>It is built to evaluate and improve model behavior in catastrophic regions — regions where traditional performance metrics hide the real risk.</em></p><p><em>This comprehensive comparison shows that:</em></p><p><em>• optimizing purely for accuracy is not enough<br>• optimizing purely for conservatism is too costly<br>• frameworks that blend risk-sensitive components outperform both extremes</em></p><p><em>TailRisk’s strength comes from combining diagnostic tools (LaR, CVaR) with modeling strategies (meta learning, hybrid weighting) to systematically push models toward safer behavior under heavy-tailed conditions.</em></p><h4>Tail-Focused Validation: Measuring Improvements Where It Matters Most</h4><p><em>Evaluating catastrophic-region performance requires metrics that highlight the upper tail instead of the average case. In TailRisk, validation focuses on four critical indicators:</em></p><p><em>• Extreme-tail MSE (≥99th percentile)<br>• CVaR(95%) of residuals<br>• Detection rate of high-severity claims<br>• Tail Coverage Ratio (TCR)</em></p><p><em>These metrics measure how often a model recognizes a high-severity event and how badly it underpredicts when it misses.</em></p><p><em>Below is the final validation table comparing the baseline model to the Hybrid TailRisk Model.</em></p><h4>TailRisk Validation Table</h4><pre>| Metric                       | Baseline       | Hybrid             | Improvement      |<br>| ---------------------------- | -------------- | ------------------ | ---------------- |<br>| MSE (99%+ Catastrophic Tail) | 260,918,452.66 | **252,549,888.54** | **+3.21%**       |<br>| CVaR (95%) Residual          | 3,146.32       | **2,823.91**       | **+10.25%**      |<br>| Detection Rate @ 90%         | 3.08%          | **6.09%**          | **+3.01 points** |<br>| Detection Rate @ 95%         | 0.83%          | **2.47%**          | **+1.64 points** |<br>| Tail Coverage Ratio @ 95%    | 0.165          | **0.306**          | **+0.141**       |<br>| Tail Coverage Ratio @ 99%    | 0.058          | **0.102**          | **+0.044**       |</pre><h4>What These Improvements Mean</h4><p><em>1. Extreme-tail MSE dropped</em></p><p><em>This means the hybrid model underestimates catastrophic losses less severely than the baseline.</em></p><p><em>2. CVaR(95%) decreased by over 10 percent</em></p><p><em>This is the most important result: the average magnitude of the worst residuals is significantly smaller.<br>In stress scenarios, the hybrid model fails less catastrophically.</em></p><p><em>3. Detection rates more than doubled</em></p><p><em>The hybrid model identifies high-severity events earlier and more frequently, reducing blind-spot failures.</em></p><p><em>4. Tail Coverage Ratios increased substantially</em></p><p><em>This metric reflects how much of the true tail mass the model captures.<br>Higher TCR values mean the model’s predictions actually align with the catastrophic distribution shape.</em></p><p><em>Together, these metrics confirm that TailRisk meaningfully improves model robustness where it matters most not in the center, but at the extreme edges of risk.</em></p><h4>Conclusion</h4><p><em>The TailRisk framework began with a simple but often overlooked realization: traditional models trained under Mean Squared Error are designed to predict what is common, not what is consequential. In insurance severity modeling, where a handful of catastrophic claims drive most of the financial exposure, this creates a systematic blind spot.</em></p><p><em>By developing Loss-at-Risk weighting, integrating Conditional Value-at-Risk as a diagnostic layer, evaluating ensemble models under tail stress, constructing meta-learners that explicitly encode extreme-loss behavior, and finally blending them into a hybrid model, TailRisk offers a structured way to measure and enhance robustness in heavy-tailed environments.</em></p><p><em>This framework is not a forecasting system and does not claim to predict the exact severity of rare losses. Instead, it quantifies how models behave when exposed to catastrophic scenarios and provides mechanisms to improve their conservatism without sacrificing overall stability. The Hybrid TailRisk Model demonstrates that it is possible to reduce extreme-tail MSE, lower catastrophic residuals, and increase detection of high-severity claims all without overfitting the rarest events.</em></p><p><em>As insurance datasets continue to grow and tail events become more relevant under modern risk landscapes, frameworks like TailRisk help bridge the gap between statistical accuracy and financial resilience. They shift the modeling objective from minimizing typical error to understanding how models behave when everything goes wrong.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81669725ebb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tail Risk: “Why Average-Based Models Miss Catastrophic Losses”]]></title>
            <link>https://medium.com/@lvishal1607/tail-risk-why-average-based-models-miss-catastrophic-losses-34870f6ace1e?source=rss-668cf5ab8335------2</link>
            <guid isPermaLink="false">https://medium.com/p/34870f6ace1e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tail-risk]]></category>
            <category><![CDATA[insurance]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <dc:creator><![CDATA[Vishal Lakshmi Narayanan]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 16:01:27 GMT</pubDate>
            <atom:updated>2025-11-12T16:03:23.477Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>The Invisible Catastrophe Inside “Accurate” Models</em></h4><p><em>When you train a forecasting model, it’s easy to trust the metrics that sparkle low MSE, high R², neat charts. But what if the model that looks most accurate on paper is also the one most likely to bankrupt an insurer?</em></p><p><em>That question kicked off Tail Risk: a project exploring how to make forecasting models see the invisible side of data: the rare, high-cost events that distort entire portfolios. Instead of celebrating average performance, the goal is to teach the model to “care” about the catastrophic tail, the few claims that decide whether a company survives a bad year.</em></p><p><em>This first phase begins with the uncomfortable realization that the Mean Squared Error (MSE) metric, trusted by nearly every regression pipeline, quietly ignores the disasters hidden at the far edge of the loss distribution.</em></p><h4><em>The Baseline That Failed Gracefully</em></h4><p><em>The starting point was a clean, familiar workflow: fit a linear regression model on about 69 k automobile insurance policies from the Mendeley dataset and measure how well it predicted yearly claim costs.</em></p><p><em>Data source : [ </em><a href="https://data.mendeley.com/datasets/5cxyb5fp4f/2"><em>https://data.mendeley.com/datasets/5cxyb5fp4f/2</em></a><em>]</em></p><p><em>The first pass looked promising on paper.<br>The Mean Squared Error (MSE) sat around 2.8 million $² not perfect, but decent for such a wide range of claim values.</em></p><p><em>Then I plotted the predictions.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*V4PSkQ7evjyDznSbm6x7-A.png" /></figure><p><em>Almost every point hugged the origin. The model handled the easy part, the majority of policies with zero or tiny claims perfectly.<br>But zooming out revealed the truth: a handful of extreme losses were completely missed. The model predicted $200 for a claim that actually cost $120 000.</em></p><p><em>The EDA confirmed it:</em></p><ul><li><em>70 % of policies had negligible annual claim costs.</em></li><li><em>The top 1 % of claims drove most of the variance.</em></li><li><em>The loss distribution was severely right-skewed, with a long, heavy tail.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*cNLIdDxKHpd-FggrCKEN2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*kBFykyrrNduYLswiEHHZsQ.png" /></figure><p><em>At first glance, the log-transformed target smoothed things out and improved correlations with features like Premium, Value_vehicle, and historical claim rates.<br>But this compression came at a price it flattened the catastrophes, reducing their visibility in the optimization.</em></p><pre>Feature            Raw Corr.   Log Corr.<br>-----------------------------------------<br>R_Claims_history     0.153       0.514<br>N_claims_history     0.034       0.142<br>Premium              0.050       0.086<br>Length               0.019       0.069<br>Weight               0.019       0.067<br>Value_vehicle        0.026       0.061<br>Cylinder_capacity    0.013       0.054<br>Power                0.023       0.045<br>Seniority           -0.054      -0.213</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnM-NmL5F1OA20VK-OPdmw.png" /></figure><p><em>Even though the model appeared statistically sound, the financial reality was wrong. It was tuned to predict the middle of the curve, not the edges, a dangerous blind spot in risk forecasting.</em></p><p><em>The takeaway: traditional MSE-based regression is an expert at predicting what’s common, and a novice at handling what’s costly. That gap became the motivation for designing a new loss function that weights the tail more heavily Loss-at-Risk (LaR).</em></p><h4><em>Introducing Loss-at-Risk</em></h4><p><em>Once the baseline model exposed its weakness, the next step was to rethink how the loss function itself behaves.</em></p><p><em>If Mean Squared Error treats every prediction error equally, then a $10 mistake on a small claim is penalized just as much as a $10 000 mistake on a $100 000 claim. That’s mathematically fair but financially absurd.</em></p><p><em>The idea behind Loss-at-Risk (LaR) was simple:<br>teach the model to care more about what costs more.</em></p><p><strong><em>The Core Idea:</em></strong></p><p><em>Instead of a uniform penalty, each sample gets a weight proportional to its claim size:</em></p><p><em>wᵢ = 1 + α · (yᵢ / max(y))</em></p><p><em>where<br>• yᵢ = true claim amount<br>• α = tail-sensitivity factor controlling how much weight large claims get</em></p><p><em>When α = 0, LaR behaves exactly like ordinary MSE.<br>As α increases, high-value claims dominate the learning process, forcing the model to pay attention to the upper tail of the loss distribution.</em></p><p><strong><em>Intuitive Example:</em></strong></p><p><em>Imagine two policies:</em></p><p><em>Policy A: true = $200, predicted = $150</em></p><p><em>Policy B: true = $50 000, predicted = $30 000</em></p><p><em>Under MSE, the second error (–$20 000) seems huge but, squared, it’s only 400× larger and yet the financial consequence is 250× greater. LaR rebalances that mismatch by multiplying the large-claim error by a heavier weight.</em></p><p><strong><em>Early Experiments</em></strong></p><p><em>The first experiment used α = 0.5.<br>Even without changing the architecture, the weighted model’s Loss-at-Risk value climbed from<br>2 808 590 → 3 540 791, revealing that catastrophic claims finally started to matter inside the optimization.<br>In other words, the model’s apparent performance got “worse” numerically — but more honest financially.</em></p><p><em>Takeaway: Loss-at-Risk shifts the learning goal from minimizing average error to minimizing regret under extreme loss.It rewards conservative predictions and penalizes under-estimation of large claims — a small trade-off for avoiding catastrophic blind spots.</em></p><h4>Evaluating Tail Sensitivity: How the Model Learns to Fear Extremes</h4><p><em>Once the Loss-at-Risk function was in place, the next question was simple:<br>How much tail-awareness is enough?</em></p><p><em>To test this, I tuned the sensitivity factor α over multiple values from 0.1 to 2.0 while keeping the model and features identical.Each run adjusted how aggressively the model weighted catastrophic claims.</em></p><p>For every α value, the model was trained using the same formula:</p><blockquote>wᵢ = 1 + α · (yᵢ / max(y))</blockquote><p>where higher α values amplify the weight of high-severity events.<br>This means that at α = 2.0, the largest claims dominate optimization forcing the model to become ultra-conservative about extreme losses.</p><pre>| α Value | MSE (Extreme Claims) | Loss-at-Risk (Overall) |<br>| ------- | -------------------- | ---------------------- |<br>| 0.1     | 2.608 × 10⁸          | 3.5408 × 10⁶           |<br>| 0.3     | 2.606 × 10⁸          | 3.5409 × 10⁶           |<br>| 0.5     | 2.604 × 10⁸          | 3.5412 × 10⁶           |<br>| 0.7     | 2.602 × 10⁸          | 3.5416 × 10⁶           |<br>| 1.0     | 2.600 × 10⁸          | 3.5423 × 10⁶           |<br>| 2.0     | 2.591 × 10⁸          | 3.5462 × 10⁶           |</pre><p><em>What This Means</em></p><p><em>As α increases, the model steadily reduces its Mean Squared Error on extreme claims meaning it’s getting better at predicting the rare, high-loss cases.<br>At the same time, the overall LaR metric slightly rises, confirming that the optimization is shifting energy toward catastrophic rather than common events.</em></p><p><em>Even small numerical gains in the 99th-percentile range have outsized financial impact: for insurers, a 0.5–1 % improvement in tail accuracy can translate to millions in more precise capital allocation.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vh9HnsrqXUen3OpZscP5mA.png" /></figure><h4>Measuring True Risk Exposure with Conditional Value-at-Risk (CVaR)</h4><p><em>While the Loss-at-Risk framework made the model more sensitive to catastrophic claims, one big question remained: How bad do things get when the model is wrong really wrong?</em></p><p><em>To quantify that, I used a metric borrowed from quantitative finance: Conditional Value-at-Risk (CVaR) also known as Expected Shortfall. It measures the average size of the model’s worst underpredictions the “pain zone” beyond a chosen confidence level.</em></p><p><strong><em>What CVaR Means (Plainly)</em></strong></p><p><em>If MSE tells you your average error, and LaR tells you your weighted error,<br>then CVaR tells you the average size of your worst errors, the ones that happen in the rarest, most expensive situations.</em></p><p><em>Let the model residuals be defined as:</em></p><blockquote><em>Lᵢ = yᵢ — ŷᵢ</em></blockquote><p><em>Here,</em></p><p><em>yᵢ → actual claim cost</em></p><p><em>ŷᵢ → model prediction</em></p><p><em>Lᵢ → residual (underprediction if positive)</em></p><p><strong><em>At a confidence level α, the Value-at-Risk (VaR) and Conditional Value-at-Risk (CVaR) are computed as:</em></strong></p><blockquote><em>VaRₐ = Quantile[L, α]<br>CVaRₐ = Mean[Lᵢ | Lᵢ ≥ VaRₐ]</em></blockquote><p><em>VaR (Value-at-Risk) marks the cutoff for the worst α fraction of residuals.</em></p><p><em>CVaR gives the expected magnitude of those worst residuals essentially asking, </em>“When the model misses, how bad are its misses?”</p><pre>| Metric          | Description                                                     | Value ($)     |<br>| --------------- | --------------------------------------------------------------- | ------------- |<br>| VaR (99 %)      | Residual threshold marking the start of the worst 1 % of errors | 3 637.83      |<br>| CVaR (99 %)     | Average underprediction within that 1 % worst zone              | 10 100.89     |</pre><p><strong><em>Interpretation</em></strong></p><p><em>At a 99 % confidence level, the baseline model underpredicts true claim costs by more than $ 3 600 in its worst 1 % of cases and once it crosses that line, it underestimates by an average of $ 10 100.</em></p><p><em>That number captures something MSE never could, how much financial damage is hidden in the tail. Even a model that looks “accurate” overall may still bleed money when rare events strike.</em></p><p><em>CVaR exposes that hidden volatility.</em></p><p><strong><em>Why CVaR Matters</em></strong></p><p><em>For insurers, this isn’t just a statistical curiosity it’s an operational alarm.<br>If your model’s CVaR is too high, you’re underestimating reserve risk and capital exposure.CVaR helps build an actuarially safer model one that doesn’t just look good in aggregate, but stays honest under crisis conditions.</em></p><h4>Comparing Tail Loss Under CVaR: Baseline vs Loss-at-Risk</h4><p><em>After introducing the Loss-at-Risk weighting, the next step was to see whether the model truly reduced catastrophic underpredictions. To measure that, I applied a Conditional Value-at-Risk (CVaR) Loss a variant of CVaR that computes the average squared error in only the worst fraction of residuals.</em></p><p><em>This approach focuses exclusively on how the model behaves under stress when it encounters the rare, high-impact claim events that define real-world risk.</em></p><p><em>Defining the CVaR Loss Function</em></p><p><em>Let the residuals be:</em></p><blockquote><em>Lᵢ = yᵢ — ŷᵢ</em></blockquote><p><em>For a chosen confidence level α (e.g., 0.95 for the worst 5 %),<br>the CVaR Loss is computed as:</em></p><blockquote><em>L_CVaR = (1 / N_tail) * Σ[(yᵢ — ŷᵢ)² for all Lᵢ ≥ VaRₐ]</em></blockquote><p><em>where:</em></p><p><em>VaRₐ = Quantile(L, α) → the cutoff defining the worst α fraction of residuals</em></p><p><em>N_tail → the number of samples beyond that threshold</em></p><p><em>This tells us how much squared error the model accumulates only in the catastrophic zone — the part that hurts the most financially.</em></p><pre>| **Model**              | **MSE (Overall)** | **CVaR (95 % Tail)** | **Change (%)** |<br>| ---------------------- | ----------------: | -------------------: | -------------: |<br>| Baseline Regression    |       2.808 × 10⁶ |          5.435 × 10⁷ |              — |<br>| Loss-at-Risk (α = 2.0) |      2.591 × 10⁸* |      **5.386 × 10⁷** |     **−0.9 %** |</pre><p><em>The CVaR Loss values are significantly higher than overall MSE, confirming that most of the model’s error energy lies within the extreme tail. When evaluated on the worst 5 % of predictions, the Loss-at-Risk model reduced tail loss by about 0.9 % without sacrificing stability across the rest of the distribution. While this improvement may appear minor numerically, it represents meaningful financial protection for insurers handling millions in exposure, where even fractional gains translate to substantial resilience during rare, high-impact events. In essence, CVaR-based evaluation rewards crisis readiness rather than average precision producing models that minimize the cost of worst-case misses instead of chasing mean accuracy. By pairing CVaR with Loss-at-Risk training, we bridge the gap between statistical performance and financial prudence, creating forecasting systems that are not only accurate but also prepared for catastrophe.</em></p><p><em>This stage of the project revealed a hard truth: average accuracy hides systemic risk. The baseline MSE model looked statistically solid but financially blind confident where it shouldn’t be, and silent when the stakes were highest. By introducing Loss-at-Risk, the model began to recognize what truly matters: not the majority of small claims, but the few catastrophic ones that define survival.<br>Adding Conditional Value-at-Risk completed the picture, showing how severe those worst-case misses really are.</em></p><p><em>Together, these insights shift the focus from precision to resilience from minimizing typical errors to understanding how models behave when everything goes wrong.</em></p><p><em>The path forward is to evolve this foundation into a risk-aware ensemble that blends multiple learners while weighting them by their tail reliability.<br>Upcoming work will explore:</em></p><ul><li><em>Adaptive α tuning within the Loss-at-Risk framework.</em></li><li><em>Embedding CVaR objectives directly into model optimization.</em></li><li><em>Comparing ensemble stability across low, high, and extreme claim regions.</em></li></ul><p><em>The goal is simple: move beyond predicting the expected toward models that anticipate the unexpected.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34870f6ace1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Tempe’s Microburst Exposed the Hidden Vulnerability of Our Urban Forest]]></title>
            <link>https://medium.com/@lvishal1607/how-tempes-microburst-exposed-the-hidden-vulnerability-of-our-urban-forest-4c71166f7e06?source=rss-668cf5ab8335------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c71166f7e06</guid>
            <category><![CDATA[tempe]]></category>
            <category><![CDATA[urban-planning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[trees]]></category>
            <dc:creator><![CDATA[Vishal Lakshmi Narayanan]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 15:00:58 GMT</pubDate>
            <atom:updated>2025-10-17T15:00:58.137Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Storm That Wasn’t a Hurricane</h4><p><em>It wasn’t a hurricane.<br>It wasn’t a tornado.<br>It was something more deceptive, a microburst, a column of sinking air that unleashed 90-mph straight-line winds across Tempe in mid-October 2025.</em></p><p><em>In just minutes, the storm uprooted hundreds of mature trees, tore apart roofs, and left neighborhoods along Southern Avenue and Kyrene Road looking like a war zone.</em></p><p><em>And yet, behind the visible wreckage lies an even bigger story, one told through data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Mp0OrnFKlAVpy7O8qIqeQ.jpeg" /><figcaption>Damages after the Tempe Microburst</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBM74R8UhSUTzq3qi7-mYQ.jpeg" /><figcaption>Image courtesy: Twitter (Public Source)</figcaption></figure><h4>The Data Beneath the Damage</h4><p><em>Tempe’s Tree Inventory from Tempe government (</em><a href="https://data.tempe.gov/datasets/tempegov::tree-inventory/about"><em>https://data.tempe.gov/datasets/tempegov::tree-inventory/about</em></a><em>) tells the story of just how much we had and how much we lost.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L09FKVNOB66OLoeKnRG5ag.png" /><figcaption>Summary metrics calculated from the data</figcaption></figure><p><em>Every tree was doing work, cooling the city, holding the soil, cleaning the air.<br>When they fell, it wasn’t just wood that broke. We lost shade, stability, and balance.</em></p><h4>Using Data to Rebuild Smarter</h4><p><em>Right now, Tempe is cleaning up.<br>But the real question is, why were some parts of the city hit so much harder than others?</em></p><p><em>To find out, I visualized Tempe’s Tree Inventory on an interactive map, plotting more than 26,000 trees across the city.<br>Each point represents a tree, color-coded by its risk level based on canopy diameter:</em></p><ul><li><em>Green: low-risk, smaller trees</em></li><li><em>Orange: medium-risk</em></li><li><em>Red: high-risk, large mature trees</em></li></ul><p><em>As the map loaded, two clear patterns emerged.</em></p><p><em>The first cluster appeared around Maple–Ash and the downtown Tempe corridor, where large, mature trees line older residential streets.<br>The second, even denser cluster stretched along Southern Avenue and Kyrene Road, the same corridor that the microburst tore through.</em></p><p><em>Both regions share similar traits: tall canopies, limited root space due to nearby pavement, and dense planting in narrow medians.<br>In other words, the very trees that make these areas beautiful and shaded are also the most structurally vulnerable when exposed to straight-line winds.</em></p><p><em>By mapping these patterns, it became clear that the storm’s path wasn’t random.<br>It followed where size, age, and urban design overlapped, revealing that Tempe’s greatest shade zones are also its weakest points during extreme weather.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*hKATLOCvCeppUwCwIu_aMA.png" /><figcaption>Tempe Trees Vulnerability Spots</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*lhGSYqdue2x-36GSgWa3cw.png" /><figcaption>Denser cluster stretched along Southern Avenue and Kyrene Road</figcaption></figure><h4>What the Trend Lines Show</h4><p><em>To see where size and risk shift geographically, I plotted average tree diameter by latitude.<br>The trend revealed a subtle but important pattern:</em></p><ul><li><em>Northern Tempe, with older neighborhoods, shows larger trees and denser canopy cover.</em></li><li><em>The southern regions — including the microburst’s core zone between 33.38° and 33.41° latitude feature smaller, younger trees.</em></li></ul><p><em>This alignment matters.<br>The storm’s path crossed directly through one of the city’s oldest and densest tree zones where size translated to vulnerability.</em></p><p><em>Green segments in the trend chart indicate areas with increasing canopy size, while red segments show thinning or younger growth.<br>That red-green shift, right through the microburst corridor, visually captures how the storm interacted with Tempe’s landscape.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rd_9PUhhWoBLu0EGV-w5Lg.png" /><figcaption>Trend line graph Avg Tree Diameter vs Latitude in Tempe region</figcaption></figure><h4>Why This Matters</h4><p><em>Urban trees aren’t just greenery they’re part of city infrastructure.<br>They regulate temperature, improve air quality, and store carbon.<br>But as cities like Tempe continue to age, tree vulnerability becomes a measurable risk one that can be mapped, predicted, and mitigated.</em></p><p><em>This analysis highlights how open datasets and simple spatial visualization can help cities plan smarter:</em></p><ul><li><em>Identify where tree replacement should prioritize diversity and stability.</em></li><li><em>Target high-risk corridors for pruning and reinforcement.</em></li><li><em>Use canopy data to strengthen future climate resilience.</em></li></ul><p><em>The takeaway is simple: the next microburst is inevitable but the scale of its damage doesn’t have to be.</em></p><p><em>The full dataset, analysis code, and interactive dashboard are available on GitHub:<br>github.com/VishalLakshmiNarayanan/TempeMicroburst</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c71166f7e06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building “MAILY”: An AI-Powered Mail & Calendar Assistant Using n8n]]></title>
            <link>https://medium.com/@lvishal1607/maily-building-maily-an-ai-powered-mail-calendar-assistant-using-n8n-43315f153708?source=rss-668cf5ab8335------2</link>
            <guid isPermaLink="false">https://medium.com/p/43315f153708</guid>
            <category><![CDATA[agent-ai-chat-bot]]></category>
            <category><![CDATA[n8n-workflow-automation]]></category>
            <category><![CDATA[mail]]></category>
            <category><![CDATA[n8n]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Vishal Lakshmi Narayanan]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 06:39:54 GMT</pubDate>
            <atom:updated>2025-06-19T06:45:55.421Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p><em>Managing emails and setting calendar events are essential — but often time-consuming — daily tasks. As someone always exploring ways to integrate AI with productivity, I recently built a smart assistant I call MAILY using n8n, a powerful no-code/low-code automation tool.</em></p><p><strong><em>MAILY is an AI-powered workflow that can:</em></strong></p><p><em>*Understand natural language instructions,</em></p><p><em>*Automatically send emails,</em></p><p><em>*Check contact databases,</em></p><p><em>*And even schedule calendar events based on conversation.</em></p><p><em>This article walks through how I built this workflow using n8n, integrated it with Gmail, Google Calendar, and Groq’s LLM, and turned a simple idea into a fully functional AI assistant.</em></p><p><em>If you’re curious about building personal agents with natural conversation flow, real-world utility, and automated decision-making, this is for you.</em></p><h3><strong>Tools Used</strong></h3><p><em>To build MAILY, I combined powerful no-code tools with smart AI integrations. Here’s a breakdown of the components used:</em></p><p><strong><em>n8n — Workflow Automation</em></strong><em><br>n8n is a powerful, open-source workflow automation tool. It lets you visually design logic flows, connect APIs, and automate interactions between apps — without writing heavy backend code.</em></p><p><strong><em>Groq — LLM for Natural Language Understanding</em></strong><em><br>I used Groq’s blazing-fast LLM to interpret user instructions, extract intent (e.g., send mail vs. set calendar event), and respond naturally.</em></p><p><strong><em>Google Sheets — Contact Database</em></strong><em><br>I stored all contact names and emails in a Google Sheet. MAILY references this sheet to validate if a recipient exists before sending emails.</em></p><p><strong><em>Gmail API — Sending Emails</em></strong><em><br>MAILY uses the Gmail node in n8n to compose and send emails dynamically based on the user’s instructions.</em></p><p><strong><em>Google Calendar API — Scheduling Events</em></strong><em><br>MAILY can also parse phrases like “schedule a call tomorrow at 6 PM” and create a corresponding event in Google Calendar — automatically.</em></p><p><strong><em>Simple Memory — Context Retention</em></strong><em><br>To manage multi-turn interactions, MAILY uses Simple Memory nodes that remember user names, preferences, and prior steps across a conversation session.</em></p><h3><strong>What is MAILY?</strong></h3><p><em>MAILY is an AI-powered mail and calendar assistant built within an n8n workflow. It functions as a conversational agent capable of understanding natural language commands, extracting relevant details like recipient names, intent, and time references, and then autonomously executing actions such as sending emails, checking contact availability, or scheduling events. It integrates Groq’s language model for interpreting user input, Google Sheets for contact lookup, Gmail for message dispatch, and Google Calendar for event creation. Additionally, MAILY leverages memory to retain user context across interactions, making it a dynamic and intelligent tool for streamlining daily communication tasks.</em></p><h3><strong>Workflow Architecture</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*hlxJhcpQSN3NCwVoNTXAvQ.png" /><figcaption><strong>n8n Workflow for the MAILY Model</strong></figcaption></figure><p><em>The workflow begins with the Chat Trigger node, which listens for a user message to initiate the flow. This message is passed to the central logic block named MAILY, which is the core AI assistant handling task routing and execution. MAILY is connected to multiple external and internal services, each serving a specific function in the pipeline.</em></p><p><em>The Groq node is the AI model responsible for natural language understanding. It interprets user inputs, extracts intent (like sending an email or setting a meeting), and passes structured information to the rest of the flow. The Simple Memory node works alongside it to store and recall key details across the conversation — for example, remembering the user’s name, previously mentioned contacts, or pending actions.</em></p><p><em>Next, based on the interpreted intent, MAILY connects to one of the external service tools:</em></p><p><em>*The Google Calendar node is used to create events when the intent includes date and time.</em></p><p><strong><em>*</em></strong><em>The Gmail node handles sending emails to the specified recipient.</em></p><p><strong><em>*</em></strong><em>The Contacts (Google Sheets) node checks if the email address of the recipient exists in the contact database before taking action.</em></p><p><em>Each tool is modular, meaning the workflow can be extended with additional nodes like Slack, Telegram, or databases as needed. The structure is clean, logical, and highly scalable, allowing MAILY to act as a reliable assistant across multiple communication channels.</em></p><h3>MAILY in Action</h3><p><em>Once MAILY is deployed, interacting with it feels just like messaging a human assistant. Here’s a sample interaction that showcases its end-to-end functionality:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*xt6xr854MwcrJM6a5ghvIw.png" /><figcaption>Chat Window of MAILY</figcaption></figure><p><em>In this exchange, MAILY identifies the task (send mail), parses the recipient’s name, verifies the email address from the contact database, and executes the email dispatch — all automatically. The conversation also highlights MAILY’s ability to confirm preconditions (like contact existence) before proceeding, ensuring reliability and safety in communication.</em></p><p><em>This example reflects how natural and seamless the user experience becomes when multiple automation tools and AI reasoning are combined effectively.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*4zVbpdWsIVwTbaDQKeEoiQ.png" /><figcaption>Mail Snapshot</figcaption></figure><h3>What Makes MAILY Powerful?</h3><p><em>MAILY isn’t just a script that sends emails — it’s a smart assistant with contextual awareness and modular automation. Its strength lies in combining conversational intelligence with action-based triggers. With Groq’s LLM at its core, MAILY can parse user instructions accurately, even when phrased naturally. The memory layer helps it recall user preferences and past messages, enabling dynamic follow-ups. Its integration with Google services makes it not only powerful but also practical for real-world productivity. Whether you’re managing a daily schedule, checking on a colleague, or coordinating meetings, MAILY removes friction and gives you a hands-free assistant experience — all built using n8n’s flexible, no-code environment.</em></p><h3>Future Enhancements</h3><p><em>MAILY is just the beginning of what’s possible when AI agents are paired with automation tools. Some planned enhancements include adding Slack and Telegram integration for multi-platform availability, enabling contact creation directly through chat, and using voice input via speech-to-text APIs. More advanced upgrades could involve email summarization, smart replies, or even sentiment-aware follow-ups. With n8n’s extensibility, adding CRMs, internal databases, or real-time alerts becomes straightforward, turning MAILY into a full-fledged AI operations assistant.</em></p><h3><strong>Conclusion</strong></h3><p><em>MAILY demonstrates how accessible and powerful AI-driven automation has become. With just a few connected nodes in n8n, a Groq LLM, and basic Google tools, I was able to build a personal assistant that can talk, think, and take action. It replaces routine tasks with smart workflows and brings the concept of AI agents into your daily productivity toolkit. If you’re looking to build your own assistant, automate conversations, or experiment with LLM integrations, MAILY is a great project to start with — and even better to grow from.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43315f153708" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting the Undetectable: Building a Hybrid AI System Against Phishing Sites]]></title>
            <link>https://medium.com/@lvishal1607/detecting-the-undetectable-building-a-hybrid-ai-system-against-phishing-sites-a7d5e6c2daba?source=rss-668cf5ab8335------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7d5e6c2daba</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[phising]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[cyber-security-awareness]]></category>
            <dc:creator><![CDATA[Vishal Lakshmi Narayanan]]></dc:creator>
            <pubDate>Sat, 19 Apr 2025 00:04:04 GMT</pubDate>
            <atom:updated>2025-04-19T00:04:04.830Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p><em>Phishing attacks are evolving. They’re no longer just shady URLs with obvious typos — now, they impersonate brands with polished webpages that trick even the trained eye. I decided to tackle this challenge by blending two powerful approaches: classic machine learning (ML) and large language models (LLMs).</em></p><p><em>This is a breakdown of the system I built — why I chose a hybrid approach, how I designed the architecture, and what kind of results I achieved.</em></p><h4>Why ML Alone Isn’t Enough</h4><p><em>Initially, I trained several machine learning models like Random Forest and XGBoost on large phishing datasets. They performed great when it came to catching common patterns — suspicious characters, short domain ages, IP-based URLs, etc.</em></p><p><em>But I ran into cases where these models failed.</em></p><p><em>One notable example was </em><strong><em>12voltdoesit.com</em></strong><em>—its structure looked clean. Every ML model misclassified it as legitimate. That&#39;s when I realized phishing isn&#39;t always visible in the URL. Sometimes, it’s hidden in </em><strong><em>the semantics of the page</em></strong><em>—the language, the layout, and the calls to action.</em></p><h4>LLM vs ML/DL</h4><p><em>To better understand the strengths and limitations of each approach, I compared traditional ML/DL models with LLM-based detection across several aspects. ML models rely on structured URL features and metadata, offering fast and lightweight inference with high precision. However, they often fail to generalize to new or cleverly disguised phishing tactics, leading to false negatives — like misclassifying 12voltdoesit.com as safe. On the other hand, LLMs analyze webpage content and semantics, allowing them to detect subtle cues like brand impersonation or obfuscated text (e.g., replacing “Login” with “L0gin”). While they require more compute and have latency due to token limits and API calls, their adaptability and semantic reasoning significantly boost recall and resilience against unseen phishing techniques. This trade-off makes LLMs an essential addition to any modern phishing detection system.</em></p><figure><img alt="Comparison Table" src="https://cdn-images-1.medium.com/max/417/1*AoiJsey7-JJkJrDgdm8cnQ.png" /><figcaption>Comparison: LLM vs ML/DL</figcaption></figure><h4>Building the System</h4><p><em>This led me to build a two-layered approach:</em></p><ol><li><em>The ML layer handles quick predictions based on URL structure.</em></li><li><em>2. The LLM layer dives into the semantic meaning of the page</em></li></ol><p><strong><em>Datasets Used:</em></strong></p><p><em>1.Phishing Webpage Dataset: 11,430 balanced samples with 87 features covering URL structure, page content, and external queries.</em></p><p><em>2.Kaggle Dataset: 662,591 URLs with 10 structural features; highly imbalanced and ideal for testing resampling techniques like SMOTE.</em></p><p><em>3.Adversarial Phishing Webpages (APW): Contains complex phishing sites designed to bypass ML models; used to evaluate robustness.</em></p><p><em>4.Adversarial Logo Dataset: Helps detect brand impersonation through deceptive logo use, supporting content-level phishing detection.</em></p><h4>System Design and Implementation</h4><p><em>Supervised Machine Learning (SML) models are extensively used for phishing detection, mostly categorizing websites based on their URLs. This research evaluated several Machine Learning models to determine their efficacy in website classification. Data augmentation techniques, including SMOTE, were used, and both Machine Learning and Deep Learning models were applied for classification tasks.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*YIoZybcHchJW45Crr0SGbA.png" /><figcaption>Architecture of Machine Learning Part</figcaption></figure><p><em>During testing, I discovered several websites exhibiting mixed features where the ML-based detection entirely failed. This research presents a multi-agent methodology using Large Language Model (LLM) agents to tackle this problem and respond to the dynamic characteristics of phishing assaults.</em></p><p><em>The suggested system follows an agentic design, where each agent is accountable for a certain job. Given that LLMs are pre-trained and fine-tuning them is both computationally costly and delivers minor benefits, this technique does not depend on further training datasets. However, for assessment reasons, the Adversarial Phishing Webpages (APW) dataset is employed</em></p><p><em>The LLM employed in this investigation is Llama-3.3- nemotron-nano-8b-v1, a fine-tuned model given by NVIDIA. This approach offers complex reasoning and function calling, making it well-suited for agent-based systems.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oloH-RKQKkl1d3FhAGH3A.png" /><figcaption>LLM-based confidence scoring architecture used in phishing detection</figcaption></figure><p><em>The procedure starts when the user transmits a URL to the backend system. The first agent parses the HTML content of the site. This text is then provided to the LLM agent, which creates a summary version depending on the criteria mentioned below:</em></p><ul><li><em>Brand Accuracy (0–10): Evaluates how closely the site resembles a well-known brand.</em></li><li><em>Has Credentials: Checks if the web page requests sensitive user information (e.g., passwords, credit card details).</em></li><li><em>Has Call To Action: Identifies if the site prompts actions like ”Click here to verify” or ”Reset your password.”</em></li><li><em>Serves Error: Determines if the site returns HTTP errors (e.g., 404, 500), which may indicate it was taken down for being malicious.</em></li></ul><p><em>Summarization is required because to the context window constraints of contemporary LLMs, which usually peak out at approximately 128k tokens — often inadequate for complete site information. The LLM then utilizes this summarized HTML information to calculate a webpage-based confidence score using the following rules:</em></p><ul><li><strong><em>Brand Imitation:</em></strong><em> If the site attempts to replicate a well known brand.</em></li><li><strong><em>Requests for Credentials:</em></strong><em> If the site asks for login, payment, or personal details.</em></li><li><strong><em>Calls to Action:</em></strong><em> The site urges users to click on links or perform specific actions.</em></li><li><strong><em>Limited Functionality: </em></strong><em>Other pages return a 404 error if only the homepage works.</em></li><li><strong><em>Suspicious URL:</em></strong><em> If the domain name mimics a legitimate site or contains weird characters.</em></li><li><strong><em>Error Pages:</em></strong><em> If the webpage serves HTTP 400+ errors, the confidence score is increased by 30%.</em></li><li><strong><em>Missing HTML Content:</em></strong><em> If no content loads, the results are marked as unavailable.</em></li></ul><p><em>While this score is being generated, another agent interacts with VirusTotal via an API request to acquire more threat information. These stats are then provided to the LLM agent, which determines a VirusTotal-based confidence score. Finally, the LLM computes a combined confidence score by merging the webpage-based and VirusTotal-based ratings. A fail-safe technique is implemented: if the agent cannot interpret the site due to HTTP problems, just the VirusTotal based score is evaluated</em></p><h4>Evaluation and Results</h4><p><em>To evaluate the effectiveness of my phishing detection system, I trained and tested a variety of machine learning models including Random Forest, XGBoost, SVM, Logistic Regression, and a deep learning architecture. The models were trained on curated datasets balanced with SMOTE and validated using k-fold cross-validation. Performance was assessed using metrics such as Accuracy, Precision, Recall, F1-Score, and AUC-ROC. Among these, Random Forest and XGBoost delivered the best results, each reaching an accuracy of 95.45% and recall above 96%. While the deep learning model had lower accuracy (79.52%), it achieved the highest recall at 89.65%, which is crucial for minimizing false negatives in phishing detection.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*YyRzpxQKU8nLPIfFFefPiQ.png" /><figcaption>Model Performance for ML/DL methods</figcaption></figure><p><em>Despite strong performance on structured data, the ML and DL models showed consistent weaknesses when tested against deceptive phishing websites that did not exhibit traditional red flags. One such case was 12voltdoesit.com — a phishing site that appeared clean to structural models but was designed to trick users through its page content. This limitation led me to integrate a large language model (LLM) into the detection pipeline. The LLM was able to parse the webpage’s text and identify signs of phishing such as suspicious calls to action, altered login phrasing, and brand impersonation. Its semantic understanding enabled detection of threats that bypassed conventional models, effectively reducing false negatives and boosting the system’s overall robustness.</em></p><p><em>To improve interpretability and reduce the rigidity of binary classifications, I designed the system to output a confidence score from 0 to 100, indicating the likelihood that a site is phishing. These scores are influenced by a combination of webpage content signals and external threat reports from sources like VirusTotal. This scoring mechanism helps distinguish between clearly malicious, clearly safe, and ambiguous cases — allowing more nuanced decision-making. By combining high-speed ML predictions with the contextual depth of LLMs, the system achieves both accuracy and adaptability, making it well-suited for identifying sophisticated phishing threats in real-world scenarios.</em></p><h4>Conclusion</h4><p><em>Building a robust phishing detection system taught me that defeating modern cyber threats requires more than just analyzing URLs. While traditional machine learning models like Random Forest and XGBoost performed exceptionally well on structured data, they often failed to detect cleverly disguised phishing sites that appeared legitimate at first glance. This limitation highlighted the need for deeper semantic understanding, which I addressed by integrating a Large Language Model (LLM) capable of analyzing the actual webpage content. The result was a hybrid detection pipeline that blends speed and precision with contextual reasoning — delivering improved recall, reduced false negatives, and better adaptability to novel phishing tactics.</em></p><p><em>Throughout the project, I encountered several technical and architectural challenges. ML models required extensive manual feature engineering and were sensitive to class imbalance, often leading to biased results. On the other hand, LLMs, while powerful, introduced latency due to their computational complexity and API constraints. Handling multilingual websites, designing a modular multi-agent architecture, and summarizing large HTML documents within token limits also added to the system’s complexity. Additionally, striking the right balance between speed, accuracy, and scalability was a continuous design consideration.</em></p><p><em>Despite these challenges, the system demonstrated strong real-world applicability and laid a scalable foundation for future enhancements. The combination of structural analysis and semantic intelligence makes it well-equipped to handle sophisticated phishing attacks that evade static defenses. Looking ahead, I plan to extend this work with adversarial training, visual content analysis, and multilingual support to further strengthen detection capabilities. In an era where phishing is increasingly subtle and deceptive, hybrid AI-driven approaches like this are essential to staying ahead of the threat curve.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7d5e6c2daba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>