<?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 Vishnu on Medium]]></title>
        <description><![CDATA[Stories by Vishnu on Medium]]></description>
        <link>https://medium.com/@uvstharun183?source=rss-f29068a00b80------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eLa5TxMbp1ZyUgy6COwfZA@2x.jpeg</url>
            <title>Stories by Vishnu on Medium</title>
            <link>https://medium.com/@uvstharun183?source=rss-f29068a00b80------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:28:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@uvstharun183/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 Model That Aced Training and Failed Production: Understanding Bias and Variance]]></title>
            <link>https://medium.com/@uvstharun183/the-model-that-aced-training-and-failed-production-understanding-bias-and-variance-199ab468d461?source=rss-f29068a00b80------2</link>
            <guid isPermaLink="false">https://medium.com/p/199ab468d461</guid>
            <category><![CDATA[stastics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Vishnu]]></dc:creator>
            <pubDate>Wed, 29 Jul 2026 23:59:58 GMT</pubDate>
            <atom:updated>2026-07-29T23:59:58.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-OgtgwFxb9IVaNLb" /><figcaption>Photo by <a href="https://unsplash.com/@googledeepmind?utm_source=medium&amp;utm_medium=referral">Google DeepMind</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Model That Aced Training and Failed Production: Understanding Bias and Variance</h3><p>You have been there. A model with 98% training accuracy hits real data and falls apart. Or a model so cautious it barely learns anything useful. Both are bias-variance problems, and most explanations stop at the textbook diagram.</p><p>Here is what this trade-off actually looks like in practice, where the classical framework breaks down, and what modern tooling gives you to manage it better</p><h4>What Bias and Variance Actually Mean</h4><p>The framing I find most useful: bias and variance are two different ways a model can be wrong.</p><p><strong>Bias </strong>is systematic error. It comes from a model that makes overly simplistic assumptions about the data. A linear regression on a clearly nonlinear target will consistently miss not randomly, but in a predictable direction. Bias measures how far off predictions are from the true values because the model cannot represent the underlying pattern.</p><p><strong>Variance</strong> is sensitivity error. A high-variance model memorizes the training set, including its noise, and falls apart on anything new. It captures how much predictions fluctuate when you change which data the model trained on.</p><p>Together, they make up most of your model’s predictable error, along with irreducible noise you cannot fix with any model choice.</p><p>The classic decomposition of mean squared error:</p><blockquote>MSE = Bias² + Variance + Irreducible Noise</blockquote><p>That last term is the floor you are working against. You cannot eliminate it. Everything else is fair game.</p><h4>Where I See This Go Wrong</h4><p>The most common mistake I have seen in teams is diagnosing a variance problem as a data problem. Someone notices the model is inconsistent across different data slices and immediately asks for more data. Sometimes that helps. But often the model is just too complex for the signal available, and more data only slightly smooths the variance curve. The right fix is regularization or a simpler architecture, not a longer data pipeline.</p><h3>The Classic Trade-off in Practice</h3><p>The mental model is simple: as you increase model complexity, bias drops and variance rises. There is a sweet spot in the middle where total error is minimized. In practice, this plays out along a few axes.</p><p><strong>Model capacity</strong>: a decision tree with depth 2 has high bias. One with depth 20 on a small dataset has extreme variance. Max depth is one of the most directly interpretable complexity knobs you have.</p><p><strong>Training set size</strong>: more data reduces variance without touching bias much. If your model is underfit, more data will not save it.</p><p><strong>Regularization</strong>: L1 and L2 penalties push coefficients toward zero. They intentionally introduce a small amount of bias to get a large reduction in variance. This is the explicit trade-off, made numerical and tunable.</p><p>I spent a week once tuning a gradient boosted model for a clinical risk score, adjusting max depth and learning rate, watching validation AUC oscillate. What I should have done on day one was plot training versus validation error across tree counts. The gap was obvious once I looked. High variance. More aggressive subsampling and a lower learning rate fixed it in an afternoon.</p><h3>Ensemble Methods: Empirical Winners on the Trade-off</h3><p>The reason Random Forest, Gradient Boosting, and XGBoost dominate so many benchmark tasks is not magic. They are architecturally designed to manage this trade-off. Random Forest reduces variance through averaging. Each tree is high-variance individually. Averaging many of them, each trained on a different bootstrap sample with different feature subsets, washes out the individual errors. Bias stays roughly the same. Variance drops substantially. Gradient Boosting reduces bias through sequential correction. Each weak learner targets the residual error of the previous one. You are explicitly fitting the remaining bias at each step, which is why it works so well on structured data.</p><p>Empirical comparisons across multiple models consistently show ensemble methods achieving the lowest overall error by managing both sides of the trade-off better than single models. This lines up with what I see in practice. When I start on a new tabular problem, a tuned XGBoost baseline is usually hard to beat without substantial additional feature engineering.</p><h3>Where the Classical Framework Breaks Down</h3><p>Here is where a lot of practitioners get confused when they move to deep learning. The textbook says models with low capacity have high bias and low variance, while models with high capacity have low bias and high variance. That holds in the classical regime. But modern deep neural networks break this rule.</p><p>Large overparameterized models ones with far more parameters than training examples often generalize well even when they perfectly fit the training data. This is called <strong>double descent</strong>. As model size increases past a critical point, test error actually starts falling again even as the model interpolates the training data exactly.</p><p>What actually happens is that the variance curve is not monotonic. It first increases with model size, then decreases beyond the point where the model can perfectly fit the training data. The classical U-shaped error curve is a simplified picture that stops too early.</p><p>This matters when you are deciding whether to regularize a large neural network or just let it train to interpolation. In my work with healthcare NLP models, large pretrained transformers fine-tuned on small clinical datasets behave oddly by classical standards. They fit training data tightly but generalize well, especially when early stopping is applied carefully. The double descent framing explains this better than the classical one does.</p><h3>Diagnosing Bias and Variance in Your Own Models</h3><p>You do not need to calculate the mathematical decomposition. Here is what I actually do.</p><p><strong>Learning curves</strong> are the most direct diagnostic. Plot training error and validation error as a function of training set size. If both are high and close together, you have bias. If validation error is much higher than training error, you have variance.</p><p><strong>Cross-validation spread</strong> tells you about variance directly. If your 5-fold CV scores have a wide range, the model is sensitive to which samples land in training. That is variance.</p><p><strong>Regularization sweeps</strong> show you where the bias-variance optimum is for your model class. Sweep your alpha in Ridge, your C in SVM, your lambda in XGBoost. The validation curve is a direct picture of the trade-off.</p><p>I log all of these to MLflow on any project that lasts more than a week. Having that history is useful when a model degrades in production and you need to understand whether the training data distribution shifted or the model was already sitting on the high-variance side of the curve.</p><h3>Modern Tools for Quantifying Uncertainty</h3><p>One thing the classical framework never gave you well is a direct number for how uncertain a specific prediction is. Conformal prediction is getting real traction. The core idea: given a calibration set, you can generate prediction intervals with guaranteed coverage your 90% interval actually contains the true value 90% of the time, regardless of the underlying model, without requiring distributional assumptions. This matters in healthcare. When a model flags a patient as high-risk, a point estimate is not enough. A clinician needs to know how confident that estimate is. Conformal prediction gives you that guarantee in a model-agnostic way. I have been using ‘nonconformist’ and ‘mapie’ in Python for this, and the results are more practically useful than raw confidence scores from sklearn ever were. Bias pulls predictions in the wrong direction systematically. Variance makes them inconsistent. Conformal prediction gives you a window into that second problem at inference time, which is where it actually costs you.</p><h3>Key Takeaways</h3><ul><li>Bias is systematic error from oversimplification. Variance is sensitivity error from overfitting. Both inflate your MSE in predictable ways.</li><li>More data mainly reduces variance, not bias. If your model is underfit, a larger dataset will not fix it.</li><li>Ensemble methods, especially gradient boosting, consistently outperform single models on the bias-variance trade-off for tabular data.</li><li>Deep neural networks break the classical U-curve. Double descent means overparameterized models can generalize well past the interpolation threshold. The classical framework is a starting point, not the full story.</li><li>Learning curves and cross-validation spread are your fastest practical diagnostics. Run them before tuning anything.</li><li>Conformal prediction is worth learning now. It gives you statistically valid prediction intervals without distributional assumptions a direct, operational tool for managing variance at inference time.</li></ul><p>The bias-variance trade-off sounds like it belongs in a textbook and ends up shaping almost every modeling decision you make. Get fluent with the diagnostics and the modern nuances, and you will spend less time chasing the wrong fix.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=199ab468d461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-Validation Explained: Why Your Train/Test Split Is Not Enough]]></title>
            <link>https://medium.com/@uvstharun183/cross-validation-explained-why-your-train-test-split-is-not-enough-8acfdc3d1e4f?source=rss-f29068a00b80------2</link>
            <guid isPermaLink="false">https://medium.com/p/8acfdc3d1e4f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-validation]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Vishnu]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 23:49:11 GMT</pubDate>
            <atom:updated>2026-06-10T23:49:11.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hkEpT1W63EkX7W5K" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=medium&amp;utm_medium=referral">Campaign Creators</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Your model scores 95% on the test set. You deploy it. Two weeks later, it is performing at 60% accuracy in production. Sound familiar? I have been there, and it hurts. The culprit is often inadequate validation. A simple train/test split feels clean and straightforward, but it is dangerously incomplete for real-world model deployment.</p><h3>The Fatal Flaw of Single Split Validation</h3><p>Most data scientists start with the classic 80/20 or 70/30 train/test split. You train on one portion, validate on another, and call it good. I did this for months when I started.</p><p>The problem is <strong>sampling bias</strong>. Your single test set might not represent the true data distribution your model will encounter in production. In healthcare data, I have seen models trained on data from one hospital system completely fail when applied to another, despite identical preprocessing and feature engineering.</p><p>Consider this scenario: You are predicting patient readmission risk using hospital data. Your random split might accidentally place all summer admissions in training and winter admissions in testing. Your model learns seasonal patterns that do not generalize.</p><p>A banking client I worked with experienced exactly this issue. Their loan default prediction model achieved 95% accuracy on training data but dropped to 60% on new data due to overfitting from improper validation.</p><h3>Why Cross-Validation Changes Everything</h3><p>Cross-validation solves the sampling bias problem by testing your model against multiple different data splits. Instead of one lucky or unlucky test set, you get a robust estimate of model performance across various data configurations.</p><h4>K-Fold Cross-Validation: The Gold Standard</h4><p>In k-fold cross-validation, you split your data into k equal parts. You train on k-1 folds and test on the remaining fold, repeating this process k times. Each data point gets to be in the test set exactly once.</p><p>K-fold cross-validation exposes models to different data distributions k times, alleviating bias that may occur in training and validation set selection.</p><p>I typically use k=5 or k=10. Research shows that k=10 lies in the middle of bias and variance, making it ideal for several modeling exercises.</p><p>Here is what this looks like in practice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*xbPvOJA7QX8i_3907TibIg.png" /></figure><h4>When Standard Cross-Validation Fails</h4><p>Not all data is created equal. Time-series data breaks the fundamental assumptions of random k-fold cross-validation.</p><p>I learned this the hard way when building patient outcome prediction models using electronic health records. Random k-fold fails for temporal data because it breaks the arrow of time, creating lookahead bias that produces scores that are pure fantasy.</p><p>For time-series data, use <strong>TimeSeriesSplit</strong> instead. This maintains temporal order, ensuring you never train on future data to predict the past.</p><h3>Choosing the Right Cross-Validation Strategy</h3><p>The validation method you choose can make or break your model’s real-world performance. Yet validation methods are often selected using default settings without considering their impact on generalizability.</p><h4>Stratified Cross-Validation for Imbalanced Data</h4><p>In healthcare, class imbalance is everywhere. Rare disease prediction, adverse event detection, treatment response classification. Regular k-fold can create folds with zero positive cases, making evaluation meaningless.</p><p>Stratified k-fold maintains the same class distribution across all folds. I use this for any classification problem where classes represent less than 20% of the data.</p><h4>Leave-One-Out for Small Datasets</h4><p>With small datasets (n &lt; 100), k-fold cross-validation can be unstable. Leave-one-out cross-validation (LOOCV) uses every possible train/test combination, giving you the most thorough evaluation possible.</p><p>The downside? Computational cost. LOOCV requires training n models instead of k models. For large datasets with complex models, this becomes prohibitive.</p><h4>Custom Cross-Validation for Domain-Specific Problems</h4><p>Sometimes standard approaches do not fit your problem structure. In multi-site clinical studies, I use <strong>GroupKFold </strong>to ensure that all data from one hospital stays together in either training or testing. This prevents data leakage between closely related samples.</p><h3>The Hidden Cost of Poor Validation</h3><p>Bad validation does not just give you wrong performance numbers. It fundamentally breaks your model selection process.</p><p>When I was building NLP models for clinical text classification, I initially used random splits. My best performing model used character-level features that seemed to capture important medical terminology patterns. After implementing proper cross-validation, I discovered the model was memorizing document formatting quirks specific to certain time periods.</p><p>The model that looked best was actually the worst at generalizing to new data patterns.</p><h3>Practical Implementation Tips</h3><h4>Monitor Validation Variance</h4><p>High variance across cross-validation folds signals instability. If your scores range from 0.65 to 0.95 across folds, your model is not robust. Either your dataset is too small, too noisy, or your model is overfitting.</p><h4>Use Cross-Validation for Hyperparameter Tuning</h4><p>Never tune hyperparameters on your test set. Use nested cross-validation: an outer loop for model evaluation and an inner loop for hyperparameter optimization. This prevents hyperparameter overfitting.</p><h4>Save Computational Resources</h4><p>Cross-validation is expensive. For rapid prototyping, start with 3-fold or 5-fold. Save 10-fold or higher for final model evaluation. Use stratification by default unless you have a specific reason not to.</p><h3>Key Takeaways</h3><p>— Single train/test splits hide sampling bias and provide unreliable performance estimates</p><p>— K-fold cross-validation with k=10 balances bias and variance for most problems</p><p>— Time-series data requires specialized cross-validation approaches that respect temporal order</p><p>— Stratified cross-validation prevents class imbalance issues in classification tasks</p><p>— High variance across folds indicates model instability or insufficient data</p><p>— Proper validation is essential for hyperparameter tuning and model selection</p><p>Cross-validation is not just a nice-to-have evaluation technique. It is the foundation of reliable model development. The extra computational cost pays for itself the first time it saves you from deploying a model that fails in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8acfdc3d1e4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Imbalanced Dataset Strategy Is Probably Wrong (And What Actually Works)]]></title>
            <link>https://medium.com/@uvstharun183/why-your-imbalanced-dataset-strategy-is-probably-wrong-and-what-actually-works-38af7fcd4466?source=rss-f29068a00b80------2</link>
            <guid isPermaLink="false">https://medium.com/p/38af7fcd4466</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Vishnu]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 21:30:34 GMT</pubDate>
            <atom:updated>2026-06-07T21:30:34.930Z</atom:updated>
            <content:encoded><![CDATA[<p>Three years ago, I thought SMOTE was magic. Apply it to any imbalanced dataset, watch your F1 scores soar, and call it a day. Then I deployed a fraud detection model to production that flagged 40% of legitimate transactions as suspicious. Real-world data taught me that handling class imbalance requires more nuance than most tutorials suggest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tX9-hrEMbvbKUVxw" /><figcaption>Photo by <a href="https://unsplash.com/@loomydoons?utm_source=medium&amp;utm_medium=referral">Myles Bloomfield</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Real Problem with Imbalanced Data</h3><p>Class imbalance isn’t just about having fewer positive samples. It’s about your model learning to predict the majority class for everything because that’s the path of least resistance to high accuracy. In healthcare data, I’ve seen datasets where 95% of patients don’t have a specific condition. A model that predicts “no condition” for everyone achieves 95% accuracy but catches zero actual cases. The business impact is catastrophic. The issue gets worse when your minority class has internal diversity. In my experience with medical imaging, rare diseases often present with multiple distinct patterns. Traditional oversampling techniques create synthetic samples that don’t capture this complexity, leading to models that fail on real patient data.</p><h4><strong>When Accuracy Lies</strong></h4><p>I learned this the hard way on a readmission prediction project. Our model achieved 89% accuracy on the test set. The hospital was thrilled until they realized we were missing 70% of actual readmission cases. High accuracy masked terrible recall on the class that mattered most. This is why I now start every imbalanced dataset project by asking: “What’s the cost of each type of error?” A false negative in fraud detection might cost $10,000. A false positive costs customer friction and processing time. Your strategy should reflect these trade-offs, not chase balanced F1 scores.</p><h3>SMOTE: When It Works and When It Fails</h3><p>SMOTE creates synthetic minority samples by interpolating between existing ones. It sounds elegant, but I’ve seen it fail spectacularly in production.</p><h4>The Good</h4><p>SMOTE works well when your minority class samples are relatively homogeneous and clustered in feature space. I used it successfully on a patient outcome prediction model where the positive cases (poor outcomes) had consistent risk factor patterns. The synthetic samples captured the underlying relationships without introducing noise.</p><p>The algorithm also handles continuous features naturally. Unlike simple oversampling, SMOTE creates new data points rather than exact duplicates, which can help prevent overfitting.</p><h4>The Bad</h4><p>Traditional oversampling methods may introduce noise and fuzzy boundaries leading to overfitting. I’ve experienced this firsthand when SMOTE created synthetic samples in regions where classes actually overlap. On a text classification project, SMOTE generated feature vectors that didn’t correspond to any real documents. These synthetic points sat in impossible regions of the feature space, causing the model to learn decision boundaries that didn’t generalize.</p><h4>The Ugly</h4><p>SMOTE has been critiqued for creating synthetic samples that don’t reflect real-world distributions, potentially leading to overfitting in real-world applications. This matches my experience with time-series forecasting, where SMOTE generated temporal patterns that violated domain knowledge about the underlying process.</p><h4>Better SMOTE Variants</h4><p>I now use Borderline-SMOTE for most projects. It only creates synthetic samples near class boundaries, avoiding the noise issues of standard SMOTE. For high-dimensional data like NLP features, I’ve had success with ADASYN, which adapts the number of synthetic samples based on local density.</p><h3>Class Weights: The Underrated Solution</h3><p>Class weights tell your algorithm to penalize misclassifying minority samples more heavily. It’s elegant because it avoids resampling entirely.</p><h4>Why I Choose Weights First</h4><p>Class weights avoid resampling needs making them elegant for large datasets, but may struggle with extreme imbalance ratios like 99:1. For moderate imbalance (5:1 to 20:1), I start with class weights because they’re fast, interpretable, and work with any sklearn classifier. In scikit-learn, `class_weight= ‘balanced’` automatically computes inverse class frequencies. For a 10:1 imbalance, minority samples get 10x the penalty weight. Simple and effective.</p><h4>When Weights Aren’t Enough</h4><p>Extreme imbalance breaks class weights. On a cybersecurity project with 1000:1 imbalance, even with balanced weights, the model still ignored minority samples. The penalty wasn’t strong enough to overcome the overwhelming majority class signal. High-dimensional sparse data also challenges class weights. In NLP projects with 50,000+ features, I’ve seen weighted models become unstable, with coefficients swinging wildly between training runs.</p><h4>Custom Weight Strategies</h4><p>Instead of `class_weight= ‘balanced’`, I often use custom ratios based on business costs. If false negatives cost 5x more than false positives, I set minority class weight to 5 rather than the frequency-based ratio. This aligns model behavior with business objectives.</p><h3>Beyond the Usual Suspects: Advanced Techniques</h3><h4>Threshold Moving</h4><p>The simplest fix is often the best. Instead of predicting class labels, predict probabilities and move the decision threshold. I use this on every imbalanced classification project.</p><p>For binary classification, sklearn’s default threshold is 0.5. But if your positive class is 10% of the data, a threshold of 0.2 might perform better. I use `precision_recall_curve` to find the optimal threshold for my business metrics.</p><h4>Ensemble Methods with Sampling</h4><p>SMOTE sampling improved model performance from 61% to 79%, with Adaboost achieving an F1-Score of 87.6%. I combine this with my own ensemble approach: train multiple models on different balanced subsets of the majority class, then ensemble their predictions.</p><p>This works particularly well with random forests. I create 10 balanced datasets by sampling without replacement from the majority class, train a forest on each, then average predictions. It’s simple but often outperforms single-model approaches.</p><h4>Cost-Sensitive Learning</h4><p>Some algorithms support cost-sensitive learning natively. XGBoost’s `scale_pos_weight` parameter is more flexible than sklearn’s class weights. LightGBM’s `is_unbalance` parameter automatically adjusts for imbalanced data. I’ve had particular success with cost-sensitive SVMs for high-dimensional healthcare data. The algorithm naturally finds decision boundaries that account for misclassification costs.</p><h3>What Actually Works in Production</h3><p>After deploying dozens of models on imbalanced datasets, here’s what consistently works:</p><h4>Start with Business Metrics</h4><p>Don’t optimize for F1 scores unless F1 score matches your business objective. In fraud detection, I optimize for recall at a fixed precision threshold. In medical diagnosis, I optimize for sensitivity while keeping false positive rates manageable.</p><h4>Combine Multiple Techniques</h4><p>My standard approach combines threshold tuning with either class weights or SMOTE, depending on the data characteristics. Real-world graph data often exhibits class imbalance, leading to poor performance of standard machine learning models on underrepresented classes. For graph-based problems, I layer multiple techniques.</p><h4>Validate on Temporal Splits</h4><p>If your data has a time component, validate using temporal splits, not random splits. I learned this lesson when a model trained on randomly split fraud data performed terribly on new fraud patterns that emerged months later.</p><h4>Monitor Drift in Production</h4><p>Imbalanced datasets are particularly susceptible to concept drift. I set up monitoring for both class distribution changes and performance degradation on minority classes. In healthcare, seasonal patterns can shift the balance between conditions, requiring model retraining.</p><h3>Key Takeaways</h3><ul><li>SMOTE isn’t magic. It works for homogeneous minority classes but fails when classes overlap or in high-dimensional spaces.</li><li>Class weights are underrated. They’re fast, interpretable, and work well for moderate imbalance without resampling.</li><li>Threshold tuning beats fancy algorithms. Move the decision boundary before trying complex sampling techniques.</li><li>Business metrics matter more than F1 scores. Optimize for what actually matters to your stakeholders.</li><li>Combine techniques strategically. Use ensemble methods with sampling for extreme imbalance.</li><li>Monitor production performance. Imbalanced models are fragile to data drift.</li></ul><p>The best imbalanced dataset strategy isn’t about finding the perfect algorithm. It’s about understanding your data, your business constraints, and the trade-offs between different approaches. Start simple, measure what matters, and iterate based on real-world performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38af7fcd4466" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude’s Secret Weapon: How MCP Turns AI Into Your Personal Data Detective]]></title>
            <link>https://medium.com/@uvstharun183/claudes-secret-weapon-how-mcp-turns-ai-into-your-personal-data-detective-329601685aa1?source=rss-f29068a00b80------2</link>
            <guid isPermaLink="false">https://medium.com/p/329601685aa1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Vishnu]]></dc:creator>
            <pubDate>Wed, 20 May 2026 01:34:34 GMT</pubDate>
            <atom:updated>2026-05-20T01:34:34.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A1abW890Ov5AwzHd" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>While everyone debates whether AI agents will replace human workers, Claude has quietly solved a more pressing problem: how do you actually connect an AI to your real data? The answer lies in something called the Model Context Protocol (MCP), and it’s turning Claude from a smart chatbot into something that feels more like having a data scientist who can instantly access any system in your organization.</p><p>I’ve been diving deep into how this works, and what I found surprised me. This isn’t just another API wrapper, it’s a standardized way for AI models to securely connect to databases, file systems, and web services that could fundamentally change how we think about AI integration.</p><h3>What Makes MCP Different from Traditional API Integrations</h3><p>Most AI tools connect to external services through one-off integrations built by each company. Need Slack? Build a Slack connector. Need Salesforce? Build a Salesforce connector. It’s the same fragmented approach we’ve seen with every new platform.</p><p>MCP flips this model entirely. Instead of each AI company building hundreds of custom integrations, MCP creates a standardized protocol that any system can implement once and then work with any MCP-compatible AI model.</p><p>The numbers tell the story of rapid adoption. The MCP ecosystem exploded from “a few hundred servers” in November 2024 to over 17,400 MCP servers by April 2026, with SDK downloads reaching 97 million per month. This isn’t gradual adoption, it’s a land rush.</p><h4>The Three-Layer Architecture</h4><p>MCP works through three distinct layers that make it both powerful and secure:</p><p><strong>Transport Layer: </strong>Handles the actual communication between Claude and external systems. This can be stdio (for local tools), server-sent events, or WebSocket connections depending on whether you’re connecting to local files or remote APIs.</p><p><strong>Protocol Layer:</strong> Manages the standardized message format that lets Claude discover what capabilities each connected system offers. When Claude connects to your database, it doesn’t need pre-built knowledge about your schema, it can ask the system directly what tables and functions are available.</p><p><strong>Application Layer:</strong> This is where the magic happens. Claude can call functions, read resources, and even subscribe to real-time updates from connected systems.</p><h3>Connecting to Databases: Beyond Simple Queries</h3><p>The database integration showcases why MCP matters for practical AI deployment. Rather than building custom database connectors, any database that implements MCP can immediately work with Claude.</p><p>I found the PostgreSQL MCP server particularly interesting because it demonstrates the security model in action. Claude doesn’t get direct database access, instead, it makes requests through the MCP server, which enforces permissions, query limits, and other safety constraints.</p><h4>Real-World Database Use Cases</h4><p>Research shows that 78% of enterprise AI teams now report at least one MCP-backed agent in production. The most common database use cases include:</p><p>- <strong>Automated reporting:</strong> Claude can query sales databases, join multiple tables, and generate executive summaries without human intervention<br>- <strong>Data quality monitoring: </strong>By connecting to data warehouses, Claude can identify anomalies, missing values, or schema changes<br>- <strong>Customer support:</strong> Integration with CRM databases lets Claude pull customer history and resolve issues faster than human agents</p><p>The key insight here is that Claude isn’t just running SQL queries, it’s reasoning about data relationships and generating insights that would typically require a data analyst.</p><h3>API Integration: The Enterprise Integration Story</h3><p>While database connections are impressive, API integration is where MCP becomes genuinely transformative for businesses. Major enterprise vendors are now publishing official MCP servers as MCP becomes the default protocol for AI-to-system integration.</p><p>The public MCP server registry grew 7.8x year-over-year from 1,200 servers in Q1 2025 to 9,400+ servers in April 2026. This explosion reflects enterprise demand for AI that can actually work with existing systems.</p><h4>Beyond CRUD Operations</h4><p>What makes MCP API integration powerful isn’t just that Claude can make API calls, any script can do that. The breakthrough is that Claude can understand API responses, combine data from multiple services, and take follow-up actions based on what it discovers.</p><p>For example, Claude might:<br>1. Query a project management API to find overdue tasks<br>2. Check a team calendar API to see who’s available<br>3. Send notifications through a Slack API to reassign work<br>4. Update the project status through the original API</p><p>This multi-step reasoning across different systems is what transforms Claude from a tool that answers questions into one that can actually solve problems.</p><h3>Local File Access: The Security Challenge</h3><p>Local file integration represents both MCP’s biggest opportunity and its trickiest challenge. The ability for Claude to read, analyze, and modify local files could revolutionize personal productivity, but it also raises obvious security concerns.</p><p>The MCP approach addresses this through <strong>sandboxed file access</strong>. Rather than giving Claude direct filesystem access, MCP servers can restrict access to specific directories, file types, or operations.</p><h4>Practical File System Use Cases</h4><p>I’ve been experimenting with file-based MCP servers, and the capabilities are genuinely impressive:</p><p>- <strong>Code analysis: </strong>Claude can read entire codebases, understand dependencies, and suggest refactoring across multiple files<br>- <strong>Document processing:</strong> Integration with local document stores lets Claude analyze contracts, research papers, or technical specifications<br>- <strong>Configuration management:</strong> Claude can read config files, identify inconsistencies, and suggest changes based on best practices</p><p>The limitation isn’t technical capability, it’s trust. Most organizations aren’t ready to give AI agents write access to critical files, even with sandboxing.</p><h3>The Ecosystem Effect: Why MCP Is Winning</h3><p>What fascinates me about MCP’s rapid adoption is how it creates network effects. Every new MCP server benefits every MCP-compatible AI model, and every new AI model that supports MCP can immediately access thousands of existing integrations.</p><p>This is fundamentally different from the walled garden approach of most AI platforms. Instead of each company building proprietary integrations, MCP creates shared infrastructure that benefits the entire AI ecosystem.</p><h4>The Open Source Advantage</h4><p>Unlike many AI protocols that remain proprietary, MCP is open source with active community development. The protocol specification is public, implementations are available in multiple programming languages, and the community is building servers faster than any single company could.</p><p>This open approach means MCP can evolve quickly to address new use cases without waiting for vendor roadmaps. When someone needs Claude to connect to a new service, they can build an MCP server and immediately share it with the community.</p><h3>Key Takeaways</h3><p>- MCP transforms Claude from a chatbot into a system that can actively work with your data across databases, APIs, and files<br>- The protocol’s rapid adoption (17,400+ servers by April 2026) reflects genuine enterprise demand for AI integration<br>- Security comes through sandboxed access rather than direct system integration<br>- Open source development creates network effects that benefit the entire AI ecosystem<br>- Enterprise adoption is accelerating, with 78% of AI teams reporting MCP-backed agents in production</p><p>The real significance of MCP isn’t just that it lets Claude connect to external systems, it’s that it provides a standardized, secure way to do so at scale. As more organizations deploy AI agents, having a common integration protocol becomes essential infrastructure. MCP appears to be filling that role, and filling it quickly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=329601685aa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Cost of Getting ML Inference Wrong: Batch vs Online vs Streaming]]></title>
            <link>https://medium.com/@uvstharun183/the-hidden-cost-of-getting-ml-inference-wrong-batch-vs-online-vs-streaming-54bc059db0cf?source=rss-f29068a00b80------2</link>
            <guid isPermaLink="false">https://medium.com/p/54bc059db0cf</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[infertility-treatment]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vishnu]]></dc:creator>
            <pubDate>Thu, 14 May 2026 02:51:00 GMT</pubDate>
            <atom:updated>2026-05-14T02:51:00.524Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hSw_wIY_dY1G5r7E" /><figcaption>Photo by <a href="https://unsplash.com/@kommumikation?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You spent months perfecting your model’s F1 score, only to discover that your choice of inference pattern matters more than that extra 2% accuracy boost. The difference between batch, online, and streaming inference isn’t just technical complexity, it’s the difference between a model that drives business value and one that collects digital dust.</p><h3><strong>The Performance Reality Check</strong></h3><p>Here’s what surprised me most during my transition from training models to deploying them: the inference pattern you choose can make or break your entire ML system. Whatnot Engineering recently shared a case study where switching from batch to online inference delivered a <strong>6x performance improvement</strong>, not through better algorithms, but through better architecture (Source: <a href="https://medium.com/whatnot-engineering/6x-faster-ml-inference-why-online-batch-16cbf1203947">Whatnot Engineering, 2025</a>).</p><p>Think of it like choosing between a sports car and a freight train. Both move fast, but the sports car accelerates instantly while the freight train needs a mile to reach full speed. Your business requirements determine which vehicle fits your needs.</p><h3>Batch Inference: The Workhorse Pattern</h3><p>Batch inference is like running cross-validation on steroids, you process large datasets in chunks, optimize for throughput over latency, and get predictable resource usage.</p><h4>When Batch Makes Sense</h4><p>Batch inference shines when you can predict what you need to predict. Spotify’s Discover Weekly exemplifies this perfectly: they generate recommendations for millions of users once per week, store results in a key-value database, and serve them instantly when users open the app (Source: <a href="https://www.hopsworks.ai/post/mlops-to-ml-systems-with-fti-pipelines">Hopsworks, 2023</a>).</p><p>Google Cloud points out a crucial advantage: “Because batch inference is not constrained by low-latency requirements, you can perform more complex and computationally intensive feature engineering on your input data, which can often lead to more accurate models” (Source: <a href="https://cloud.google.com/discover/what-is-batch-inference">Google Cloud, 2024</a>).</p><h4>The Hidden Costs</h4><p>Batch inference seems simple until you hit the edge cases. What happens when your weekly batch job fails on Wednesday? Your users get stale recommendations for four days. What about users who signed up after your last batch run? They see nothing.</p><p>From my experience training models, batch processing felt natural, it’s how we validate models after all. But in production, that comfort zone becomes a constraint when business needs change faster than your batch schedule.</p><h3>Online Inference: The Responsive Solution</h3><p>Online inference flips the script entirely. Instead of preprocessing everything, you wait for requests and respond in real-time. It’s like the difference between meal prep and cooking to order, higher complexity, but fresh results every time.</p><h4>The Latency Game</h4><p>Made With ML explains the core challenge: “While we can achieve batch inference at scale, many models will need to be served in a real-time manner where we may need to deliver predictions for many incoming requests (high throughput) with low latency” (Source: <a href="https://madewithml.com/courses/mlops/serving/">Made With ML, 2024</a>).</p><p>The Whatnot case study reveals the engineering reality behind this. They achieved their 6x improvement through specific optimizations: migrating from DynamoDB to Redis cut latency by 3x, compiling models to native C binaries improved inference speed by 20x, and implementing gRPC reduced data transmission overhead by 6.7x (Source: <a href="https://medium.com/whatnot-engineering/6x-faster-ml-inference-why-online-batch-16cbf1203947">Whatnot Engineering, 2025</a>).</p><h4>Feature Store Dependencies</h4><p>Online inference introduces a new problem we never faced during model training: feature freshness. Your model might need user behavior data from the last hour, inventory levels from five minutes ago, and demographic data that rarely changes. Managing this feature pipeline becomes as complex as the model itself.</p><h3>Streaming Inference: The Real-Time Frontier</h3><p>Streaming inference represents the cutting edge, processing data as it flows through your system. Think of it as online inference that never stops listening.</p><h4>The Architecture Challenge</h4><p>Conduktor’s recent analysis reveals a crucial insight: “Most production systems use real-time inference with periodic model updates. True online learning remains challenging due to stability concerns and infrastructure complexity” (Source: <a href="https://www.conduktor.io/glossary/real-time-ml-pipelines">Conduktor, 2024</a>).</p><p>This distinction matters more than I initially realized. Streaming inference often means streaming predictions, not streaming model updates. You’re continuously processing new data points, but the model itself typically updates through traditional training pipelines.</p><h4>When Streaming Becomes Essential</h4><p>Fraud detection showcases streaming inference at its best. A credit card transaction happens now, not in tomorrow’s batch job. The system needs to evaluate hundreds of features about the user, merchant, and transaction pattern within milliseconds of the swipe.</p><h3>The Decision Framework That Actually Works</h3><p>After diving deep into production systems, I’ve learned that choosing between these patterns isn’t about technical preferences, it’s about business constraints.</p><h4>Start With Business Requirements</h4><p>Ask these questions before writing a single line of infrastructure code:<br>- How stale can your predictions be before they lose value?<br>- What’s the cost of a prediction being wrong versus being late?<br>- How often do your input features change?<br>- What’s your tolerance for complexity versus performance?</p><h4>The Hybrid Reality</h4><p>Most production systems don’t pick just one pattern. Netflix uses batch inference for generating candidate recommendations, online inference for ranking them based on current context, and streaming processing for updating user interaction features in real-time.</p><p>This hybrid approach acknowledges a truth I wish someone had told me earlier: different parts of your ML system have different latency requirements.</p><h3>The Engineering Tradeoffs You Need to Know</h3><h4>Resource Utilization</h4><p>Batch inference maximizes resource efficiency, you can spin up massive compute clusters, process everything, then shut down. Online inference requires always-on infrastructure, making cost management more complex but resource usage more predictable.</p><h4>Debugging and Monitoring</h4><p>Here’s something that caught me off guard: debugging batch jobs feels familiar because it’s similar to debugging training pipelines. You have clear start and end points, logs you can analyze offline, and deterministic inputs.</p><p>Online inference debugging requires different skills. You’re troubleshooting distributed systems under load, analyzing latency percentiles, and dealing with cascading failures. The monitoring complexity grows exponentially.</p><h3>Model Updates</h3><p>Batch systems naturally align with traditional ML workflows, retrain weekly, deploy to batch job, monitor aggregate metrics. Online systems force you to think about graceful model updates, A/B testing infrastructure, and canary deployments.</p><h3>Key Takeaways</h3><p>- <strong>Performance isn’t just about model accuracy</strong>, infrastructure choices like migrating from DynamoDB to Redis can deliver 3x latency improvements<br>- <strong>Batch inference enables more complex feature engineering</strong> but constrains you to predetermined schedules and stale predictions<br>- <strong>Online inference provides flexibility and freshness</strong> at the cost of infrastructure complexity and always-on resource requirements<br>- <strong>Streaming inference excels for time-sensitive applications</strong> like fraud detection but requires sophisticated data pipeline management<br>- <strong>Most production systems use hybrid approaches</strong> rather than committing to a single inference pattern<br>- <strong>Choose based on business requirements first</strong>, how stale can predictions be before they lose value?</p><p>The path from training models to serving them taught me that technical elegance matters less than business impact. Your inference pattern choice will outlive multiple model iterations, so choose wisely based on constraints, not preferences.</p><h3>References</h3><p>[1] Made With ML by Anyscale. “Model Serving — Made With ML.” Made With ML, 2024. <a href="https://madewithml.com/courses/mlops/serving/">https://madewithml.com/courses/mlops/serving/</a></p><p>[2] Google Cloud. “What is batch inference? How does it work?” Google Cloud, 2024. <a href="https://cloud.google.com/discover/what-is-batch-inference">https://cloud.google.com/discover/what-is-batch-inference</a></p><p>[3] Conduktor (Stéphane Derosiaux). “Real-Time ML Pipelines: Machine Learning on Streaming Data.” Conduktor, 2024. <a href="https://www.conduktor.io/glossary/real-time-ml-pipelines">https://www.conduktor.io/glossary/real-time-ml-pipelines</a></p><p>[4] Whatnot Engineering. “6x Faster ML Inference: Why Online≫Batch.” Medium, 2025. <a href="https://medium.com/whatnot-engineering/6x-faster-ml-inference-why-online-batch-16cbf1203947">https://medium.com/whatnot-engineering/6x-faster-ml-inference-why-online-batch-16cbf1203947</a></p><p>[5] Hopsworks. “From MLOps to ML Systems with Feature/Training/Inference Pipelines.” Hopsworks, 2023. <a href="https://www.hopsworks.ai/post/mlops-to-ml-systems-with-fti-pipelines">https://www.hopsworks.ai/post/mlops-to-ml-systems-with-fti-pipelines</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54bc059db0cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The ML Testing Pyramid: Why Your Model Needs Tests More Than Your Web App]]></title>
            <link>https://medium.com/@uvstharun183/the-ml-testing-pyramid-why-your-model-needs-tests-more-than-your-web-app-499bd1ec4433?source=rss-f29068a00b80------2</link>
            <guid isPermaLink="false">https://medium.com/p/499bd1ec4433</guid>
            <category><![CDATA[model-evaluation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Vishnu]]></dc:creator>
            <pubDate>Fri, 08 May 2026 03:37:18 GMT</pubDate>
            <atom:updated>2026-05-08T03:37:18.034Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve spent weeks perfecting your model’s F1 score, but when it hits production, it quietly starts predicting cats as dogs. No error logs. No stack traces. Just silent failures that cost your business thousands. Welcome to the wild world of untested ML systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I-2bl1RThrB-aDrK" /><figcaption>Photo by <a href="https://unsplash.com/@altumcode?utm_source=medium&amp;utm_medium=referral">AltumCode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Invisible Failures That Keep Us Up at Night</h3><p>Coming from traditional model training, I used to think validation accuracy was enough. Hit 95% on the test set, ship it, celebrate. Then I learned the hard truth: <strong>models break differently</strong> than regular software.</p><p>Your web app crashes loudly when something goes wrong. Your ML model just gets… worse. It keeps running, keeps predicting, but the predictions become garbage. According to recent industry data, 76% of developers now use AI tools at work, yet only 43% trust their accuracy (Source: <a href="https://www.growin.com/blog/mlops-developers-guide-toai-deployment-2025/">Growin, 2025</a>). The gap between building AI and making it reliable in production has never been clearer.</p><p>Here’s the thing: models break quietly. They won’t throw a 500 error; they’ll just start making bad predictions. That’s why continuous testing in MLOps exists, to catch subtle failures before they snowball (Source: <a href="https://www.accelq.com/blog/testing-in-mlops/">ACCELQ, 2025</a>).</p><h3>Unit Tests: Testing Your ML Building Blocks</h3><h4>What to Actually Test</h4><p>Unit tests in ML aren’t just about testing functions that return expected outputs. You’re testing the <strong>logic that transforms data</strong> and the <strong>assumptions your model makes</strong>.</p><p>Start with your preprocessing pipeline. If you’re scaling features, test that your scaler actually transforms the data correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*wkpY063_jF9-8JAosxdpUw.png" /></figure><p>But here’s what surprised me: you also need to test your <strong>model assumptions</strong>. Does your model expect certain data types? Does it handle missing values correctly? These aren’t just edge cases, they’re the most common ways models fail in production.</p><h4><strong>The Data Scientist’s Testing Mindset</strong></h4><p>Think of unit tests like cross-validation, but for individual components. Instead of testing model performance, you’re testing that each piece of your pipeline does what you think it does.</p><p>Test your feature engineering functions. Test your data loading logic. Test that your model wrapper correctly handles different input formats. One critical insight from recent MLOps practice: “Start with writing unit tests for individual components and integration tests to check the flow from data ingestion to model output” (Source: <a href="https://medium.com/@mailtodevens/mlops-test-frameworks-a-guide-for-quality-engineers-695d29b53db8">Devender Sharma, 2024</a>).</p><h4>Integration Tests: When Components Meet Reality</h4><p><strong>Testing the Full Pipeline<br></strong>Integration tests check that your components work together correctly. This is where you test the <strong>entire flow</strong> from raw data to model prediction.</p><p>Your integration test might look like:</p><ol><li>Load sample raw data</li><li>Run it through your preprocessing pipeline.</li><li>Feed it to your model</li><li>Verify the output format and ranges make sense</li></ol><p><strong>The Schema Evolution Problem<br></strong>Here’s a failure mode I discovered the hard way: your training data has 50 features, but production data starts coming in with 52 features. Your model still runs, but now it’s making predictions on misaligned data.</p><p>Integration tests catch this. They verify that the <strong>data contract </strong>between your training environment and production environment remains intact. Test that column order doesn’t matter. Test that extra columns are handled gracefully. Test that missing columns fail fast rather than silently.</p><p><strong>API Contract Testing<br></strong>If your model serves predictions via API, integration tests should verify the entire request-response cycle. Mock realistic payloads. Test edge cases like extremely large inputs or malformed requests. Ensure your model returns consistent output formats.</p><h3>Data Validation: The Foundation That’s Often Forgotten</h3><h4><strong>Beyond Basic Schema Checks</strong></h4><p>Data validation in ML goes deeper than “is this column an integer?” You need to validate <strong>statistical properties</strong> of your data.</p><p>Does the distribution of incoming features match what your model was trained on? Are there unexpected null rates? Has the correlation structure changed? These questions matter because models are sensitive to distributional shift in ways that traditional software isn’t.</p><p>Data validation tools like Great Expectations help check inputs and data quality before training or using the model (Source: <a href="https://billtcheng2013.medium.com/mlops-2025-eaec6edd7fcf">Xin Cheng, 2025</a>). But you need to know what to check for.</p><p><strong>The Training-Serving Skew Problem<br></strong>Here’s a subtle failure mode: your training data is perfectly clean, but production data has different characteristics. Maybe it comes from a different time period, or users behave differently than your training assumptions.</p><p>Set up validation rules that check:</p><ul><li><strong>Statistical properties:</strong> mean, variance, percentiles of numerical features</li><li><strong>Categorical distributions: </strong>are new categories appearing? Are existing categories vanishing?</li><li><strong>Data freshness:</strong> how old is this data compared to training data</li></ul><p><strong>Continuous Data Monitoring<br></strong>Unlike traditional software, ML systems need <strong>ongoing data validation</strong>. Set up alerts for when data drift exceeds acceptable thresholds. Create dashboards that show key data health metrics over time.</p><p>Think of it like monitoring server health, but for data. CPU usage spikes are obvious; data distribution shifts are subtle but equally dangerous.</p><h3>The ML Testing Strategy That Actually Works</h3><h4>Start Small, Build Up</h4><p>In MLOps, testing is one of the main principles that I consider it the second one after version controlling when starting your machine learning projects (Source: <a href="https://towardsdatascience.com/testing-in-practice-code-data-and-ml-model-cfb1ada81f6c/">Towards Data Science, 2025</a>).</p><p>Begin with the components you understand best. Test your data loading functions first. Then your preprocessing. Then integration between components. Finally, add data validation as a continuous process.</p><h4>Test the Failure Modes</h4><p>Traditional software testing often focuses on happy path scenarios. ML testing must focus on <strong>degradation modes</strong>. What happens when data quality drops by 10%? What if a key feature becomes unavailable? How does model performance degrade under different conditions?</p><p>Build tests that simulate these scenarios. Inject missing values. Corrupt features. Shift distributions. See how your system responds.</p><h4>Automation Is Critical</h4><p>Manual testing doesn’t scale for ML systems. You need automated test suites that run on every code change, every data update, and continuously in production.</p><p>Set up CI/CD pipelines that run your full test suite. Configure monitoring that automatically validates incoming data. Create alerts that trigger when test failures indicate potential model degradation.</p><h4>Key Takeaways</h4><ul><li>ML systems fail silently and gradually, making testing more critical than in traditional software development</li><li>Unit tests should focus on data transformation logic and model assumptions, not just function outputs</li><li>Integration tests must verify the entire pipeline and catch data contract violations between training and serving</li><li>Data validation requires monitoring statistical properties and distributions, not just schema compliance</li><li>Testing failure modes and degradation scenarios is more important than testing happy paths</li><li>Automation and continuous monitoring are essential since manual testing cannot catch subtle data drift</li></ul><p>Testing ML systems feels overwhelming at first, but it’s the foundation of reliable MLOps. Start with one component, write one test, and build from there. Your future self (and your users) will thank you when your models keep working reliably in production.</p><h4>References</h4><p>[1] Towards Data Science. “Testing in Practice: Code, Data and ML Model.” 2025. https://towardsdatascience.com/testing-in-practice-code-data-and-ml-model-cfb1ada81f6c/</p><p>[2] Devender Sharma. “MLOps Test Frameworks: A Guide for Quality Engineers.” Medium, 2024. https://medium.com/@mailtodevens/mlops-test-frameworks-a-guide-for-quality-engineers-695d29b53db8</p><p>[3] Growin. “What Is MLOps? A Top Developer’s Guide to Great AI Deployment in 2025.” 2025. https://www.growin.com/blog/mlops-developers-guide-toai-deployment-2025/</p><p>[4] ACCELQ. “Testing in MLOps: Ensuring Reliable Machine Learning Models.” 2025. https://www.accelq.com/blog/testing-in-mlops/</p><p>[5] Xin Cheng. “MLOps 2025.” Medium, 2025. https://billtcheng2013.medium.com/mlops-2025-eaec6edd7fcf</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=499bd1ec4433" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A/B Testing for Data Scientists: The Statistical Rigor Your Business Experiments Actually Need]]></title>
            <link>https://medium.com/@uvstharun183/a-b-testing-for-data-scientists-the-statistical-rigor-your-business-experiments-actually-need-18fa76ebfec8?source=rss-f29068a00b80------2</link>
            <guid isPermaLink="false">https://medium.com/p/18fa76ebfec8</guid>
            <category><![CDATA[experimentation]]></category>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Vishnu]]></dc:creator>
            <pubDate>Fri, 01 May 2026 04:41:36 GMT</pubDate>
            <atom:updated>2026-05-01T04:45:46.246Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T9L8jnLssppNF7zS" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Most data scientists run A/B tests like they’re flipping coins, not designing scientific experiments. I’ve seen teams declare victory at 85% confidence and others wait for 99.9% certainty on a button color change. Both approaches waste time and money.</p><h3>The Real Cost of Statistical Sloppiness</h3><p>A/B testing isn’t just about p-values and confidence intervals. It’s about making million-dollar decisions with incomplete information. When Netflix tests a new recommendation algorithm, they’re not just optimizing for engagement metrics. They’re betting subscriber revenue against the risk of driving users away.</p><p>I learned this lesson the hard way three years ago. My team “proved” that a new checkout flow increased conversions by 12% after running the test for just five days. We shipped it to 100% of users. Two weeks later, customer support was flooded with complaints about the confusing new interface. The initial spike was novelty bias, not genuine improvement.</p><p>The problem wasn’t our statistical test. It was our statistical thinking. We confused correlation with causation and short-term metrics with long-term value. According to research analyzing 28,304 experiments, only 20% of A/B tests actually reach 95% statistical significance (Source: <a href="https://convert.com/">Convert.com</a>, 2025). Most teams are making decisions on noise.</p><h3><strong>Building Hypotheses That Actually Matter</strong></h3><p>Your hypothesis determines everything that follows. A weak hypothesis produces weak experiments, regardless of sample size or statistical significance.</p><h4>The Business Impact First Approach</h4><p>Start with the business problem, not the feature idea. Instead of “Does changing the button color increase clicks?”, ask “Will reducing cognitive load in the purchase flow increase revenue per visitor?” The first question optimizes for vanity metrics. The second optimizes for business outcomes.</p><p>I now require every hypothesis to include three components: the user behavior change we expect, the mechanism that drives that change, and the measurable business impact. For example: “Reducing form fields from 8 to 4 will decrease abandonment rates by lowering perceived effort, resulting in a 15% increase in completed signups.”</p><h4>Defining Success Metrics Early</h4><p>Pick your primary metric before you see any data. I’ve watched teams cherry-pick favorable secondary metrics when their primary metric showed no effect. This is how you fool yourself into thinking random noise is meaningful insight.</p><p>Your primary metric should directly connect to business value. Conversion rate, revenue per visitor, customer lifetime value. Secondary metrics help you understand the mechanism, but they don’t determine success. Companies with mature A/B testing programs achieve 15–25% uplift in conversion rates by maintaining this focus on business metrics (Source: <a href="https://sparkco.ai/blog/design-ab-testing-statistical-significance">Sparkco AI</a>, 2025).</p><h3>Sample Size: The Mathematics of Confidence</h3><p>Most data scientists underestimate the sample size needed for reliable results. Statistical power calculations seem academic until you’re trying to detect a 2% conversion rate improvement with 95% confidence.</p><h4>The Minimum Detectable Effect Problem</h4><p>You can’t detect arbitrarily small effects with reasonable sample sizes. If your current conversion rate is 3% and you want to detect a 0.1 percentage point improvement, you’ll need over 800,000 visitors per variant. Most businesses don’t have that traffic.</p><p>Instead of designing tests to detect tiny effects, focus on changes that matter. A 10% relative improvement in conversion rate requires much smaller samples and delivers meaningful business impact. According to recent research on statistical convergence, when data follows normal distribution patterns, the sample size requirements scale with the square root of the effect size you’re trying to detect (Source: Deng &amp; Kohavi, 2025).</p><h4>Power Analysis in Practice</h4><p>I run power calculations for every test using a simple formula: n = (Z_α/2 + Z_β)² × 2p(1-p) / (p₁-p₀)², where p is your baseline rate and (p₁-p₀) is the minimum detectable effect. Most statistical packages automate this, but understanding the math helps you make better design decisions.</p><p>For a typical conversion test with 3% baseline rate, detecting a 20% relative improvement (0.6 percentage points) requires about 22,000 visitors per variant at 80% power and 95% confidence. That’s achievable for most businesses within 2–4 weeks.</p><h3>Running Tests That Don’t Lie to You</h3><p>The mechanics of running A/B tests determine whether your results reflect reality or statistical artifacts. Small implementation details create big interpretation problems.</p><h4><strong>Randomization That Actually Works</strong></h4><p>Random assignment sounds simple until you’re dealing with logged-in users, cookie deletion, and cross-device behavior. I’ve seen tests where “random” assignment correlated with user engagement levels because the randomization happened after users demonstrated intent.</p><p>Randomize at the earliest possible point in the user journey. For web applications, this usually means randomization on first page load with persistent cookie storage. For mobile apps, randomize on app installation. For email campaigns, randomize at the user ID level before sending.</p><h4>Avoiding Temporal Confounding</h4><p>Run your variants simultaneously, not sequentially. I learned this lesson when testing email subject lines by running variant A for a week, then variant B the following week. Variant B performed 30% better, but it was Thanksgiving week. The higher open rates had nothing to do with our subject line.</p><p>Calendar effects, marketing campaigns, and seasonal patterns create false signals. Control for these by running both variants concurrently with proper randomization.</p><h3>Statistical Significance: What It Actually Means</h3><p>Statistical significance doesn’t mean your result is practically important. It means you’re confident the difference isn’t due to random chance. I’ve seen statistically significant results that were too small to matter and practically important results that weren’t statistically significant.</p><h4>The 95% Threshold Myth</h4><p>95% confidence isn’t magic. It’s a convention that balances Type I and Type II errors for most business contexts. But it’s not always appropriate. If you’re testing a critical security feature, you might want 99% confidence. If you’re testing button copy, 90% might be sufficient.</p><p>The key insight is that statistical significance is about risk management, not truth discovery. You’re managing the risk of making the wrong decision, not proving that your hypothesis is correct.</p><h4>Multiple Testing Corrections</h4><p>When you track multiple metrics, you increase the probability of finding false positives. With 20 metrics at 95% confidence, you expect one spurious result by chance alone. This is why I limit primary metrics to one or two and apply Bonferroni corrections when analyzing multiple secondary metrics.</p><p>The math is straightforward: if you’re testing k metrics, use α/k as your significance threshold instead of α. For three metrics at 95% confidence, test each at 98.3% confidence (0.05/3 = 0.0167).</p><h3>When to Stop Testing</h3><p>Knowing when to stop a test requires balancing statistical confidence with business constraints. Perfect certainty is expensive and often unnecessary.</p><h4>The Sequential Testing Problem</h4><p>Don’t peek at results and stop early when you see significance. This practice, called “p-hacking,” inflates your false positive rate far above your nominal significance level. If you need to monitor results during the test, use sequential testing methods that adjust for multiple looks.</p><p>I use Optimizely’s sequential testing algorithm, which maintains valid error rates while allowing continuous monitoring. The trade-off is slightly larger sample size requirements, but the business value of early stopping often justifies this cost.</p><h4>Business Context Overrides Statistics</h4><p>Sometimes business constraints matter more than statistical perfection. If you’re testing a Christmas promotion in December, you can’t wait for perfect statistical confidence. Make the best decision you can with available data and document your confidence level.</p><p>The goal isn’t perfect experiments. It’s better decisions under uncertainty.</p><h3>Key Takeaways</h3><p>- Design experiments around business impact, not statistical convenience<br>- Calculate required sample sizes before running tests, not after<br>- Randomize early and run variants simultaneously to avoid confounding<br>- Statistical significance measures confidence, not practical importance<br>- Stop peeking at results unless you’re using sequential testing methods<br>- Business constraints sometimes override statistical perfection</p><p>A/B testing is ultimately about making better decisions faster. Statistical rigor serves that goal, but it’s not the goal itself. The best test is the one that helps you understand your users well enough to build something they actually want.</p><h3>References</h3><p>[1] Casalegno, Francesco. “A/B Testing — A complete guide to statistical testing.” Towards Data Science, January 2025. <a href="https://towardsdatascience.com/a-b-testing-a-complete-guide-to-statistical-testing-e3f1db140499/">https://towardsdatascience.com/a-b-testing-a-complete-guide-to-statistical-testing-e3f1db140499/</a></p><p>[2] Sparkco AI Research Team. “Designing A/B Testing and Statistical Significance for Growth Teams.” Sparkco AI Blog, November 2025. <a href="https://sparkco.ai/blog/design-ab-testing-statistical-significance">https://sparkco.ai/blog/design-ab-testing-statistical-significance</a></p><p>[3] <a href="https://convert.com/">Convert.com</a> Team. “Understanding Statistical Significance in A/B Testing.” Convert Blog, Updated September 2025. <a href="https://www.convert.com/blog/a-b-testing/statistical-significance/">https://www.convert.com/blog/a-b-testing/statistical-significance/</a></p><p>[4] Deng, Alex and Kohavi, Ron. “Statistical Analysis of A/B Tests.” In Causal Inference and Its Applications in Online Industry, 2025. <a href="https://alexdeng.github.io/causal/abstats.html">https://alexdeng.github.io/causal/abstats.html</a></p><p>[5] Machado, Joana, et al. “Statistical Challenges in Online Controlled Experiments: A Review of A/B Testing Methodology.” The American Statistician, 2023. <a href="https://www.tandfonline.com/doi/full/10.1080/00031305.2023.2257237">https://www.tandfonline.com/doi/full/10.1080/00031305.2023.2257237</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18fa76ebfec8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your ML Experiments Deserve Version Control Just as Much as Your Code]]></title>
            <link>https://medium.com/@uvstharun183/why-your-ml-experiments-deserve-version-control-just-as-much-as-your-code-dd79777291fe?source=rss-f29068a00b80------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd79777291fe</guid>
            <dc:creator><![CDATA[Vishnu]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 00:34:09 GMT</pubDate>
            <atom:updated>2026-04-26T00:34:09.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tRhYyfa2KQV3bfKE" /><figcaption>Photo by <a href="https://unsplash.com/@herfrenchness?utm_source=medium&amp;utm_medium=referral">Clarisse Croset</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Most data scientists have a graveyard of model_v2_final_REAL_final.pkl files sitting on a local disk somewhere. I know I did. Then I started treating my experiments like a software engineer treats code, and everything changed.</p><p>The uncomfortable truth is that 85% of ML projects never reach production. A big reason for that is not model quality. It is the chaos that surrounds the model: nobody knows which run produced it, which hyperparameters were used, or whether the training data changed between iterations. MLflow exists to solve exactly that problem, and after spending time learning it properly, I want to walk you through what I wish I had known earlier.</p><h3>The Notebook Archaeology Problem</h3><p>Here is a scenario that will feel familiar. You trained a great model three weeks ago. Your stakeholder now wants to know what features you used, what the validation AUC was, and whether you can reproduce it. You open four Jupyter notebooks, three CSV files, and a Slack thread trying to reconstruct the answer.</p><p>Teams without structured experiment tracking spend an average of 34% of their ML engineering time reproducing past results rather than building new ones. That is more than one day every week, consumed by archaeology instead of progress.</p><p>This is the exact failure mode MLflow prevents. Think of it like Git for your training runs. Just as you would never push code to production without a commit history, you should never ship a model without a logged, reproducible record of how it was created.</p><h3>What MLflow Actually Tracks</h3><p>MLflow’s experiment tracking lets you log four categories of information in every training run:</p><p>Parameters: the hyperparameters you configured, like learning rate, max depth, or regularization strength</p><p>Metrics: performance values like accuracy, F1, RMSE, logged at any point during training</p><p>Artifacts: files generated during the run, including the serialized model, feature importance plots, confusion matrices, or even the dataset snapshot</p><p>Source code: the exact code version tied to that run, so you can always trace back what logic produced what result</p><p>What surprised me the first time I used it was how little code this requires. You add a few lines around your existing training script, and suddenly every run is logged automatically. No custom database, no manual spreadsheet, no guesswork about which hyperparameters you used.</p><h4>A Minimal Working Example</h4><p>Here is roughly what adding MLflow to an existing sklearn pipeline looks like:</p><p>import mlflow</p><p>import mlflow.sklearn</p><p>with mlflow.start_run():</p><p>mlflow.log_param(“n_estimators”, 100)</p><p>mlflow.log_param(“max_depth”, 5)</p><p>model = RandomForestClassifier(n_estimators=100, max_depth=5)</p><p>model.fit(X_train, y_train)</p><p>acc = model.score(X_test, y_test)</p><p>mlflow.log_metric(“accuracy”, acc)</p><p>mlflow.sklearn.log_model(model, “random_forest_model”)</p><p>That is it. Every time you run this, MLflow creates a new run entry with a unique ID, timestamps it, links it to your experiment, and stores everything in a structured format you can query later.</p><h3>The Model Registry: Where Versioning Gets Real</h3><p>Logging experiments is the entry point. The Model Registry is where you start operating like a software engineer.</p><p>The MLflow Model Registry is a centralized model store that manages the full lifecycle of a machine learning model. It provides lineage, versioning, aliasing, metadata tagging, and annotation support to ensure full traceability from development to production deployment.</p><p>Think of it like a release pipeline for models. You do not just dump a .pkl file on a server. You register the model, give it a version number, and move it through defined stages: Staging (ready for integration testing), Production (live and serving traffic), and Archived (retired but kept for auditability).</p><h4>Aliases and Tags Make Collaboration Real</h4><p>One underappreciated feature is the ability to assign aliases and tags to model versions. You can tag a version with dataset and feature_set metadata, then alias it as “champion” or “challenger”. Your serving layer references the alias rather than a hardcoded version number, which means promoting a new model to production is just updating the alias rather than changing deployment config. That is a software engineering pattern applied directly to ML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rdf0eOumrFlca4DN" /><figcaption>Photo by <a href="https://unsplash.com/@avivace?utm_source=medium&amp;utm_medium=referral">Antonio Vivace</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Connecting MLflow to a CI/CD Mindset</h3><p>63% of organizations studied used MLflow Tracking as their initial entry point into broader MLOps transformation. That makes sense, because once your experiments are tracked and your models are registered, the next natural step is automation.</p><p>With a proper MLflow setup, a CI/CD pipeline can trigger a new training run on every code merge, compare the new run’s metrics against the currently registered production model, automatically promote the new version to staging if it passes a performance threshold, and require a human approval step before moving to production.</p><p>This is not hypothetical complexity reserved for big tech teams. MLflow’s APIs make all of this scriptable. And MLflow has earned trust at scale, with over 17 million monthly downloads as of early 2026. The tooling is mature enough to build on.</p><h4>What I Would Do Differently</h4><p>When I first set up MLflow, I made two mistakes. First, I only logged final metrics and forgot to log per-epoch or per-fold metrics. That made it impossible to compare training curves across runs later. Second, I did not version my input data, only my model. If the dataset changes and you do not log a hash or a reference to the exact data snapshot, you lose reproducibility even if the code is identical.</p><p>Now I log a data hash as a parameter on every run, and I log metrics at each cross-validation fold rather than just the mean. Small habits, big payoff.</p><h3>What This Looks Like at Team Scale</h3><p>Solo use of MLflow is valuable. Team use is where the real leverage appears.</p><p>When multiple data scientists are working on the same problem, a shared MLflow tracking server means everyone can see each other’s runs, compare experiments across the team, and avoid duplicating work. The experiment comparison view in the MLflow UI lets you plot metrics from twenty different runs on a single chart and filter by any logged parameter. It is the equivalent of a shared Git history, but for model performance.</p><p>For teams early in their MLOps journey, I would recommend starting with a single shared MLflow tracking server before worrying about Kubernetes, feature stores, or any of the more complex infrastructure. Get the tracking discipline in place first. Everything else builds on top of it.</p><h3>Key Takeaways</h3><p>The biggest hidden cost in ML development is time spent reproducing past results, estimated at 34% of engineering time for teams without structured tracking.</p><p>MLflow logs four things that matter on every run: parameters, metrics, artifacts, and source code version.</p><p>The Model Registry moves you from ad-hoc files to a governed versioning system with staging, production, and archived states.</p><p>Aliases and tags make model promotion programmable and auditable, which is critical for rollbacks.</p><p>Log data references alongside model artifacts. Reproducibility breaks without both.</p><p>Team-level adoption unlocks the real value: shared experiment history, cross-run comparison, and a foundation for CI/CD automation.</p><p>The shift from “I trained a model” to “I have a reproducible, versioned, auditable artifact that I can trace back to a specific dataset and codebase” is not just a tooling upgrade. It is a professional mindset upgrade. MLflow is the tool that makes it practical to get there.</p><h3>References</h3><p>MLflow Documentation. “ML Experiment Tracking and Model Registry.” MLflow, 2025.</p><p>Gulati, Jayita. “MLFlow Mastery: A Complete Guide to Experiment Tracking and Model Management.” KDnuggets, June 2025.</p><p>MarkAICode. “MLflow End-to-End: Experiment Tracking, Model Registry, and GitHub Actions CI/CD.” 2026.</p><p>World Journal of Advanced Engineering Technology and Sciences. “A Comprehensive Analysis of MLflow for MLOps.” Vol. 15, Issue 02, 2025.</p><p>Let’s Data Science. “Master MLflow: From Experiment Tracking to Production.” 2025.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd79777291fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Healthcare NL-to-SQL Agent From Scratch — Here’s What Nobody Tells You About Tool-Calling]]></title>
            <link>https://medium.com/@uvstharun183/i-built-a-healthcare-nl-to-sql-agent-from-scratch-heres-what-nobody-tells-you-about-tool-calling-2c529830f998?source=rss-f29068a00b80------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c529830f998</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[Vishnu]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 02:58:20 GMT</pubDate>
            <atom:updated>2026-04-23T02:58:20.897Z</atom:updated>
            <content:encoded><![CDATA[<p>I am a data scientist working in healthcare. My day job involves SQL queries, Tableau dashboards, and traditional analytics. It is meaningful work helping hospital operations teams make better decisions with data is something I genuinely care about.</p><p>But I also pay attention to where the industry is heading. Over the last year it became clear that the skills driving the most interesting opportunities were shifting toward LLMs, agents, and applied AI systems. I had strong SQL skills, deep healthcare domain knowledge, and years of experience working with real clinical data. I wanted to make sure I was building on top of that foundation, not falling behind it.</p><p>So on weekends I started building things I had never built before. Not tutorials. Not notebooks I would never open again. Real projects with real data that I could actually show someone.</p><p>This article is about the first one.</p><h3>What I Built</h3><p>The project is a multi-tool AI agent that lets anyone ask questions about Medicare prescribing data and clinical guidelines in plain English, with no SQL knowledge required.</p><p>You type something like “How many providers prescribed Metformin in California?” and the agent writes the SQL, runs it against a database of real CMS Medicare records, and explains the answer back to you in plain English. Ask it a clinical question like “What do guidelines say about diabetes dietary management?” and it searches actual NIH clinical guideline documents and synthesizes an answer. Ask a question that needs both and it uses both tools simultaneously, combining structured data with clinical knowledge in one response.</p><p>The stack is Anthropic Claude for the LLM layer, raw tool-calling via the Anthropic SDK (no LangChain), SQLite for the database, ChromaDB for the vector store, FastAPI for the backend, and a custom HTML frontend. The database has real CMS Medicare Part D data. The vector store contains clinical guideline PDFs from NIH.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOtDJ9GQEeQbCmRhOwiNHg.png" /></figure><h3>The Thing Nobody Actually Explains About Tool-Calling</h3><p>Before I built this, I read a lot of articles about AI agents. Most of them describe agents at a high level — the agent “decides” what to do, “calls a tool,” and “returns an answer.” What none of them explained clearly was what is actually happening at the code level.</p><p>Here is the real loop, written out as five explicit steps.</p><p><strong>Step one:</strong> you send the user’s question to Claude along with a description of the tools available. The tool description includes the name of the tool, what it does, and what inputs it accepts. Claude reads all of this.</p><p><strong>Step two:</strong> Claude responds not with an answer, but with a tool call. It says “I want to use the SQL tool and here is the query I want to run.” This comes back as a structured block called a tool_use block in the API response.</p><p><strong>Step three:</strong> your Python code takes that query, runs it against the actual database, and gets real results back.</p><p><strong>Step four: </strong>you send those results back to Claude as a tool_result block. Claude now has the original question, the tool it called, and the actual data.</p><p><strong>Step five:</strong> Claude reads all of that context and generates a final plain English answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HOBoGDm-J2IPtPoNuOZng.png" /></figure><p>That is it. That is the entire agent loop. Every AI agent framework in existence — LangChain, LangGraph, AutoGen, all of them — is just an organized version of those five steps. They write the loop for you so you do not have to. But if you have never written the loop yourself, you do not really understand what the framework is doing, which means you cannot debug it when it breaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*DR3Y39eSIcmB593vq2khxg.png" /></figure><h3>The Mistake That Taught Me the Most</h3><p>About halfway through building this, I ran into a frustrating bug. I asked the agent “How many total claims are there in California?” and it returned zero results. The SQL it generated was correct in structure but it was querying WHERE state = ‘California’ when the data actually stored states as two-letter abbreviations like ‘CA’.</p><p>My first instinct was to fix the code. But the code was not broken. The SQL logic was fine. The problem was that Claude did not know the data used abbreviations because I had not told it.</p><p>I went into the tool description and changed one line. Before it said “state where the provider practices.” After it said “2-letter US state abbreviation such as CA, TX, or NY.” I ran the same question again and the agent immediately generated WHERE state = ‘CA’ and returned the correct answer.</p><p>That experience taught me something important about how LLM agents actually work. The tool description is not documentation. It is part of the code. The quality of the plain English you use to describe your data directly controls the quality of the SQL the agent generates. No amount of prompt engineering elsewhere can compensate for a vague schema description.</p><h3>What the RAG Side Taught Me</h3><p>The second tool in the agent searches clinical guideline documents. I loaded two PDFs from NIH into ChromaDB, chunked them into 500-word pieces, embedded them using a local sentence-transformers model, and built a retrieval function that finds the most relevant chunks for any query.</p><p>What surprised me was how well it worked for genuinely clinical questions. When I asked “What do guidelines say about carbohydrate counting for diabetic patients?” it retrieved a chunk from an ADA dietary guidelines document that contained specific, actionable clinical recommendations. Claude then synthesized that into a clear answer with the source cited.</p><p>The combined query is where it gets interesting. “How many providers prescribed Metformin and what do guidelines say about it?” triggers both tools. Claude calls the SQL tool first, gets the count, then calls the RAG tool, gets the clinical context, and synthesizes both into one coherent response. The agent decided to use both tools without being told to. That emergent behavior was genuinely surprising the first time I saw it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tu4u0IopdPnH2WxtLcmkfw.png" /></figure><h3>Three Things I Would Tell Someone Starting Out</h3><p>The first thing is to build the raw version before using a framework. I know LangChain exists. I know it would have saved me time in some ways. But because I wrote the tool-calling loop myself, I now understand exactly what LangChain is doing under the hood. When something goes wrong in a LangChain agent, I know where to look. Most people who learn LangChain first cannot say the same.</p><p>The second thing is that your domain knowledge is not a disadvantage. I spent years working with healthcare data and felt like that experience was somehow less valuable than software engineering skills. It is not. The reason my agent produces better clinical outputs than a generic demo is because I know what ICD codes are, what CCSR categories mean, and why the difference between brand name and generic drug names matters in a query. That knowledge is embedded in my prompts and it shows in the results.</p><p>The third thing is that the schema description is more important than the model. I tested this multiple times. A precise, detailed description of your data schema will outperform a more expensive model with a vague description every time. Before you upgrade your model, upgrade your prompt.</p><h3>Where To Find the Code</h3><p>Both projects are on my GitHub. The Medicare NL-to-SQL agent is <a href="https://github.com/uvstharun/healthcare-nl-sql-agent">here</a> and the ICD Code Explainer is <a href="https://github.com/uvstharun/icd-code-explainer.">here</a>. The READMEs walk through the full setup if you want to run them yourself.</p><p>I am still building. The next project is a clinical note summarizer, which will be the first time I use LangChain properly now that I understand what it does underneath. If you are working on something similar or want to talk about healthcare AI, I would genuinely like to connect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c529830f998" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Blaming Your Model: Your Imbalanced Dataset Is the Real Problem]]></title>
            <link>https://medium.com/@uvstharun183/stop-blaming-your-model-your-imbalanced-dataset-is-the-real-problem-e55d5a5e799e?source=rss-f29068a00b80------2</link>
            <guid isPermaLink="false">https://medium.com/p/e55d5a5e799e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Vishnu]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 20:01:36 GMT</pubDate>
            <atom:updated>2026-04-19T20:01:36.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3srmigwGGphlbVXb" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Most fraud detection models I’ve seen in the wild are not broken because of the algorithm. They’re broken because nobody handled the class imbalance properly. Here’s what actually works, what I got wrong for years, and what the latest research says about it.</p><h3>Why Imbalance Breaks More Than Your Accuracy Score</h3><p>Let me set the scene. You train a classifier on a dataset where 98% of transactions are legitimate and 2% are fraudulent. Your model hits 98% accuracy. You feel good. You ship it. It flags almost nothing. You’ve essentially built a very expensive rule that says “not fraud” every single time.</p><p>This is the classic trap. Accuracy is useless on imbalanced data, and yet I’ve sat in review meetings where people celebrated 98% accuracy on exactly this kind of dataset.</p><p>The problem runs deeper than the metric. When a model sees 49 negative examples for every positive one, the loss function itself pushes the model to ignore the minority class. Gradient updates from the majority class dominate. The decision boundary shifts. You end up with a model that has never really learned what fraud, churn, or disease looks like.</p><p>The real metrics you should be watching: precision-recall AUC, F1 on the minority class, and Matthews Correlation Coefficient (MCC). These tell you whether your model is actually doing something useful.</p><h3>SMOTE: Powerful but Misunderstood</h3><p>Synthetic Minority Over-sampling Technique has been around since 2002, but I still see it misused constantly. The core idea is simple: instead of duplicating minority class examples, SMOTE interpolates between them to generate synthetic samples. Pick a minority point, find its k-nearest neighbors in feature space, and create new points along the line segments connecting them.</p><p>The appeal is obvious. You get more training data without just repeating the same rows. In practice, it genuinely helps, but the devil is in the details.</p><h4>Where SMOTE fails</h4><p>The standard SMOTE has one big blind spot: it ignores the majority class entirely when generating samples. It happily creates synthetic minority points inside regions that are dominated by majority class examples. Those synthetic points are then ambiguous at best, harmful at worst.</p><p>This is where Borderline-SMOTE and SVM-SMOTE came from. They focus synthetic generation on the decision boundary, where it actually matters. A comparative study across six ML models found that SMOTE and ADASYN performed best overall, with SVM using a linear kernel hitting 99.67% accuracy and a recall of 1.00 on ADASYN-oversampled data.</p><h4>The outlier problem</h4><p>Standard SMOTE gets worse when your minority class contains noisy or anomalous instances. If you have a few extreme outliers in your fraud examples, SMOTE will interpolate toward them and generate synthetic frauds that look like noise. A 2024 study introduced several SMOTE extensions, including Dirichlet ExtSMOTE and BGMM SMOTE, specifically to handle outlier-contaminated minority classes. Dirichlet ExtSMOTE outperformed most existing variants on F1, MCC, and PR-AUC.</p><p>I’ve started using BGMM SMOTE on healthcare datasets where the minority class is small and noisy. The difference in PR-AUC is real and consistent.</p><h4>The most important SMOTE rule</h4><p>Never apply SMOTE to your full dataset before splitting. Apply it only to the training fold. If synthetic samples bleed into your validation or test set, your evaluation is lying to you. Use a pipeline object in scikit-learn or imbalanced-learn to enforce this. I got burned by this mistake on a churn prediction project in 2020. The model looked incredible in cross-validation and fell apart in production.</p><h3>Class Weights: The Underrated Alternative</h3><p>Here is something I wish someone told me early: class weights are often better than SMOTE, and they require zero data manipulation.</p><p>Most sklearn classifiers accept a class_weight parameter. Set it to ‘balanced’ and the library automatically adjusts the loss function to penalize misclassification of the minority class more heavily. The math is straightforward: the weight for class i becomes n_samples / (n_classes * count_i).</p><p>You can also set custom weights. If your churn rate is 5%, try class_weight={0: 1, 1: 20} and tune from there. In XGBoost, the equivalent is scale_pos_weight, which you set to the ratio of negative to positive examples.</p><p>The advantage over SMOTE is that class weights touch nothing about your data distribution. You are training on real data. No synthetic points, no distribution shift, no risk of interpolating across class boundaries in ways that don’t reflect reality. For datasets where the minority class is genuinely sparse and hard to characterize, I almost always try class weights first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O5C_RY5DlEDqYm_o" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve A Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Finding That Surprised Me</h3><p>I have been recommending SMOTE as a default for years. A recent analysis changed my thinking.</p><p>An ICLR 2025 submission found that for most datasets, applying no rebalancing strategy is competitive with tuned models using SMOTE, logistic regression, or LightGBM. That is a striking result. The study does carve out an exception: for highly imbalanced datasets, newer methods like CV-SMOTE and Multivariate Gaussian SMOTE remain competitive. But the broader message is that practitioners are often adding complexity without measurable gain.</p><p>My read: if your imbalance ratio is below 1:10 and your model is a well-tuned gradient boosted tree with scale_pos_weight set correctly, you may not need oversampling at all. Benchmark it. Don’t assume SMOTE helps.</p><h3>Other Fixes Worth Your Time</h3><h4>Undersampling the majority class</h4><p>Random undersampling is fast and works surprisingly well at high imbalance ratios. The cost is throwing away data. Tomek Links and Edited Nearest Neighbors are cleaner alternatives that remove majority class samples near the decision boundary rather than randomly. Use these in combination with oversampling, not in isolation.</p><h4>Threshold tuning</h4><p>This one is free and almost nobody does it properly. By default, classifiers use 0.5 as the decision threshold. On imbalanced data, that is almost certainly wrong. Plot the precision-recall curve, find the threshold that maximizes F1 or whatever metric your business actually cares about, and set it explicitly. I’ve improved production recall by 15 percentage points on fraud pipelines just by shifting the threshold from 0.5 to 0.3.</p><h4>Ensemble methods</h4><p>Balanced Random Forest and EasyEnsemble both resample internally at each iteration. They handle imbalance at the algorithm level, not as a preprocessing step. On tabular fraud datasets, Balanced Random Forest is my go-to when I need something robust out of the box.</p><h4>Domain-specific validation matters</h4><p>A structured analysis of SMOTE variants across healthcare datasets found real limitations in multi-class settings and small or noisy samples. The conclusion: empirical evidence demands domain-specific validation, not blind application of a single technique. This tracks with my experience. What works on a credit card fraud dataset does not automatically transfer to rare disease classification.</p><h3>How I Actually Approach This in Practice</h3><p>My current workflow on any new imbalanced problem: Start with a baseline model using class_weight=’balanced’ and no resampling. Evaluate on PR-AUC and F1 on the minority class only. Try SMOTE inside a proper pipeline and compare. If the minority class is small and noisy, try Borderline-SMOTE or BGMM SMOTE. Tune the decision threshold separately after model selection. Never finalize a model based on accuracy alone.</p><p>The whole process takes maybe two hours of iteration for a new problem. The mistake I made for years was jumping straight to SMOTE because it felt like “doing something.” Sometimes the best fix is just a correctly specified loss function.</p><h3>Key Takeaways</h3><p>Accuracy is a meaningless metric on imbalanced data. Use PR-AUC, F1, or MCC.</p><p>Apply SMOTE only inside your training fold. Never before your train/test split.</p><p>Class weights are often competitive with SMOTE and involve zero data manipulation.</p><p>Recent research suggests that for moderate imbalance, no rebalancing at all can match tuned SMOTE approaches.</p><p>Threshold tuning is free performance. Use it.</p><p>Newer SMOTE variants like Dirichlet ExtSMOTE and BGMM SMOTE handle noisy minority classes better than the original.</p><p>Always validate your rebalancing strategy on your specific domain. Healthcare data behaves differently from financial transaction data.</p><p>The field is still sorting out which techniques actually generalize. What I know from shipping these systems is this: start simple, measure correctly, and add complexity only when the numbers justify it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e55d5a5e799e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>