<?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 Prince Raj on Medium]]></title>
        <description><![CDATA[Stories by Prince Raj on Medium]]></description>
        <link>https://medium.com/@prince.raj1?source=rss-25c846fdce5a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OMD6_TEuVtzpBsqk</url>
            <title>Stories by Prince Raj on Medium</title>
            <link>https://medium.com/@prince.raj1?source=rss-25c846fdce5a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:54:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prince.raj1/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[Building Rock-Solid ML Systems]]></title>
            <link>https://medium.com/swiggy-bytes/building-rock-solid-ml-systems-bb775f8a7126?source=rss-25c846fdce5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb775f8a7126</guid>
            <category><![CDATA[operational-excellence]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[robust-ai]]></category>
            <dc:creator><![CDATA[Prince Raj]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 07:05:54 GMT</pubDate>
            <atom:updated>2025-04-11T07:05:54.694Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Co-Authored with </em><a href="https://medium.com/@prathamesh.agarwal"><em>Prathamesh Agarwal</em></a><em> and special thanks to </em><a href="https://medium.com/@banerjee.soumyajyoti4"><em>Soumyajyoti Banerjee</em></a><em> and </em><a href="https://medium.com/u/7eb9236fe3b9?source=post_page---user_mention--7b9ec0bd7e5f---------------------------------------"><em>Sunil Rathee</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_4Xj78VbOhtXEmtZ" /></figure><h3>Introduction</h3><p>In the fast-paced world of food delivery, machine learning (ML) is the backbone that powers Swiggy’s ability to provide seamless and efficient service to millions of customers. From predicting the estimated time of arrival (ETA) of your order to recommending groceries on Instamart, ML models are integral to our operations. Ensuring the accuracy and reliability of these models is not just a technical challenge but a business imperative. This blog dives into the best practices that underpin Swiggy’s ML operational excellence.</p><p><strong>Key Areas of ML Operational Excellence</strong></p><ul><li><strong>Exploratory Data Analysis (EDA)</strong>: We explore how Swiggy uses EDA to understand data distributions, identify anomalies, and check for drift. Feature selection and engineering are also covered, emphasizing the importance of evaluating categorical features and effective data visualization.</li><li><strong>Sensitivity Analysis</strong>: Sensitivity analysis is highlighted as a method to assess how input variations affect model predictions, ensuring robust performance in production. We discuss testing model robustness, fine-tuning parameters, and setting operating ranges for features.</li><li><strong>Explainable AI</strong>: Explainable AI addresses the “black box” problem by making models understandable. We share how tools like SHAP provide transparency and build trust in AI decisions.</li><li><strong>Coding Standards</strong>: The importance of coding standards, best practices, and documentation to maintain high-quality ML systems is explored.</li></ul><p>Now, let’s explore these four critical practices and how they help Swiggy’s business and product stakeholders make informed decisions, mitigate risks, and deliver exceptional customer experiences through more reliable and transparent ML systems.</p><h3>Exploratory Data Analysis (EDA)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hc6ocQ56iohwueN-" /></figure><p>Exploratory Data Analysis (EDA) forms the cornerstone of Swiggy’s ML operational excellence, beginning with a deep understanding of our data’s fundamental properties. By examining data distributions through statistical techniques and visualizations, our data scientists identify natural patterns and potential anomalies that could affect model performance downstream.</p><p>This distribution analysis naturally leads us to the critical task of anomaly detection. At Swiggy, we’ve refined our approach to identifying outliers by implementing complementary methods:</p><ul><li>Z-scores (Z = (X — μ) / σ): Helps us flag values beyond ±3 standard deviations in normally distributed data</li><li>Adjusted Z-scores (M_i = 0.6745 * (X_i — X̃) / MAD): We found this method reduces false positives by 37% in our skewed datasets where traditional z-scores fall short</li><li>Visual techniques: Box plots and other visualizations provide additional context to our statistical findings</li></ul><p>Once we’ve cleaned our data of anomalies, we must ensure its stability across training and testing environments. This is where our distribution drift checks become essential. The Kolmogorov-Smirnov (KS) test allows us to quantify distribution differences:</p><ul><li>The KS test measures maximum distance between cumulative distributions (D = sup|F₁(x) — F₂(x)|)</li><li>We calculate KS-statistic and p-value for all model features</li><li>Features with KS-statistic &gt; 0.1 are flagged as drifted and removed when evaluation performance may not reflect test set performance</li></ul><p>With clean, stable data in hand, we progress to feature selection and engineering. Our correlation analyses reveal interdependencies that guide the creation of new features, enhancing model accuracy while reducing noise. For categorical features specifically, we employ the Kruskal-Wallis test:</p><ul><li>This non-parametric method determines if samples from different groups have equal distributions</li><li>Mathematically expressed as: H = [12/(N(N+1))] × Σ[R_i²/n_i] — 3(N+1)</li><li>Helps us assess whether categorical features (like restaurant_id or city_id) significantly impact target variables</li></ul><h4>Common Pitfalls and How to Avoid Them</h4><p>Even experienced data scientists can fall into traps during EDA. One common mistake is confirmation bias — it is the tendency to search for, interpret, and recall information that confirms our preexisting beliefs while ignoring contradictory evidence. This common analytical pitfall leads to skewed conclusions and flawed decision-making processes. At Swiggy, we approach each analysis with an open mind, letting the data challenge our assumptions.</p><p>Another pitfall is analysis paralysis — getting so caught up in exploring the data that you never move to action. We set clear objectives for our EDA and timelines for moving to the next step.</p><h4>Bringing It All Together</h4><p>EDA is both science and art — the science of statistical methods and the art of asking the right questions. By combining rigorous analysis with creative thinking, we turn raw data into valuable insights that drive our business forward.</p><p>Remember, the goal of EDA isn’t just to understand your data — it’s to understand your business through your data. When done right, it’s like having a conversation with your data, where each question leads to new discoveries and better decisions.</p><h3>Sensitivity Analysis</h3><p>Sensitivity analysis is a systematic approach to evaluate how variations in input features affect model predictions and outcomes. By methodically altering input values while observing corresponding changes in results, it identifies which features have the greatest influence on model behavior. This technique helps establish effective operating ranges for features, assess model robustness, and implement appropriate guardrails in production environments to manage outliers.</p><h4>Identifying Operating Ranges for Features</h4><p>One of the most practical applications of sensitivity analysis is finding the effective operating range for each feature. Think of this as discovering the “safe zone” where our model performs reliably. When we identify these boundaries, we can implement value capping — essentially placing guardrails on our data.</p><p>For example, if our delivery time prediction model starts behaving erratically when restaurant preparation times exceed 60 minutes (an unusual outlier), we can cap this value at 60 minutes in our production system. This simple technique prevents extreme values from causing wild predictions while maintaining model accuracy for the vast majority of normal cases.</p><p>By systematically testing how our model reacts to different feature values, we can:</p><ul><li>Identify thresholds where feature influence becomes unpredictable</li><li>Create reasonable minimum and maximum boundaries for each feature</li><li>Implement these caps in our preprocessing pipeline</li></ul><p>This approach is particularly valuable in production environments where real-world data often contains unexpected outliers that weren’t present in training data.</p><h4>The “What-If” Game: Making Sensitivity Analysis Tangible</h4><p>At its core, sensitivity analysis is like playing a sophisticated “what-if” game with your model. What if the distance to deliver doubles? What if order volume suddenly spikes? What if the average preparation time changes?</p><p>We quantify these effects using techniques ranging from simple one-at-a-time analysis (changing one variable while holding others constant) to more complex approaches like Sobol indices for measuring interaction effects between features.</p><p>The insights gained often surprise even experienced data scientists. Features we assumed were critical sometimes turn out to have minimal impact, while seemingly minor variables can dramatically affect predictions under certain conditions.</p><h4>Local vs. Global Sensitivity Analysis</h4><p>We conduct two types of sensitivity analysis: Local sensitivity examines how small changes affect predictions in specific cases. This helps us understand individual predictions — particularly useful when explaining model decisions. Global sensitivity looks at feature importance across the entire input space. This broader view helps us understand overall model behavior and identify features that deserve special attention in preprocessing and monitoring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*kYTJA2FEtnWdhpUK" /></figure><p><strong>Sensitivity Analysis for Feature Impact: </strong>This plot shows how variations in <em>stress indicator</em> affect model predictions. As the <em>stress indicator</em> increases, the model’s predicted time also rises, indicating a positive correlation. This suggests that <em>stress indicator</em> plays a crucial role in influencing prediction outcomes. Identifying such patterns helps in setting operational boundaries, fine-tuning models, and ensuring robust decision-making in real-world scenarios.</p><h4>Implementing Sensitivity Boundaries in Production</h4><p>Converting sensitivity insights into production safeguards requires collaboration between data scientists and engineers. Here’s our typical workflow:</p><ol><li>Data scientists identify safe operating ranges for key features</li><li>These ranges are documented and reviewed by subject matter experts</li><li>Engineers implement preprocessing steps that apply these boundaries</li><li>Monitoring systems flag when incoming data frequently hits these boundaries, suggesting either a data quality issue or a need to revisit our model</li></ol><p>This systematic approach ensures our models remain stable even when facing the messiness of real-world data, delivering consistent results our business can rely on.</p><h4>The Balance Between Protection and Information Loss</h4><p>When capping feature values, we carefully balance protection against information loss. Too-aggressive capping might shield the model from outliers but could discard valuable information about legitimate extreme cases.</p><p>We typically validate our capping strategies by comparing model performance with different threshold values, finding the sweet spot where the model remains robust without unnecessarily sacrificing predictive power for valid edge cases.</p><p>Through thoughtful sensitivity analysis and feature range management, we build models that combine the seemingly contradictory virtues of mathematical sophistication and real-world ruggedness — models that not only perform well in controlled environments but continue to deliver value when facing the unpredictable nature of actual business operations.</p><h3>Explainable AI: Taking the Black Box Out of AI</h3><p>We will now explore how Explainable AI (XAI) transforms mysterious algorithms into transparent, understandable tools. This journey takes us from the fundamental problem of AI opacity through practical implementation techniques to real-world applications. By making AI interpretable, we’re not just improving technical systems — we’re building the trust necessary for AI to serve genuine human needs.</p><h4>The “Black Box” Problem: Why AI Explanations Matter</h4><p>Imagine you’re using a GPS app that suddenly routes you through a neighborhood you know is congested. You’d naturally wonder, “Why this way?” Now imagine if your GPS could answer: “I’m routing you this way because there’s construction on the main road, and despite this area normally being busy, current traffic data shows it’s moving well right now.”</p><p>That’s essentially what Explainable AI does for complex algorithms. Instead of just getting an answer, you get the reasoning behind it.</p><p>At companies like Swiggy, AI models make millions of predictions daily — estimating delivery times, optimizing routes, recommending restaurants. But when these predictions seem off, the classic “black box” nature of AI creates frustration. As Einstein wisely noted, “If you can’t explain it to a six-year-old, you don’t understand it yourself.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m6sum00Mt2kUGolc" /></figure><h4>Peeking Inside the Black Box: How XAI Works</h4><p>The breakthrough in making complex models understandable has come through techniques that help attribute predictions to specific inputs. At Swiggy, after experimenting with multiple approaches including LIME and various SHAP methods, we found that Deep Explainer works best for their neural network models.</p><p>Think of SHAP like a financial audit of your model’s decision. It calculates how much each input “contributed” to the final prediction — much like how you might break down where your money went at the end of the month.</p><p>For example, when Swiggy’s model predicts a longer delivery time, SHAP can show exactly how much each factor (traffic conditions, restaurant preparation time, distance, etc.) pushed the prediction up or down.</p><h4>From Theory to Practice: Real-World Implementation</h4><p>Implementing explainability for deep learning models isn’t straightforward, especially when dealing with:</p><ul><li>Complex Network Architectures: Modern AI often uses multi-input, multi-output designs that process different types of data simultaneously.</li><li>Embeddings: These mathematical representations of categorical data (like restaurants or cities) are powerful but notoriously difficult to interpret.</li></ul><p>We tackled these challenges by creating a simplified version of our production model that maintained identical predictions but was structured to work with explainability tools. This involved extracting embedding values and building wrapper functions to ensure the explainer could process the model correctly.</p><p>The results appear in intuitive visualizations:</p><ul><li>Force Plots: Show how each feature pushes a prediction higher or lower</li><li>Waterfall Charts: Illustrate the journey from baseline to final prediction</li><li>Feature Importance Plots: Reveal which inputs matter most across all predictions</li></ul><p>For more info: Please refer to our previous blogs on XAI here — <a href="https://bytes.swiggy.com/we-hate-black-boxes-part-i-64e87ad6b56e">Part 1</a>, <a href="https://bytes.swiggy.com/we-hate-black-boxes-part-ii-44039b4b0ced">Part 2</a></p><h4>Seeing is Believing: XAI in Action</h4><p>In one fascinating test, we changed a single variable — the day of the week from Sunday to Saturday — in a delivery time prediction for Bangalore. The explainer correctly showed that this change increased the predicted delivery time, attributing the increase specifically to the weekday change. This matches our intuitive understanding that Saturday traffic in cities is generally heavier than Sunday traffic.</p><p>These explanations take milliseconds for individual predictions, making them practical for real-time applications. However, generating global explanations across tens of thousands of data points takes longer — a challenge the team continues to optimize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x7EgUQyjkSmc5Keb" /></figure><p>The SHAP waterfall plot explains how different features contribute to the model’s prediction (<strong>f(x) = 25.674</strong>). Features like <strong>feature_62 (+6.72)</strong> and <strong>feature_66 (+4.9)</strong> significantly increase the prediction, while <strong>feature_16 (-5.02)</strong> and <strong>feature_48 (-1.53)</strong> decrease it. Smaller contributions from other features further refine the prediction. This visualization helps in understanding model behavior, improving transparency, debugging, and building stakeholder trust in AI decisions.</p><h4>Transparency: The Bridge Between AI and Humans</h4><p>Explainable AI fundamentally ensures that machine intelligence serves human needs through transparency. By demystifying complex systems, we maintain essential human oversight for responsible AI deployment.</p><p>“We don’t just want our models to be accurate — we want them to be trusted, understood, and aligned with human values.” This approach transforms AI from a mysterious oracle into a collaborative tool that enhances human decision-making capabilities.</p><p>The black box is opening, and what’s inside is not magic but mathematics we can finally understand.</p><h3>Coding Standards</h3><p>Our coding standards form a continuous improvement cycle that begins with structured code, flows through smart implementation, undergoes thorough review, performs rigorous unit testing and concludes with clear documentation.</p><h4>Start With Clean Code</h4><p>We build on a foundation of PEP8-compliant code with consistent formatting. Our notebooks follow a logical structure (imports → constants → functions), using snake_case for functions and PascalCase for classes. This clarity eliminates commented code blocks in production and promotes descriptive naming.</p><h4>Implement With Purpose</h4><p>Building on this foundation, we select the right tools for each job — choosing PySpark over Pandas for large datasets and optimizing with broadcast joins and native transformations instead of UDFs. We protect our data architecture through date partitioning to manage S3 TTL issues, while Dataclasses organize configuration and unit tests validate model reliability.</p><h4>Review Thoughtfully</h4><p>Our code then passes through collaborative review where we block critical issues like DBFS in production and unauthorized S3 writes. Reviews verify our standards are met while distinguishing between blockers and enhancements. Each review becomes a teaching opportunity that strengthens our collective expertise.</p><h4>Unit Testing</h4><p>Unit testing verifies individual components work correctly within data pipelines. It catches mathematical errors early, ensures reproducibility, and serves as executable documentation of expected behavior. For data scientists, thorough testing means confident deployment, reliable models, and clearer collaboration — critical when decisions depend on your code’s accuracy.</p><p>Below is a code snippet for unit testing in TensorFlow:</p><pre># Import necessary libraries<br>import tensorflow as tf  # TensorFlow for numerical computation<br>import logging  # Logging module to manage log levels<br><br># Configure logging to suppress unnecessary warnings<br>logger = spark._jvm.org.apache.log4j  # Access Spark&#39;s logging framework<br>logging.getLogger(&quot;py4j.java_gateway&quot;).setLevel(logging.ERROR)  # Suppress Py4J warnings<br><br># Define a function to perform simple addition of two inputs<br>def transform_outputs(inputs):<br>    &quot;&quot;&quot;<br>    Function: transform_outputs<br>    Purpose: Perform addition of two input tensors.<br>    <br>    Input:<br>        inputs (dict): A dictionary containing:<br>            - &#39;var_a&#39;: TensorFlow tensor (float32)<br>            - &#39;var_b&#39;: TensorFlow tensor (float32)<br>    <br>    Output:<br>        outputs (dict): A dictionary containing:<br>            - &#39;result&#39;: TensorFlow tensor (float32), result of addition.<br>    &quot;&quot;&quot;<br>    outputs = {}  # Initialize an empty dictionary for outputs<br>    outputs[&#39;result&#39;] = tf.add(inputs[&#39;var_a&#39;], inputs[&#39;var_b&#39;])  # Add the input tensors<br>    return outputs  # Return the output dictionary<br><br><br># Define a test case class for the function using TensorFlow&#39;s testing framework<br>class TestTensorFlowFunction(tf.test.TestCase):<br>    &quot;&quot;&quot;<br>    Class: TestTensorFlowFunction<br>    Purpose: Test the functionality of the transform_outputs function.<br>    <br>    Method:<br>        test_transformation: Validates the addition logic with sample inputs.<br>    &quot;&quot;&quot;<br><br>    def test_transformation(self):<br>        &quot;&quot;&quot;<br>        Test Case: test_transformation<br>        <br>        Use Case:<br>            - Inputs: var_a = 1.0, var_b = 4.0<br>            - Expected Output: result = 5.0<br>        <br>        Purpose:<br>            Validate that the function correctly adds two input tensors.<br>        &quot;&quot;&quot;<br>        # Define input tensors for testing<br>        inputs = {}<br>        inputs[&#39;var_a&#39;] = tf.constant([1.0], dtype=tf.float32)  # Input tensor &#39;var_a&#39;<br>        inputs[&#39;var_b&#39;] = tf.constant([4.0], dtype=tf.float32)  # Input tensor &#39;var_b&#39;<br><br>        # Define expected output for comparison<br>        expected_output = {}<br>        expected_output[&quot;result&quot;] = tf.constant([5.0], dtype=tf.float32)  # Expected result<br><br>        # Call the function and get the result<br>        result = transform_outputs(inputs)<br><br>        # Assert that the result matches the expected output<br>        self.assertDictEqual(result, expected_output)<br><br><br># Create an instance of the test case class and manually execute the test<br>test_case = TestTensorFlowFunction()  # Instantiate the test case class<br><br># If there are setup methods in the class, call them first<br>test_case.setUpClass()  # Set up any class-level configurations<br><br># Run the specific test method to validate functionality<br>test_case.test_transformation()  # Execute the transformation test case</pre><p>If the expected output doesn’t match the transformed output, an error message will be generated. Here’s an explanation of the error message:</p><pre>Not equal to tolerance rtol=1e-06, atol=1e-06:<br># This means the comparison between the expected and actual results failed.<br># The relative tolerance (rtol) is set to 1e-06, and the absolute tolerance (atol) is set to 1e-06.<br># The difference between the values exceeds these tolerances.<br><br>Mismatched value: a is different from b.<br># Indicates that the two values being compared (actual and expected) are not equal.<br><br>result: The values being compared are different.<br># Specifies that the mismatch occurred in the &#39;result&#39; key of the output dictionary.<br><br>not close where = (array([0]),):<br># Shows the indices where the mismatch occurs in the array.<br># In this case, it is at index 0.<br><br>not close lhs = [5.]:<br># The left-hand side (lhs) value represents the actual output from the function.<br># Here, the actual value is `[5.]`.<br><br>not close rhs = [2.]:<br># The right-hand side (rhs) value represents the expected output defined in the test case.<br># Here, the expected value is `[2.]`.<br><br>not close dif = [3.]:<br># The difference between the actual and expected values.<br># In this case, `5.0 - 2.0 = 3.0`.<br><br>not close tol = [3.e-06]:<br># The tolerance level for comparison, calculated as `rtol * abs(rhs) + atol`.<br># Here, it is `[3.e-06]`, which is much smaller than the actual difference `[3.]`.<br><br>dtype = float32, shape = (1,):<br># Specifies that both arrays being compared have a data type of `float32` and a shape of `(1,)`.<br><br>Mismatched elements: 1 / 1 (100%):<br># Indicates that 1 out of 1 element in the arrays does not match.<br># This represents a 100% mismatch rate.<br><br>Max absolute difference: 3.:<br># The maximum absolute difference between any pair of elements in the two arrays.<br># Here, it is `3.0`.<br><br>Max relative difference: 1.5:<br># The maximum relative difference between any pair of elements in the two arrays.<br># It is calculated as `abs(lhs - rhs) / abs(rhs)`.</pre><h4>Document Clearly</h4><p>Finally, we complete the cycle with documentation that captures the purpose of each component, specifies parameters and outputs, and explains complex logic. This documentation evolves with our code, ensuring knowledge transfers seamlessly across the team.</p><p>This integrated approach ensures we deliver quality, maintainable solutions that empower efficient collaboration throughout our data science workflow.</p><h3>Conclusion</h3><p>In conclusion, building rock-solid ML systems at Swiggy involves a comprehensive approach that integrates best practices across various stages of the ML lifecycle. From the initial data exploration to ensuring model explainability and maintaining coding standards, each step is crucial for achieving operational excellence and reliability. By focusing on these areas, we can deliver consistent and accurate predictions that enhance the customer experience and drive business success. As we continue to innovate and refine our processes, we remain committed to sharing our insights and learnings with the broader community. Stay tuned for more in-depth discussions and expert tips in our upcoming blogs!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb775f8a7126" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swiggy-bytes/building-rock-solid-ml-systems-bb775f8a7126">Building Rock-Solid ML Systems</a> was originally published in <a href="https://medium.com/swiggy-bytes">Swiggy Bytes — Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>