<?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 venkateshtantravahi on Medium]]></title>
        <description><![CDATA[Stories by venkateshtantravahi on Medium]]></description>
        <link>https://medium.com/@vtantravahi?source=rss-309ac2129d06------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KE6UMOc1LoqgNS2RsTJF4Q.png</url>
            <title>Stories by venkateshtantravahi on Medium</title>
            <link>https://medium.com/@vtantravahi?source=rss-309ac2129d06------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:27:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vtantravahi/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[Machine Learning Deployment Strategy: From Notebook to Production Pipeline]]></title>
            <link>https://vtantravahi.medium.com/machine-learning-deployment-strategy-from-notebook-to-production-pipeline-0555ad231803?source=rss-309ac2129d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/0555ad231803</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[venkateshtantravahi]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 14:40:36 GMT</pubDate>
            <atom:updated>2025-12-10T14:40:36.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iP68NIi9naTygxgpRrUrtQ.png" /><figcaption>Model LifeCycle (Image Credits: <a href="https://www.canva.com/design/DAG1WhH3PYg/tgt8qtZsgw8Y2TsiTDVK0g/view?utm_content=DAG1WhH3PYg&amp;utm_campaign=designshare&amp;utm_medium=link2&amp;utm_source=uniquelinks&amp;utlId=h4f054e6c46">Author Edit</a>)</figcaption></figure><p>You’ve successfully trained your model. The data pipeline is robust, the features are tuned, and your model is achieving <strong>high predictive accuracy</strong> within your development environment. You’ve completed the core work, and the results are compelling.</p><p>Then comes the essential next step: <strong>“It’s time to deploy it to the cloud.”</strong></p><p>This is often where the development process hits a wall. Suddenly, you’re faced with a new vocabulary such as <strong>SageMaker, Kubernetes, REST APIs, Containers, Endpoints, </strong>and the landscape shifts from data science to infrastructure. It’s easy to feel overwhelmed, but this transition is natural and expected.</p><p><strong>Model deployment</strong> is the final, critical stage of the Machine Learning lifecycle. It’s the process that moves your proven model from an isolated experiment into a <strong>live, usable service</strong> that real customers can interact with. Without deployment, your predictive power remains confined to your notebook.</p><p>This guide is designed to bridge that gap. We will systematically clarify the deployment process, ensuring you understand the necessary steps without getting lost in complex cloud engineering.</p><p>You will learn:</p><ul><li><strong>What deployment fundamentally is?</strong> and the key distinctions between development and production environments.</li><li>The essential components: <strong>model artifacts, inference scripts, and containerization.</strong></li><li>How to first establish a functional <strong>local prediction API</strong> (using frameworks like Flask or FastAPI).</li><li>The practical steps for scaling this service to the <strong>Cloud</strong> (e.g., AWS or GCP, Render).</li><li>Professional strategies for <strong>version control and monitoring</strong> to maintain system reliability.</li></ul><p>By the end of this article, you will have a clear, step-by-step understanding of how to transform your trained model into a reliable, low-latency prediction endpoint. You will possess the knowledge required to successfully implement the full ML workflow.</p><h4>Understanding the Core Pieces: What Really Happens When You Deploy a Model</h4><p>Before we dive into deployment commands or cloud dashboards, let’s establish a clear understanding of the <strong>underlying technical components. </strong>What exactly are we placing into production?</p><p>A deployed model is far more than a simple file like .pkl in storage. It is a <strong>structured, encapsulated system</strong> designed to facilitate real-time interaction between your trained algorithm and incoming data. Essentially, you are assembling a minimal application around your model to allow it to communicate reliably with the outside world.</p><p>Let’s break down the essential components that make up this live prediction service.</p><ol><li><strong>The Model Artifact: The Brain</strong></li></ol><p>The <strong>Model Artifact</strong> is the serialized version of your trained algorithm the complete output generated after the training phase.</p><ul><li>This might be a .pkl or .joblib file (for scikit-learn), a .pt or .pth file (for PyTorch), or a saved model directory (for TensorFlow).</li><li>It contains the model’s learned parameters and structural blueprint which is the <strong>intellectual core</strong> of your deployment.</li></ul><p>The critical concept here is that in production, the artifact is <strong>read-only</strong>. You load it into memory to generate predictions, you do not retrain or modify it.</p><p><strong>2. The Inference Script: The Translator</strong></p><p>The <strong>Inference Script</strong> (often named inference.py or app.py) holds the crucial logic for processing requests and generating results. It serves as the translator between the external request and the internal model.</p><p>Its responsibilities include:</p><ul><li><strong>Loading</strong> the model artifact into the server’s memory upon startup.</li><li><strong>Preprocessing</strong> incoming raw data to strictly match the format the model expects.</li><li><strong>Generating</strong> the prediction and <strong>structuring</strong> the output (typically as JSON) before returning it to the user.</li></ul><p>This script is the essential bridge. It dictates the data flow i.e., how inputs arrive, how the prediction is made, and how the results are safely sent back out.</p><p><strong>3. The Environment and Dependencies: The Habitat</strong></p><p>Every model is inextricably linked to a specific software environment. This includes exact versions of libraries (e.g., NumPy, Pandas, TensorFlow), the Python version, and sometimes even OS-level dependencies.</p><p>Defining this <strong>Environment</strong> precisely (via requirements.txt or a conda.yaml) is non-negotiable. This step guarantees that your model executes identically in the production environment as it did during development, eliminating the costly and common “it works on my machine” problem.</p><p><strong>4. Containerization (Recommended Practice)</strong></p><p><strong>Containerization</strong>, primarily using tools like Docker, bundles the entire operational stack such as the code, dependencies, configuration, and runtime into a single, standardized, and lightweight image.</p><ul><li>This process makes your deployed system supremely <strong>portable, reproducible, and ready for any cloud provider</strong>.</li></ul><p><strong>Analogy:</strong> Think of a container as a sealed <strong>shipping manifest</strong> for your model. Everything needed to run the application is locked inside, ensuring it runs consistently regardless of the underlying server infrastructure it lands on.</p><p><strong>5. The Serving Layer or Endpoint: The Gateway</strong></p><p>The <strong>Serving Layer</strong> is the final component, acting as the public-facing gateway for your model. This is where your service accepts external traffic.</p><p>This layer could manifest as:</p><ul><li>A local REST API established using a framework like Flask or FastAPI.</li><li>A serverless compute function (e.g., AWS Lambda, Google Cloud Run).</li><li>A managed service endpoint provided by a platform like AWS SageMaker or GCP Vertex AI.</li></ul><p>This endpoint listens for HTTP requests, directs the data through your inference script, and responds with the prediction, often within a millisecond timeframe. It is the functional proof that your entire system is operational.</p><p>In summary, achieving a robust, deployed ML model requires integrating these distinct elements:</p><blockquote><strong>Model Artifact + Inference Script + Stable Environment + (Optional) Container + Serving Endpoint = A Live Prediction Service.</strong></blockquote><p>By understanding the function of each piece, you can approach deployment confidently, knowing the technical <em>why</em> behind every command and configuration step.</p><h3>The Practical Walkthrough (A Local API Case Study)</h3><p>Now that we understand the theory, let’s shift from concepts to code. We will use the standard <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_california_housing.html"><strong>California Housing dataset</strong></a> provided by Scikit-Learn.</p><p>We have reached the pivotal moment in the machine learning lifecycle.</p><p>In the previous phase, we didn’t just train a model. We built a rigorous experimentation pipeline. Using <strong>MLflow</strong> (as detailed in the attached notebook), we tracked multiple runs, compared hyperparameters, and logged our metrics systematically. We didn’t just pick a model at random, but we scientifically selected the “Best” model that offered the best balance of accuracy (RMSE) and generalizability.</p><p><a href="https://colab.research.google.com/drive/12v0wDFpk_6hvnnN4XJdSdYSo6mSOBJek?usp=sharing">Google Colab</a></p><blockquote><strong>The Training Notebook</strong> Before we write a single line of deployment code, I strongly recommend reviewing the attached <strong>Training Notebook</strong>. It demonstrates a production-grade workflow where we:</blockquote><blockquote>Perform Exploratory Data Analysis (EDA) to select high-value features.</blockquote><blockquote>Use <strong>MLflow</strong> to log experiments, ensuring that if we need to retrain in 6 months, we know <em>exactly</em> what parameters were used.</blockquote><blockquote>Serialize the final “Best” model into a portable .joblib file.</blockquote><blockquote><em>For the rest of this guide, we assume you have successfully run this notebook and have your </em><em>housing_model.joblib file ready.</em></blockquote><p>Now, we must switch hats.</p><p>As a Data Scientist, your goal was to minimize error. As an <strong>Machine Learning Engineer</strong>, your goal is to minimize <strong>friction</strong>. We need to take that static .joblib file and wrap it into a dynamic service that can talk to the outside world.</p><p>Whether it is a frontend React website or a mobile app, clients cannot read a Python pickle file. They speak <strong>JSON</strong> over <strong>HTTP</strong>. Our job is to build that translator.</p><p>We will achieve this using <strong>Flask</strong>, a lightweight and powerful framework that allows us to spin up a prediction engine in seconds.</p><h4>Step 1: The Setup</h4><p>In a production environment, file structure is not a suggestion it is a requirement. A messy directory leads to broken paths and deployment failures. Create a folder named ml-housepricing-prediction and set up this structure:</p><pre>ml-housepricing-prediction/<br>├── model/<br>│   └── housing_model.joblib   &lt;-- (The artifact exported from our MLflow run)<br>├── app.py                     &lt;-- (The inference server script)<br>├── Dockerfile                 &lt;-- (The blueprint for our container)<br>└── requirements.txt           &lt;-- (The dependency manifest)</pre><h4>Step 2: The Inference Script (app.py)</h4><p>This script is the main component of our deployment. It loads the model into memory and defines how the server handles requests.</p><p>We are going to write a robust <strong>Flask</strong> application that handles errors gracefully. If a user sends bad data, we want to tell them <em>why</em> it failed, rather than just crashing the server.</p><p><strong>Create </strong><strong>app.py and add the following code:</strong></p><pre>import pandas as pd<br>import joblib<br>from flask import Flask, request, jsonify<br>import sklearn<br>import numpy as np<br><br># Initialize the Flask application<br>app = Flask(__name__)<br><br># --- 1. Load the Champion Model ---<br># We load the model globally so it stays in memory.<br># Loading it inside the function would be too slow for high-traffic apps.<br>print(&quot;Loading model pipeline...&quot;)<br>try:<br>    model = joblib.load(&#39;model/housing_model.joblib&#39;)<br>    print(&quot;Model loaded successfully.&quot;)<br>except FileNotFoundError:<br>    print(&quot;Error: Model file not found.&quot;)<br><br><br>@app.route(&#39;/&#39;)<br>def home():<br>    &quot;&quot;&quot;Health check route to ensure the app is running.&quot;&quot;&quot;<br>    return jsonify({&quot;status&quot;: &quot;online&quot;,<br>                    &quot;message&quot;: &quot;House Price Prediction API is active.&quot;})<br><br><br>@app.route(&#39;/predict&#39;, methods=[&#39;POST&#39;])<br>def predict():<br>    &quot;&quot;&quot;<br>    Accepts JSON data, creates a DataFrame, and returns a price prediction.<br>    &quot;&quot;&quot;<br>    try:<br>        # --- 2. Receive &amp; Parse Data ---<br>        data = request.get_json()<br><br>        # We extract the specific features our model expects.<br>        # This acts as a filter, ignoring any extra junk data sent by the user.<br>        input_data = {<br>            &#39;MedInc&#39;: data[&#39;MedInc&#39;],  # Median Income<br>            &#39;HouseAge&#39;: data[&#39;HouseAge&#39;],  # Age of the house<br>            &#39;AveRooms&#39;: data[&#39;AveRooms&#39;],  # Avg rooms per household<br>            &#39;AveBedrms&#39;: data[&#39;AveBedrms&#39;],  # Avg bedrooms<br>            &#39;Population&#39;: data[&#39;Population&#39;],  # Block population<br>            &#39;AveOccup&#39;: data[&#39;AveOccup&#39;]<br>        }<br><br>        # Convert to DataFrame (Scikit-Learn expects this format)<br>        input_df = pd.DataFrame([input_data])<br><br>        # --- 3. Generate Prediction ---<br>        prediction = model.predict(input_df)<br><br>        # Calculate the actual dollar value (target was scaled in $100k units)<br>        price_in_100k = prediction[0]<br>        price_in_usd = price_in_100k * 100000<br><br>        # Return the result in a clean JSON format<br>        return jsonify({<br>            &quot;status&quot;: &quot;success&quot;,<br>            &quot;input_features&quot;: input_data,<br>            &quot;prediction&quot;: {<br>                &quot;price_100k_units&quot;: float(price_in_100k),<br>                &quot;estimated_value_usd&quot;: round(float(price_in_usd), 2)<br>            }<br>        })<br><br>    except KeyError as e:<br>        # Handle missing fields (e.g., user forgot &#39;MedInc&#39;)<br>        return jsonify({&quot;error&quot;: f&quot;Missing required field: {str(e)}&quot;}), 400<br>    except Exception as e:<br>        # Handle other unforeseen errors<br>        return jsonify({&quot;error&quot;: str(e)}), 500<br><br><br>if __name__ == &#39;__main__&#39;:<br>    # Run the server locally on port 5000<br>    app.run(host=&#39;0.0.0.0&#39;, port=5000, debug=True)</pre><h4>Step 3: Defining Dependencies (requirements.txt)</h4><p>We need to explicitly list the libraries our project depends on. This ensures that when we move to Docker or the Cloud, the environment is identical to our local machine.</p><p><strong>Create </strong><strong>requirements.txt:</strong></p><pre>flask<br>scikit-learn<br>pandas<br>joblib<br>numpy</pre><h4>Step 4: Containerization (The Dockerfile)</h4><p>This is the step that makes your work “Professional.”</p><p>Instead of asking your colleagues to “install Python and hope for the best,” we package the OS, Python, and dependencies into a <strong>Docker Container</strong>. This container is a standalone unit that will run exactly the same way on your laptop as it does on a massive AWS server.</p><p><strong>Create a file named </strong><strong>Dockerfile (no extension):</strong></p><pre># 1. Base Image: Start with a lightweight version of Python<br>FROM python:3.9-slim<br><br># 2. Work Directory: Create a folder inside the container<br>WORKDIR /app<br><br># 3. Dependencies: Install libraries first<br># We copy requirements.txt separately to leverage Docker&#39;s &quot;Layer Caching&quot;.<br># This makes re-building the container much faster if only your code changes.<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># 4. Application Code: Copy the rest of your files<br>COPY . .<br><br># 5. Launch: Start the Flask server<br># We bind to 0.0.0.0 to ensure the container listens to external requests.<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><h4>Step 5: Build and Run Locally</h4><p>Now, let’s verify everything works. Open your terminal in the project directory.</p><ol><li><strong>Build the Image</strong> We tell Docker to read our requirements and starts up the image. We’ll tag it as house-price-api.</li></ol><pre>docker build -t house-price-api .</pre><p><strong>2. Run the Container</strong> We start the container and map port <strong>5000</strong> on our machine to port <strong>5000</strong> inside the container.</p><pre>docker run -p 5000:5000 house-price-api</pre><p><strong>3. Test the Endpoint</strong> With the container running, we can send a test request. You can use <strong>Postman</strong> or simply run this command in a new terminal window:</p><pre>curl -X POST http://localhost:5001/predict -H &quot;Content-Type: application/json&quot; <br>-d &#39;{&quot;MedInc&quot;: 8.3, &quot;HouseAge&quot;: 41, &quot;AveRooms&quot;: 6, &quot;AveBedrms&quot;: 1, <br>&quot;Population&quot;: 322, &quot;AveOccup&quot;: 2.0}&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6w3V6EoEXUg0nWQvUExWA.png" /><figcaption>Expected Output</figcaption></figure><h3>A Safety Net — Testing Before Release</h3><p>You have a working model in a container. Your validation RMSE looks great. You are ready to go live, right? <strong>Wrong.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*oRXnScpskqNXM_uJ.jpg" /><figcaption>Real Time Meme of ML Deployment (<a href="https://imgflip.com/i/4ca8pe">Image Credits</a>)</figcaption></figure><p>Validation data is history. Production data is the future. They are rarely the same. If you deploy your new model to 100% of users immediately, you risk a catastrophic failure if the model behaves unexpectedly on live data.</p><p>Before we flick the switch, professional ML teams use three strategies to “audit” a model in production without risking user trust.</p><h4>1. Shadow Mode (The “Dark” Launch)</h4><p>This is the safest way to deploy. You deploy your new model alongside the old system (or a dummy baseline), but <strong>you do not show its predictions to the user.</strong></p><ul><li><strong>How it works:</strong> When a user requests a price, the system sends the data to <em>both</em> the old model and your new container.</li><li><strong>The Result:</strong> The user sees the old model’s safe price. Your new model’s prediction is quietly saved to a database (shadow_logs).</li><li><strong>The Stats:</strong> After a week, you compare the shadow_logs against real house sales. If your new model predicted $450k and the house sold for $448k, you have <strong>proof</strong> it works on live data without ever risking a user complaint.</li></ul><h4>2. Canary Deployment (The “Toe Dip”)</h4><p>Once Shadow Mode proves the model isn’t crashing, you roll it out to a tiny fraction of users.</p><ul><li><strong>How it works:</strong> You configure your load balancer to send <strong>95%</strong> of traffic to the old system and <strong>5%</strong> to your new model.</li><li><strong>The Stats:</strong> You monitor that 5% closely. If the server crashes or users complain, you revert instantly. You only affected a handful of people.</li><li><strong>Incremental Rollout:</strong> If the 5% works, you bump it to 10%, then 25%, then 50%.</li></ul><h4>3. A/B Testing (The “Showdown”)</h4><p>Shadow testing checks for <em>errors</em>. A/B testing checks for <em>value</em>.</p><ul><li><strong>How it works:</strong> You split traffic 50/50. Group A gets the Old Model. Group B gets the New Model.</li><li><strong>The Stats:</strong> You don’t just check accuracy, you check <strong>Business Metrics</strong>.</li></ul><blockquote><em>Example:</em> “Did users in Group B click ‘Contact Agent’ more often?”</blockquote><ul><li>If the new model is accurate but confuses users, A/B testing will reveal it before you commit.</li></ul><h3>Going Public — The Cloud Deployment Strategy</h3><p>We currently have a fully functional prediction service running in a container on your local machine. This is a major achievement, but it has a limitation: it only exists on your localhost. To make this model useful to a developer in London or a mobile app user in New York, we need to move it to a public server.</p><p>In a massive enterprise environments, this step involves a complex orchestra of infrastructure. They use <strong>Kubernetes</strong> to manage thousands of container copies, <strong>Load Balancers</strong> to distribute traffic, and <strong>API Gateways</strong> to handle security. While that architecture is powerful, it requires a dedicated DevOps team to manage.</p><p>For our purpose taking a model from a notebook to a live prototype we can bypass that complexity using a <strong>Platform-as-a-Service (PaaS)</strong>. Modern platforms like <a href="https://render.com/"><strong>Render</strong></a>, <a href="https://railway.com/"><strong>Railway</strong></a>, or <a href="https://fly.io/"><strong>Fly.io</strong></a> are designed to speak “Docker” natively. They look at your repository, see a Dockerfile, and automatically build the infrastructure for you.</p><h4>deploying with Render</h4><p>We will use Render for this walkthrough because of its simplicity and generous free tier. The process is surprisingly straightforward because we have already done the hard work of containerization.</p><p>First, ensure your code (the app.py, Dockerfile, requirements.txt, and the model/ directory) is pushed to a public <strong>GitHub repository</strong>. This acts as the source of truth for your deployment.</p><p>Next, head over to <a href="https://render.com/">render.com</a> and create a new <strong>Web Service</strong>. When you connect your GitHub repository, Render analyzes your files. Because it finds a Dockerfile in the root directory, it understands exactly what to do: it will build the image, install the dependencies listed in requirements.txt, and start the uvicorn server using the command we defined.</p><p>You don’t need to configure ports or manage Linux servers. You simply select the “Free” plan and click Deploy. You can watch the logs stream in real-time as the cloud server installs your libraries. Once the build finishes, Render assigns you a secure HTTPS URL (e.g., <a href="https://house-price-predictor.onrender.com)./">https://house-price-predictor.onrender.com).</a></p><p>Your model is now live. You can test it immediately by sending a request to your new public URL:</p><pre>curl -X POST {{base_url}}/predict \<br>     -H &quot;Content-Type: application/json&quot; \<br>     -d &#39;{&quot;MedInc&quot;: 8.3, &quot;HouseAge&quot;: 41, &quot;AveRooms&quot;: 6, &quot;AveBedrms&quot;: 1, &quot;Population&quot;: 322, &quot;AveOccup&quot;: 2.5}&#39;</pre><p>If you receive a JSON prediction back like below, you have successfully bridged the gap between a static data science notebook and a globally accessible production API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jD_Q7gTKi4kCCLxoz5HsAw.png" /><figcaption>Cloud API Testing</figcaption></figure><h3>The Day-Two Problem — Reliability and Maintenance</h3><p>Deploying the model is often celebrated as the finish line, but in professional engineering, it is simply Day One. Once a model is live, the challenge shifts from “making it run” to “keeping it running” and ensuring it continues to add value without breaking the user experience.</p><h4>Managing Risk with “Safe” Deployments</h4><p>One of the biggest misconceptions in deployment is that you simply overwrite the old model with the new one. In the real world, this is dangerous. If your new model has a hidden bug or performs poorly on live data, you could disrupt the service for every user instantly.</p><p>To mitigate this, mature teams use <strong>Shadow Mode</strong> or <strong>Canary Deployments</strong>. In a Shadow Mode deployment, the new model runs quietly in the background, receiving real traffic and making predictions that are logged but never shown to the user. This allows engineers to “audit” the model’s performance on live data for a week before letting it make actual decisions. Alternatively, a Canary Deployment sends the new model to a tiny fraction of users (say, 5%) to test the waters. If the system remains stable, the traffic is gradually increased to 100%.</p><h4>The Architecture of Scaling</h4><p>As your service grows, a single container will eventually hit its limit. If ten thousand users try to predict house prices simultaneously, your application will crash. This is where tools like <strong>Kubernetes</strong> come into play.</p><p>Kubernetes acts as a manager for your containers. It monitors the traffic load, and if it notices a spike, it automatically spins up dozens of new copies (Pods) of your container to handle the demand. Once the traffic subsides, it shuts them down to save costs. Additionally, it provides a “Self-Healing” capability, if your application crashes due to a memory error, Kubernetes detects the failure and instantly restarts the container, often before a user even notices something went wrong.</p><h4>Ensuring Reproducibility and Versioning</h4><p>Finally, we must address the “Time Travel” problem. Six months from now, you may need to retrain this model or debug an issue. If you cannot recreate the exact environment you used today, you are in trouble.</p><p>This is why we version everything. We use <strong>Git</strong> to track changes in our code, ensuring we know which script logic was running on any given day. We use tools like <strong>DVC (Data Version Control)</strong> or S3 versioning to track the datasets, so we know exactly which data was used to train the model. And most importantly, we version the model artifacts themselves. Instead of constantly overwriting model.joblib, we tag releases (e.g., v1.0, v1.1). This three-pillar approach ensures that if the system breaks, you can instantly roll back to a previous, stable state.</p><h3>Conclusion</h3><p>We started this article with a common scenario, a high-performing model trapped inside a Jupyter Notebook, offering zero value to the outside world.</p><p>Through this guide, we broke down the walls between Data Science and Engineering. You didn’t just write code, you built a pipeline. You established a contract with <strong>Flask</strong> to sanitize inputs, you packaged your environment with <strong>Docker</strong> to guarantee reproducibility, and you leveraged the cloud to turn a local script into a global service.</p><p>This transition is what separates a model trainer from a Machine Learning Engineer. The reality of production ML is that the modeling code part we often obsess over is actually the smallest part of the system. The real challenge, and the real value, lies in the surrounding infrastructure, the serving, the monitoring, and the reliability.</p><p>You now possess the blueprint. The infrastructure landscape will change tools like Kubernetes and SageMaker will evolve but the fundamental principles of <strong>Portability (Docker)</strong> and <strong>Interoperability (APIs)</strong> will remain the same.</p><p>Start small. Ship your first endpoint. Watch it fail, fix it, and iterate. That is the only way to truly learn.</p><h4>Further Reading &amp; References</h4><p>Deployment is a vast field. Here are three “Gold Standard” resources I recommend to deepen your understanding of MLOps and Engineering:</p><ul><li><a href="https://papers.nips.cc/paper/2015/file/86df7dcfd896fcaf2674f757a2463eba-Paper.pdf"><strong>Hidden Technical Debt in Machine Learning Systems</strong></a> <em>(Paper, Google)</em> — This is the most famous paper in MLOps. It explains why “just deploying” is dangerous and how to avoid long-term maintenance nightmares.</li><li><a href="https://12factor.net/"><strong>The Twelve-Factor App</strong></a> <em>(Manifesto)</em> — A classic guide on building software-as-a-service apps. It covers best practices for config, backing services, and logs that every engineer should know.</li><li><a href="https://martinfowler.com/articles/cd4ml.html"><strong>Continuous Delivery for Machine Learning (CD4ML)</strong></a> <em>(Article, Martin Fowler)</em> — An excellent deep dive into how to automate the training and deployment process so you never have to manually copy files again.</li></ul><h3>Thanks for reading!</h3><p>If this guide helped you move your first model to production, I’d love to hear about it. Please <strong>give this article a clap 👏</strong> and <strong>subscribe</strong> to follow along.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0555ad231803" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Before You Build That Credit Model, Read This: What Nobody Tells You About Risk, Policy, and People]]></title>
            <link>https://vtantravahi.medium.com/before-you-build-that-credit-model-read-this-what-nobody-tells-you-about-risk-policy-and-people-a441610161e4?source=rss-309ac2129d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/a441610161e4</guid>
            <category><![CDATA[financial-risk-management]]></category>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[responsible-lending]]></category>
            <category><![CDATA[underwriting]]></category>
            <category><![CDATA[credit-risk-modelling]]></category>
            <dc:creator><![CDATA[venkateshtantravahi]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 04:25:44 GMT</pubDate>
            <atom:updated>2025-10-08T04:25:44.177Z</atom:updated>
            <content:encoded><![CDATA[<p><em>(Part 5.2 of the Credit Risk Modeling Series. if you missed </em><a href="https://medium.com/@vtantravahi/turning-raw-data-into-meaningful-features-the-feature-engineering-process-ed0dc378fe96"><em>Part 5.1: Turning Raw Data into Meaningful Features</em></a><em>, start there to see how data transforms before decisions.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arVWpPN4Ua0ErFPqSpIKYg.png" /><figcaption>Risk Policies Evaluation Illustration (Credit: Generated by Canva AI)</figcaption></figure><h4>Introduction: What Happens Before the Model?</h4><p>Ever think <strong>credit risk modeling</strong> is all about fancy algorithms and shiny dashboards? It’s not.</p><p>Here’s the truth the real action happens <em>before</em> the first line of code is even written. It starts in quiet boardrooms where teams argue over who deserves a loan, how much risk is “acceptable,” and what fairness really means when money’s on the line.</p><p>That’s where the magic (and the mess) of <strong>credit strategy</strong>, <strong>underwriting</strong>, and <strong>responsible lending</strong> unfold.</p><p>I’ve sat in those meetings where data scientists talk about AUC scores, and the business team just wants fewer charge-offs. Where someone throws around “risk appetite” like it’s a snack, and compliance quietly reminds everyone, “Don’t forget <a href="http://Equal Credit Opportunity Act (Regulation B)  CFPB (.gov) https://www.consumerfinance.gov › regulations">ECOA</a>.”</p><p>This isn’t just about predicting who defaults. It’s about defining <em>how you treat people</em> before they ever become a number in your model.</p><p>So grab your coffee, because we’re going to talk about the side of credit modeling nobody explains in ML courses the strategy, the policy, and the human judgment that keep this whole system running.</p><p>And if you’ve ever wondered why your perfectly tuned PD model got shelved, this will make it click.</p><h4>Credit Strategy: The Business Behind Every Model</h4><p>A <strong>credit strategy</strong> is basically the company’s philosophy about who it wants to lend to and who it doesn’t. It’s not written in Python, it’s written in board decks and risk memos.</p><p>Some lenders play it safe. They approve fewer loans, use tighter rules, and sleep better at night. Others swing for growth. They approve more people, offer higher limits, and accept that some loans will go bad.</p><p>I once worked with a lender who said, “We’d rather lose a little than miss a good customer.” That was their <a href="https://productschool.com/blog/analytics/north-star-metric#:~:text=A%20North%20Star%20Metric%20(NSM,compass%20for%20your%20product%20strategy.">northstar growth</a> over perfection and every data decision, from cutoffs to thresholds, reflected that.</p><p>That’s the thing your model isn’t the strategy, it’s how you <em>apply</em> the strategy. A model trained for a conservative bank behaves totally differently when plugged into an aggressive fintech system. Same math but different mindset.</p><p>So before you optimize, ask “Who are we trying to serve, and what risk are we willing to live with?” That’s the real foundation of <strong>credit risk modeling </strong>not the code, but the call.</p><h4>Underwriting: Where Data Meets Human Judgment</h4><p>Underwriting is the main part of lending. It’s the process that turns data into a decision either a <em>yes</em> or a <em>no</em> or <em>maybe</em>.</p><p>Old-school underwriting was manual someone would peak over bank statements, pay slips, and tax returns while sipping lukewarm coffee at 10 p.m. Then came rule-based systems “No bankruptcies in two years,” “Minimum income $30,000,” and so on.</p><p>Now we’ve got automated underwriting platforms combining bureau data, transaction feeds, and PD scores. It’s fast, scalable, and consistent but it still has one thing in common with the old ways judgment.</p><p>Because even with a great model, borderline cases still need a human look.<br> I’ve seen underwriters approve people that a model rejected and they turned out to be some of the best-performing borrowers in the book. That’s the part tech folks often miss. <strong><em>Models don’t replace underwriting</em></strong>. They power it.</p><h4>Portfolio Management: When the Loans Start Talking Back</h4><p>Approving loans is exciting. Managing them? That’s where reality checks in.</p><p><strong>Portfolio management</strong> means tracking what happens <em>after</em> the money leaves the building. You group accounts by segments prime, near-prime, subprime and watch how they behave. You track stuff like:</p><ul><li><strong>Delinquency rates — </strong>who’s 30, 60, 90+ days late.</li><li><strong>Charge-offs</strong> — loans you’ve given up on.</li><li><strong>Non-performing loans (NPLs)</strong> — the ones sitting idle.</li></ul><p>I once saw a dashboard light up red for a single month’s originations. Turned out, a small policy tweak had loosened the score cutoff just for that batch. Tiny change, huge effect. That’s how sensitive credit systems are.<br> And those metrics? They become your next model’s labels. If your definition of “bad” shifts, your model’s personality changes too.</p><p>So yeah, the model’s not the end. <em>It’s just a part of a much bigger loop learn, adjust, repeat</em>.</p><h4>Credit Policies and Decision Rules: The Hidden Playbook</h4><p>If strategy is the “why,” credit policy is the “how.” Policies are the rulebook that turns business goals into actual decisions. They’re full of conditions like:</p><ul><li>“Minimum credit score 680.”</li><li>“No collections in the last 12 months.”</li><li>“If PD &lt; 0.05, fast-track approval.”</li></ul><p>You’ve got <strong>hard cutoffs</strong>, <strong>soft overrides</strong>, and <strong>manual review zones</strong>. Here’s the thing your model doesn’t make the rules. It plays by them.<br> If policy says no, no amount of predictive genius can change that.</p><p>I’ve seen entire data teams puzzled over why approvals dropped after deploying a “better” model. Turns out, the new score distribution didn’t align with the policy logic same customers, different thresholds. Credit policies and modeling have to talk to each other. Otherwise, you’ll have a perfect algorithm solving the wrong problem.</p><h4>Responsible Lending: Doing the Right Thing, Even When It’s Hard</h4><p>Here’s where the math meets morality. Lending isn’t just about profit it’s about fairness and accountability. In the U.S., acts like <strong>ECOA</strong> and <strong>FCRA</strong> say you must treat applicants fairly, explain decisions clearly, and use data responsibly.</p><p>That means if you deny someone credit, you owe them an <strong>Adverse Action Notice (</strong>which we’ll cover in upcoming parts<strong>)</strong> explaining why. And that reason better make sense to a normal human being, not just to your SHAP plot.</p><p>Once, during a model audit, we discovered one feature geographic region correlated with income in a way that skewed scores for certain groups. It wasn’t malicious, it was statistical. But we fixed it anyway. Performance dipped a bit, but trust went up.</p><p>Responsible lending isn’t about looking good. It’s about staying <em>good </em>compliant, explainable, and fair.</p><h4>Modeling: Where Everything Connects</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zc4-P32VyqMabMxLfqnlDw.png" /></figure><p>Now we circle back to the part everyone loves the actual <strong>Credit Risk Model</strong>. This is where everything upstream comes together:</p><ul><li><strong>Strategy</strong> defines your goal.</li><li><strong>Policy</strong> defines your boundaries.</li><li><strong>Data</strong> defines your possibilities.</li></ul><p>And together, they define your model. So before you build:</p><ul><li>Ask how “default” is defined — 90 DPD? Charge-off?</li><li>Check what data you’re allowed to use.</li><li>Make sure your features align with business logic.</li></ul><p>I’ve seen models with 0.90 AUCs sit in uncertainty for months because they weren’t explainable or policy-compliant. High accuracy doesn’t mean high usability. The best models are the ones that pass audits, stay stable, and actually <em>run</em> in production without any uninterpretable decisions.</p><h4>The Big Picture: Credit Is Human</h4><p>At the end of the day, <strong>Credit Risk Modeling</strong> isn’t a math problem it’s a people problem solved with math. It starts with how much risk you’re comfortable with. It ends with how fairly you treat people when you say “yes” or “no.”</p><ul><li>Data science gives structure.</li><li>Business gives context.</li><li>Policy gives boundaries.</li></ul><p>When all three align, the model doesn’t just predict it <em>works</em>. So next time someone says, “Can you build a PD model?”, ask them first</p><p><strong><em>“Sure. But what’s your strategy, policy, and fairness stand?”</em></strong></p><p>That’s the difference between a data scientist and a risk professional.</p><h4>Some of my Favorite FAQs</h4><ol><li><strong>What’s the real difference between credit strategy and underwriting?</strong><br> Credit strategy defines the <em>direction </em>who to lend to and why.<br> Underwriting handles the <em>decision </em>how to apply that logic to each applicant.</li><li><strong>Why do models need to be explainable?</strong><br> Because regulations like ECOA and FCRA require lenders to explain credit decisions. If your model’s reasons don’t make sense to a human, it won’t pass compliance review.</li><li><strong>How can lenders balance fairness and accuracy?</strong><br> By testing for bias early, using interpretable features, and being transparent about trade-offs. Slightly lower accuracy is worth long-term trust and regulatory safety.</li></ol><h4>Final Words</h4><p>Credit Risk Modeling isn’t just an experiment. It’s a system built by people trying to balance trust, profit, and fairness among different aspects all at once.</p><p>While the math behind it always gets the attention, but it’s the <em>mindset</em> that decides how the math is being used. Every number a model predicts or learns out carries someone’s judgment, a policy choice, a business decision, or a belief about who deserves a chance.</p><p>When you see it that way, modeling stops being just data science experiment. The best models are not just accurate they’re aligned with the company’s values, the customer’s reality, and the regulator’s expectations. That’s where real credit innovation happens not by pushing limits of algorithms, but by connecting human reasoning with responsible automation.</p><p>If you’re in this space, don’t just build better models rather build better <em>decisions</em>. Ask the tougher questions:</p><ul><li>Are we fair in how we define “risk”?</li><li>Are our policies helping or hiding bias?</li><li>Are we measuring success the same way our customers feel it?</li></ul><p>Because the future of lending is not about who predicts best it’s about who decides best. So next time you’re staring at a ROC curve, remember behind every point on that line is a person who trusted you with their data and their story. Treat it like it matters because it does.</p><p>And if this conversation made you see credit modeling a little differently, drop a thought, share it with a teammate. That’s how better models and better lenders get built.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a441610161e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning Raw Data into Meaningful Features — The Feature Engineering Process]]></title>
            <link>https://vtantravahi.medium.com/turning-raw-data-into-meaningful-features-the-feature-engineering-process-ed0dc378fe96?source=rss-309ac2129d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed0dc378fe96</guid>
            <category><![CDATA[datascienceinfinance]]></category>
            <category><![CDATA[model-explainability]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[credit-risk-modelling]]></category>
            <category><![CDATA[ml-in-finance]]></category>
            <dc:creator><![CDATA[venkateshtantravahi]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 01:52:43 GMT</pubDate>
            <atom:updated>2025-08-26T01:52:43.611Z</atom:updated>
            <content:encoded><![CDATA[<h3>Turning Raw Data into Meaningful Features — The Feature Engineering Process</h3><p>Ever wondered how raw messy, real world data turns into the clean, meaningful features that powers credit risk models? In the last few parts of this series, we looked at what credit risk means, where the data comes from, how we define outcomes like default, and how we evaluate feature strength using tools like Information Value (IV) and Weight of Evidence (WoE).</p><p>But now we really step into the real world of modeling i.e., How do we actually create features that help a model to decide whether to approve or reject a loan?</p><p>If you’re new to series or missed earlier parts, check out my <a href="https://vtantravahi.medium.com/">medium profile</a> to explore the full series so far. However, in this article we’ll break down the feature engineering process not just as a modeling step but as a core part of how credit decisions are made in the real world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKtP2Yt9yP5Z6JKyJ4Umvg.png" /><figcaption>Data Sources to Transforming and Storing (Credit: Author )</figcaption></figure><h4>What does “Feature Engineering” actually mean?</h4><p>In machine learning, features are the input variables used by a model to make predictions to simply put they are “what” a model learns from. But in real world raw data isn’t always clean, meaningful, or directly usable. It’s often messy, inconsistent and not in the form that models can understand. That’s where we engineer or try to come up with features or variables which model can learn. To put this as in definition</p><blockquote>Feature Engineering is the process of converting raw, real-world data into structured and meaningful inputs (features) that improve the accuracy, interpretability and reliability of a predictive model.</blockquote><p>Think of it as preparing ingredients before cooking a meal. Raw Ingredients (data) need to be peeled, chopped, or seasoned (transforming process) before they can become a proper dish (model). Let’s say that you’re working on with this raw data from a loan applicant</p><pre>| Field                    | Raw Value  |<br>|--------------------------|----------- |<br>| date_of_birth            | 1995-06-12 |<br>| credit_balance           | $4,300     |<br>| credit_limit             | $10,000    |<br>| missed_payments_12months | 3          |<br></pre><p>None of these on their own tell the full story. But if we transform them into features such as</p><ul><li>age = current_year — birth_year → 30</li><li>credit_utilization_ratio = balance/limit → 0.43</li><li>deliquency_rate = missed_payments / 12 → 0.25</li></ul><p>now these represent the language which is easy to understand and interpret by the models as well as humans. But have you ever thought with the progress in technology and computing can’t we make the models understand the raw data without feature engineering? well the simple answer is no because</p><ul><li>Models don’t understand dates, categories, or strings natively.</li><li>Patterns often lie in combinations, ratios, or historical trends not in raw values.</li><li>Models need numerical, clean and scaled inputs from learn effectively.</li></ul><h4>From a Credit Risk Business Perspective</h4><p>Let’s think in the world of lending and credit modeling perspective, suppose you’re building a model to predict the first common question we already talked about is</p><blockquote>Will this customer default on their loan in next 12 months?</blockquote><p>But every different role care about the same data in different ways like a <em>data scientist always care about extracting signals, reducing noise, encoding features, checking missing values or normalizing inputs</em>. However, a <em>risk analyst or lender from same organization care about understanding borrowing behavior, repayment reliability, employment stability, overuse of credit</em>. So instead of feeding raw fields like job_title or payment_due_dates , you might try to come up with features like</p><ul><li>employement_stability_score from time in current job and frequency of switching.</li><li>repayment_ratio from total paid and expected paid/current balance.</li><li>recent_credit_activity_score from number of inquiries in last 3 months.</li></ul><p>This alignment is where features connect business understanding to model variables is where the good feature engineering lies in. Some key characteristics while designing good features are:</p><ol><li><strong>Predictive:</strong> Which helps distinguish between good and bad outcomes.</li><li><strong>Interpretable:</strong> Easy to explain to a human (especially important for regulators).</li><li><strong>Stable:</strong> Performs consistently across the whole population segment.</li><li><strong>Business aligned:</strong> Makes sense from a lending/risk strategy perspective.</li></ol><blockquote>Data is just raw facts. Features are the logic that turns those facts into insights.</blockquote><p>In Credit risk, a good feature isn’t just a mathematical derived number but also should reflect the real world business or behavior that signals financial reliability or risk.</p><h4>Types of Feature Engineering ( Credit Risk Context )</h4><p>When you’re working with raw financial or behavioral data, the possibilities for transforming that data into useful features are endless. But to make it easier, we can organize feature engineering into several common buckets or categories. Some of the most commonly used one’s are explained below..</p><ol><li><strong>Basic Numerical Features: </strong>Direct use of existing numerical data, sometimes cleaned or normalized. For example, age , income , credit_amount , loan_term_months and we mostly do handling missing values, normalize scale (if needed), apply log transforms if <a href="https://builtin.com/data-science/skewed-data"><strong><em>skewed</em></strong></a>. A suggestion is that ‘Age’ might be usable as-is, but sometimes you group it (binning) for model simplicity and explainability.</li><li><strong>Ratio Based Features:</strong> Which are calculated as the <strong>proportion of two related fields</strong>. For example, credit_utilization = current_balance / credit_limit or installment_to_income_ratio = monthly_installment / income because ratios often show behavior better than raw values. Let’s think this way that someone with $5000 in credit card balance and $10,000 limit is very different from someone with same balance but only a $6000 limit.</li><li><strong>Categorical Encoding: </strong>Converting non numerical data like job_title , marital_status , or home_ownership into model friendly forms. Here we often use techniques such as <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html"><strong>label encoding</strong></a> (for tree based models), <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html"><strong>one-hot encoding</strong></a> (each category gets its own column), <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.TargetEncoder.html"><strong>target/mean encoding</strong></a> (risky fo leakage). For example, job title = engineer -&gt; job_title = 1, all others = 0.</li><li><strong>Time Based/ Recency Features: </strong>Features that are derived from time stamps or date history. For example, days since last missed payment, months since last loan approval, time in current job etc., these behaviors often reveal the creditworthiness of a individual because let’s think this way that a missed payment 3 years ago matters less compared to the one last month.</li><li><strong>Count / Frequency Features: </strong>Number of times an event occured over a period. For example, number of loans opened in last 12 months, number of credit inquiries, or count of delinquent accounts etc., these features help reflect activity level or behavior patterns.</li><li><strong>Aggregated Behavioral Features: </strong>Features which are derived from summary statistics over time or accounts. For example, average monthly spend over last 6 months, Max delinquency days in past year, or Min payment-to-balance ratio over past 3 months etc., these often come from longitudinal account data or bureau reports and require historical tracking.</li><li><strong>Derived Bins &amp; Risk Buckets (Binning): </strong>Converting continuous features into risk buckets (for e.g., 0–10%, 10–30% utilization). These buckets help improving explainability, helps with non-linearity, common in scorecards. For binning we can either use domain rules such as age &lt; 25 -&gt; young or use optimal binning techniques (e.g., IV/WoE or decision trees).</li><li><strong>Interaction Features: </strong>Combine two features to capture deeper patterns. for example, age * credit_utilization or loan_amount / income * num_dependents etc., but sometime we might also leak some patterns while overlooking at these calculations feeding unwanted information to model so being aware of these could help us a lot.</li><li><strong>Missing Value Indicators: </strong>Sometimes missing data is the signal for example, if employment history is missing, it mean informal income might become a riskier profile. Try converting such features to binary or sometimes categorical.</li></ol><p>You might feel does anyone do explore these much further down for features or building them as deep as possible but ya not every project needs all of these but being aware of them helps you explore your data more creatively and responsibly.</p><h4>The Step-by-Step Process</h4><p>Feature engineering isn’t a one-click step in your pipeline. It’s a process that evolves alongside your understanding of the data, the business logic and the modeling goals. Here’s how it typically plays out in real world projects with a blend of data understanding and domain reasoning.</p><ol><li><strong>Understand the business and target: </strong>will inform what kind of features will be relevant. For instance, delinquency patterns matter more in PD models than in pricing models.<strong><br>- </strong>What is the model predicting? is it PD, charge-off or fraud?<br>- Is it used for loan approval, limit assignment, or pricing?<br>- What’s the definition of “default”? (90+ DPD, charge-off flag, etc.)</li><li><strong>Exploring Raw Data Thoroughly: </strong>For example, “employement_since” might look weird until you check its categorical encoding like “≥ 7 years”, “unemployed”.<br>- Check distributions, outliers, missing values.<br>- Group fields into demographics (age, job, housing), Behavior (payments, utilization), Historical bureau data (credit history).<br>- Identify date fields for trends or <a href="https://www.investopedia.com/terms/r/rfm-recency-frequency-monetary-value.asp">recency features</a>.</li><li><strong>Define Modeling Rules and Constraints: </strong>This help more proper way of designing features as scorecards need monotonic, interpretable features compared to tree based models.<br>- What model are you planning to use? (Scorecard? LightBGM? XGBoost?)<br>- Do you need explainable features (like WoE bins)?<br>- Are you building a production pipeline or POC?</li><li><strong>Engineer Features and transformations: </strong>Each level adds some depth towards your data but also make sure to think twice before thinking of a features sometimes adding more complexity to models will overfit.<strong><br>- </strong>Clean missing, fix types, standardize formats.<br>- Calculate utilization, buckets of age or balance.<br>- 3-month averages, recency flags, max delinquency days.<br>- Risk adjusted ratios, behavioral combinations.</li><li><strong>Evaluate Feature Quality (Statistical + Business): </strong>While evaluating features somethings you always need to ask is <br>- Does it separate goods vs bads in terms of borrowing?<br>- Does it make business sense?<br>- Is it stable over time? <br>and you can use some tools to answer these like<br>- Information Value (IV) for statistical power of a variable.<br>- Weight of Evidence (WoE) for interpretable patterns.<br>- PSI (Population Stability Index) across months to detect data drift.</li><li><strong>Handle Missing and Noisy Data<br>- </strong>Impute missing values thoughtfully (don’t fill income with median/mean blindly)<br>- Create missing flags if patterns seems important<br>- Filter out rare categories (e.g., ZIP codes used by &lt; 0.1% customers)</li><li><strong>Validate Stability and Business Feedback<br>- </strong>Show and validate with stakeholders like risk analysts or underwriters asking “does this make sense”?<br>- Backtest on different time slices.<br>- Validate that engineered features aren’t just <strong>overfitting quirks</strong>.</li><li><strong>Document and Modularize: </strong>In real projects, features may get reused across models. Keep them reusable.<br>- Document logic behind each feature: “Why does this exists?”<br>- Version your transformations using notebooks, scripts, or features stores.<br>- Track dependencies: if source column changes, can we retrace the logic?</li></ol><h4>Some Examples of Engineered Features in Credit Risk</h4><p>Now that we’ve outlined the process of feature engineering, let’s see what it actually looks like in the action. These are real patterns and transformations that credit risk teams across banks, fintechs, and lending platforms use every day to assess risk , improve predictions, and comply with regulatory standards.</p><ol><li><strong>Delinquency Flags: “</strong>Has the customer ever missed a payment in the past few months?” usually used in PD models to capture the historical repayment behavior.<br>- has_dpd_30_plus_last_3m = 1 if max(DPD_last_3_month) &gt;= 30 else 0 <br>- ever_dpd_90_plus = 1 if any(DPD) &gt;= 90 else 0</li><li><strong>Utilization Ratios: “</strong>How much of the the available credit does the customer actually use?<strong>” </strong>because higher utilization may signal increased credit dependency or stress.<br>- current_utilization = current_balance / credit_limit <br>- max_utilization_last_6m = max(balance / limit) over last 6 months</li><li><strong>Recency Based Features:</strong> “When was the last time the customer made a payment?” because it can be a powerful predictor of recovery of further default.<br>- days_since_last_payment <br>- months_since_last_dpd_30_plus</li><li><strong>Income Stability: </strong>“How stable is the customer’s income or employment?” because volatility in income can signal risky borrowers.<br>- employement_bin = map(employement_status to ordinal scale) <br>- avg_income_variance = std(income_last_6m) / mean(income_last_6m)</li><li><strong>Behavioral Trends: “</strong>Is the customer improving or declining?” which can help model understand whether customer is trending towards risk or stability.<br>- spending_trend_3m = (sum(amount_m3) — sum(amount_m1)) / 3 <br>- credit_limit_changes = number of times limit increased or decreased</li><li><strong>External Credit Signals: “</strong>What does the bureau say?<strong>” </strong>these are often merged from Equifax, Experian, or TransUnion feeds.<br>- num_open_loans_bureau , bureau_dpd_60_plus_count <br>- bureau_score_bucket = derived from external credit score</li><li><strong>Categorical Bucketing: “</strong>Does the customer fall into riskier groups?” this is helpful in segment-level PD calibration and marketing offers.<br>- region_risk_bucket = map(region_code to low/med/high risk) <br>- customer_segment = based on age, job type, and residence stability</li></ol><p>Each of the above features may look simple but building them involves a lot</p><ul><li>Understanding raw source data formats</li><li>Collaborating with risk teams and data analysts</li><li>Writing repeatable transformation logic</li><li>Testing on historical data slices</li><li>and most importantly validating “does this make sense for a lender?”</li></ul><p><strong>Hands-On Feature Engineering on Public Credit Data</strong></p><p>To connect theory with real-world application, I’ve created two practical tutorials using publicly available credit datasets. These examples show how raw data is converted into useful, model-ready features through organized engineering processes.</p><p>The first tutorial is a brief guide, which takes you through practical feature creation using Python and pandas. It features examples such as calculating debt-to-income ratios, identifying delinquencies, binning continuous variables, and encoding categorical data — all within the framework of credit risk modeling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b55eac1541772df0e4b00ba8d5b912f8/href">https://medium.com/media/b55eac1541772df0e4b00ba8d5b912f8/href</a></iframe><p>The second tutorial is a more complex production-style feature engineering pipeline. This project mimics a real-world situation where data is collected from APIs, transformed with dbt, and made ready for offline training and online inference using Feast — a contemporary feature store. The repository is thoroughly documented and highlights modular, reproducible feature workflows designed for scalability and teamwork.</p><p><a href="https://github.com/venkateshtantravahi/credit-risk-feature-store-tutorial.git">GitHub - venkateshtantravahi/credit-risk-feature-store-tutorial: A Tutorial on credit risk feature store building</a></p><p>Together, these tutorials aim to illustrate how feature engineering is crucial in both prototyping and production. You are welcome to explore, run them locally, and modify the workflows to fit your own needs.</p><h4>Let’s Wrap UP</h4><p>In this article, we’ve explored how feature engineering bridges the gap between raw data and meaningful model inputs. From understanding what makes a good feature in credit risk, to walking through real-world transformations and production-ready pipelines, the goal was to show both the thinking and the doing. Whether you’re building your first scorecard or scaling a risk system, strong features are the foundation of trustworthy models.</p><p>Thanks for following along and if you found this helpful or think something could be improved, feel free to share your feedback. In the next part of this series, we’ll look at how feature choices impact model behavior, and how we evaluate fairness, explainability, and stability before a model goes live.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed0dc378fe96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Makes a Feature “Useful”? Understanding IV, WOE and the art of feature value in Credit Risk]]></title>
            <link>https://vtantravahi.medium.com/what-makes-a-feature-useful-understanding-iv-woe-and-the-art-of-feature-value-in-credit-risk-e769385f5df0?source=rss-309ac2129d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/e769385f5df0</guid>
            <category><![CDATA[information-value]]></category>
            <category><![CDATA[weight-of-evidence]]></category>
            <category><![CDATA[credit-risk-modelling]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[venkateshtantravahi]]></dc:creator>
            <pubDate>Thu, 07 Aug 2025 15:43:34 GMT</pubDate>
            <atom:updated>2025-08-07T15:43:34.881Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last few parts of this series, we explored the foundations of credit risk modeling such as what credit risk actually is, where the data comes from and how we define outcomes like delinquency or default. If you missed them, you can find all earlier parts on my <a href="https://vtantravahi.medium.com/">medium profile</a> each one is build to be standalone, but together they tell the full story of modern credit risk modeling.</p><p>When I first started exploring real world or may be the near one from public available credit data, I was both excited and overwhelmed. There were dozens of features such as income, age, job type, balance history, account status, and more. And like many others, I asked myself</p><blockquote>Should I just use all the available features?<br>Do I need to create new ones from existing columns?<br>Should I rely on correlation matrices like we often do in traditional ML workflows?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0zIK3Op5l8dm6ttKUdYilA.png" /><figcaption>Feature Selection ( Image Credits: Author through Canva)</figcaption></figure><p>I even tried few things selected top variables using correlation, did some trial and error runs, even dropped a few features randomly to see if it affected accuracy. It worked sometimes but didn’t feel systematic or explainable, especially in a domain where transparency matters. That’s when I came across two robust tools that the credit risk modeling has relied on for years. which are</p><ul><li>Information Value (IV) and</li><li>Weight of Evidence (WoE)</li></ul><p>At first, they seemed like “legacy concepts”. But the more I explored, the more I realized they were exactly what I needed</p><ul><li>A way to measure how predictive a feature actually is</li><li>A method to make categorical variables model-friendly</li><li>and most importantly, a way to build trust with risk teams and regulators.</li></ul><p>This part of series is about unpacking these tools not just what they are, but why they matter and how you can use them in your own credit risk pipelines, whether you’re building scorecards or modern ML models.</p><h4>What is Information Value (IV)?</h4><p>When credit risk modeling was just beginning to take shape long before tree based algorithms or automated ML platforms risk analysts and statisticians needed a reliable way to evaluate which variables actually helped predict customer behavior. One of the techniques that emerged from this need was Information Value or IV.</p><p>It’s a measure of how well a feature helps separate two groups typically “goods” (e.g., customers who repay) and “bads” (e.g., customers who defaults). It doesn’t rely on accuracy, AUC or model coefficients but it simply asks</p><blockquote><em>Does this variable help me tell the difference between a good and a bad customer?</em></blockquote><p>If the answer is yes, IV gives you a numeric score that reflects just how strong that separation is. It became widely used in credit scorecard development, especially alongside logistic regression a model type that depends heavily on clean, monotonic, well behaved variables. IV helps identify which features to keep, which to drop and which may look predictive but are actually misleading.</p><p>The origin of IV is from <a href="https://en.wikipedia.org/wiki/Information_theory">information theory</a> specifically in measuring how much “information” a variable gives us about an outcome. Let’s think of in a simpler way for suppose</p><ul><li>If a variable looks the same for both good and bad customers, it’s not helpful.</li><li>but if the same variable shows some distribution difference then it caries some information differentiating customers.</li></ul><p>The more different the distributions, the more confident we can be that this variable is “worth carrying some information”. Moreover, it’s not theoretical way of proving but statistical.Let’s imagine we are having some dataset pulled from a source system and we’re looking at a variable like “Age”</p><ul><li>would you expect younger borrowers to default more often than older ones?</li><li>If yes, can we capture that difference in a measurable way?</li></ul><p>That’s what IV gives to test and quantify that intuition. A few points to keep in mind while working with IV are</p><ul><li>It’s model independent means all you need is data and features.</li><li>It works best on categorical or binned numerical variables.</li><li>It tells you how well a variable helps separate classes but not whether it’s casual or biased.</li><li>Also sometimes leakage happens choosing high IV variables.</li></ul><h4>What is Weight of Evidence (WOE)?</h4><p>We have already seen that <strong>Information Value</strong> tells us <strong>how useful</strong> a feature is, then <strong>weight of evidence (woe)</strong> tells us <strong>why it’s useful </strong>and gives us the path to quantify that usefulness. WOE is a concept rooted from <a href="https://en.wikipedia.org/wiki/Logistic_regression">logistic regression</a> and information theory where analysts needed a way to</p><ul><li>Convert categorical values into numbers</li><li>Preserve <a href="https://www.discoverphds.com/blog/monotonic-relationship">monotonic relationships</a> with the outcome</li><li>Avoid treating raw numeric values as-is (which may not behave well)</li></ul><p>i.e., Rather than using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html">one-hot encoding</a> or <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html">label encoding</a> which often fail in credit risk tasks WoE transforms a variable based on how much “evidence” it provides in <strong>favor of being a good or bad customer</strong>.</p><p>So, the weight of evidence for a given category or bin is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U8KE1OqwaHzOUOtv.png" /><figcaption>WoE Calculation (Image Credits: <a href="https://latex2png.com/">LatextoPNG</a>)</figcaption></figure><p>It measures the strength of association between that group and the outcome and answers the question “Does this group lean more towards ‘good’ or towards ‘bad’?”. A +ve WoE suggests bin leans towards good customers and vice versa. For example, we have binned “Age” variable from a dataset and calculated WoE that looks like below:</p><pre>| Age Group | % of Goods | % of Bads | WoE   |<br>| --------- | ---------- | --------- | ----- |<br>| 18–25     | 5%         | 15%       | -1.10 |<br>| 26–35     | 25%        | 35%       | -0.34 |<br>| 36–50     | 45%        | 35%       | +0.25 |<br>| 51+       | 25%        | 15%       | +0.51 |</pre><p>You can see how WoE shows the direction and strength of evidence</p><ul><li>Younger age → negative WoE ( which means riskier group)</li><li>Older age → positive WoE (less riskier group)</li></ul><p><strong>Why use WoE?</strong></p><ul><li>Helps with variable transformation for logistic regression.</li><li>Ensures monotonicity (helps model avoid weird jumps while learning).</li><li>Makes categorical variables model-ready</li><li>Makes feature behavior more interpretable and explainable.</li></ul><p>Some things to remember while working with WoE are it only works well when there’s enough data in each bin, and sensitive to data leakage and you need to pre-bin continuous variables.</p><h4>How are WoE and IV Calculated?</h4><p>By now, we know the “what” and “why” behind the WoE and IV. So now let’s focus on how and look at using python code. Here we’ll work with a simple AGE_GROUP feature that’s been binned into categories, and a binary TARGET variable indicating whether the customer defaulted 1 or not 0 .</p><pre>import pandas as pd<br>import numpy as np<br>import pandas.api.types as ptypes<br>from typing import Tuple<br><br>#a dummy dataset<br>dataset = pd.DataFrame({<br>        &#39;AGE_GROUP&#39;: [&#39;18-25&#39;] * 200 + [&#39;26-35&#39;] * 700 + [&#39;36–50&#39;] * 1000 + [&#39;51+&#39;] * 400,<br>        &#39;TARGET&#39;: [1] * 150 + [0] * 50 + #18-25: 150 bad, 50 good<br>                  [1] * 400 + [0] * 300 + # 26–35: 400 bad, 300 good<br>                  [1] * 400 + [0] * 600 + # 36–50: 400 bad, 600 good<br>                  [1] * 100 + [0] * 300   # 51+:   100 bad, 300 good<br>})<br><br><br>def calculate_woe_iv(df: pd.DataFrame, feature: str, target: str) -&gt; Tuple[pd.DataFrame, float]:<br>&quot;&quot;&quot;<br>Calculate weight of Evidance (WoE) and Information Value(IV) for a single feature.<br><br>WoE measures the strength of a relationship between a categorical independent variable<br>(or binned numerical variable) and a binary dependent variable. It is calculated as:<br>WoE = ln((% of goods in bin) / (% of bads in bin)).<br>A positive WoE indicates that the bin has a higher proportion of goods, while a <br>negative WoE suggests a higher proportion of bads.<br><br>Information Value (IV) is a measure of the predictive power of a feature. It is <br>calculated as the sum of ( (% of goods in bin) - (% of bads in bin) ) * WoE for<br>each bin. IV values are typically interpreted as follows:<br>- Less than 0.02: Useless for prediction<br>- 0.02 to 0.1: Weak predictor<br>- 0.1 to 0.3: Medium predictor<br>- 0.3 to 0.5: strong predictor<br>- Greater than 0.5: Suspiciously strong (might be a data leakage or overfitting)<br><br>Parameters:<br>- df: The input DataFrame containing the feature and target columns.<br>- feature: The name of the feature column (categorical or pre-binned numerical)<br>           for which WoE and IV are to be calculated.<br>- target: The name of the binary target column (0 for &#39;good&#39; / non-event,<br>          1 for &#39;bad&#39; / event).<br><br>Returns:<br>- woe_df: A pandas DataFrame containing the following columns for each bin of the feature:<br>          - &#39;feature_bin&#39;: The unique values or bins of the feature.<br>          - &#39;total&#39;: Total count of observations in the bin.<br>          - &#39;bads&#39;: Count of &#39;bad&#39; observations (target=1) in the bin.<br>          - &#39;goods&#39;: Count of &#39;good&#39; observations (target=0) in the bin.<br>          - &#39;bad_pct&#39;: Percentage of total &#39;bad&#39; observations in the bin.<br>          - &#39;good_pct&#39;: Percentage of total &#39;good&#39; observations in the bin.<br>          - &#39;woe&#39;: Weight of Evidence for the bin.<br>          - &#39;iv&#39;: Information Value contributed by the bin.<br>- total_iv: A float representing the sum of IV across all bins, indicating the<br>            overall predictive power of the feature.<br><br>Raises:<br>- TypeError: If &#39;df&#39; is not a pandas DataFrame.<br>- ValueError: If &#39;feature&#39; or &#39;target&#39; columns do no exist in the DataFrame,<br>              if the &#39;target&#39; column is not binary (0 and 1), or if there are<br>              no &#39;good&#39; or &#39;bad&#39; observations in the target column.<br>&quot;&quot;&quot;<br>#Input validation<br>if not isinstance(df, pd.DataFrame):<br>  raise TypeError(&quot;Input &#39;df&#39; must be a pandas DataFrame.&quot;)<br>if feature not in df.columns:<br>  raise ValueError(f&quot;Feature column &#39;{feature}&#39; not found in a DataFrame.&quot;)<br>if target not in df.columns:<br>  raise ValueError(f&quot;Target column &#39;{target}&#39; not found in thr DataFrame.&quot;)<br><br><br>#Validate target column values<br>unique_target_values = df[target].unique()<br>if not (np.array_equal(np.sort(unique_target_values), np.array([0, 1])) or <br>        np.array_equal(np.sort(unique_target_values), np.array([1, 0])))<br>  raise ValueError(f&quot;Target Column &#39;{target}&#39; must be binary containing only 0&#39;s and 1&#39;s.&quot;)<br><br>#Calculate total counts of &#39;good&#39; and &#39;bad&#39; observations<br>total_goods: int = (df[target] == 0).sum()<br>total_bads: int = (df[target] == 1).sum()<br><br>#check for zero totals to prevent division by zero errors later<br>if total_goods == 0:<br>  raise ValueError(&quot;No &#39;good&#39; observations (target = 0) found in the DataFrame. Cannot calculate WoE/IV.&quot;)<br>if total_bads == 0:<br>  raise ValueError(&quot;No &#39;bad&#39; observations (target = 1) found in the DataFrame.Cannot calculate WoE/IV.&quot;)<br><br>#Group by feature and calculate counts for &#39;total&#39; and &#39;bads&#39;<br>grouped = df.groupby(feature)[target].agg(<br>            total = (&#39;count&#39;),<br>            bads = (&#39;sum&#39;)<br>).reset_index() # reset_index() to make the feature column accessible<br><br># Rename the feature column for clarity in the output<br>grouped = grouped.rename(columns={feature: &#39;feature_bin&#39;})<br><br>#Calculate &#39;goods&#39; count<br>grouped[&#39;goods&#39;] = grouped[&#39;total&#39;] - grouped[&#39;bads&#39;]<br><br># Add a small epsilon to avoid division by zero or log(0) issues, especially<br># for bins where either good_pct or bad_pct might be zero.<br>epsilon = 1e-6<br><br># Calculate percentage of total &#39;bads&#39; and &#39;goods&#39; with each bin<br>grouped[&#39;bad_pct&#39;] = (grouped[&#39;bads&#39;] + epsilon) / (total_bads + epsilon * grouped.shape[0])<br>grouped[&#39;good_pct&#39;] = (grouped[&#39;goods&#39;] + epsilon) / (total_goods + epsilon * grouped.shape[0])<br><br>#Calculate WoE<br>grouped[&#39;WoE&#39;] = np.log(grouped[&#39;good_pct&#39;] / grouped[&#39;bad_pct&#39;])<br><br>#IV for each bin <br>grouped[&#39;IV&#39;] = (grouped[&#39;good_pct&#39;] - grouped[&#39;bad_pct&#39;]) * grouped[&#39;WoE&#39;]<br><br>total_iv: float = grouped[&#39;IV&#39;].sum()<br><br>return grouped, total_iv<br><br><br>if __name__ == &quot;__main__&quot;:<br>woe_df, iv = calculate_woe_iv(data, &#39;AGE_GROUP&#39;, &#39;TARGET&#39;)<br>print(woe_df)<br>print(f&quot;\nTotal IV for AGE_GROUP: {iv:.3f}&quot;)<br></pre><p><strong>Output from the above code:</strong></p><pre>| AGE_GROUP  | total | bads | goods | bad_pct  | good_pct  | woe   | iv    |<br>| ---------- | ----- | ---- | ----- | -------- | --------- | ----- | ----- |<br>| 18–25      | 200   | 150  | 50    | 0.14     | 0.04      | -1.25 | 0.125 |<br>| 26–35      | 700   | 400  | 300   | 0.38     | 0.24      | -0.47 | 0.066 |<br>| 36–50      | 1000  | 400  | 600   | 0.38     | 0.48      | +0.23 | 0.023 |<br>| 51+        | 400   | 100  | 300   | 0.10     | 0.24      | +0.88 | 0.123 |<br><br>Total IV for AGE_GROUP: 0.337</pre><p>From the above results we can say that this feature is one of the strong predictors.</p><h4>Putting IV and WoE into Practice</h4><p>So from the above code you might have picked up calculating the feature IV and WoE values where the data is completely dummy small and just for the experimentation and setting you up to the stage but in real world or at least in near real world it can be a complete different situation so I have created a well documented <a href="https://gist.github.com/venkateshtantravahi/c91c15553c7fa6341600187acdd22ce1">github gist</a> attaching below where you can see and observe how to do things.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39e28b374f03d13f33d9301285071831/href">https://medium.com/media/39e28b374f03d13f33d9301285071831/href</a></iframe><h4>Why Risk Teams Still Use IV and WoE (Even Today)?</h4><p>By now, you might be wondering if modern models like LightBGM, logistic regression or neural networks exists, why do risk teams still care so much about WoE and IV?</p><p>To answer this question it’s all about interpretability and accountability in credit risk. When you’re building models in the credit risk space, it’s not just about accuracy.It’s about justifying decision that directly impact people’s lives whether they get approved for a loan, how much interest they pay or whether they’re denied altogether. These decisions can’t be made in a black box models or deep neural networks.</p><p>These techniques give a clear, numeric view of which variables are strong predictors, and how those variables influence risk. For example, you can point to a certain age group, or a credit history category, and explain how it affects the likelihood of default This is critical not just for internal clarity but for regulators, auditors and adverse action notices (the “why you were denied credit” messages sent to customers).</p><p>Even in pipelines where machine learning plays a key role, WoE and IV still play a role. These are often used before modelling as a filter to eliminate noisy or weak features or in scorecards where every input must be fully transparent.</p><h4>Common Mistakes to be taken care of</h4><p>Just like any other techniques IV and WoE can be misused if you are not careful enough observing few patterns such as</p><ol><li><strong>Overbinning: </strong>Sometimes we may think of creating many tiny bins to capture every small details of the distribution but doing this often leads to noisy or unstable estimates especially if there are small size samples per bin.</li><li><strong>Target Leakage: </strong>Sometimes a feature will look incredibly predictive (too good to be true). That’s a red flag which might leaking information (like a status flag updated after the loan was given). These features inflate IV but are not useful in production pipeline causing model deviations.</li><li><strong>Tiny Sample Sizes: </strong>For suppose you binned data and has only 2 or 3 observations per bin, the WoE value can swing dramatically with just a minor label change. So should always check for minimum bin size before trusting the numbers.</li><li><strong>Blind Application: </strong>Just because a feature has a good IV score doesn’t mean it’s appropriate. Always try to ask yourself “does this make any business sense?” will this be stable over time? always try combining the statistical evaluations with business understanding.</li></ol><h4>Let’s Wrap UP</h4><p>Understanding which feature carry meaningful information and being able to explain why is a critical part of building responsible credit risk models. WoE and IV offer a structured way to evaluate how each variable contribute to distinguishing between good and bad outcomes. More importantly, they help align data science efforts with the expectations of regulators, business stakeholders, and real-world decision making.</p><p>In the next part of series, we’ll explore the practical side of feature engineering and how a new variables are created from existing ones, what patterns we look for and how these decisions affect model performance. We’ll also walk through examples on credit data to see how well designed features can add depth and clarity to predictive models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e769385f5df0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Data Before You Even Think About Modeling]]></title>
            <link>https://vtantravahi.medium.com/understanding-the-data-before-you-even-think-about-modeling-99a4c59c9dcc?source=rss-309ac2129d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/99a4c59c9dcc</guid>
            <category><![CDATA[credit-risk]]></category>
            <category><![CDATA[risk-modeling]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[venkateshtantravahi]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 23:16:14 GMT</pubDate>
            <atom:updated>2025-08-01T23:16:14.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*XXwi_UmVc5pdM8U6_yaXUA.gif" /><figcaption>Data Sources ( Image Credit: Author Edit)</figcaption></figure><p>We’ve talked about what credit risk means in <a href="https://vtantravahi.medium.com/how-a-fintech-app-got-me-hooked-on-credit-risk-modeling-fffb67109310">part-1</a> then we’ve looked at the language used to describe outcomes and decisions in <a href="https://vtantravahi.medium.com/the-language-of-lending-you-need-to-understand-before-modeling-anything-57c234f708e5">part-2</a>, but now comes the real challenge the data itself. Because in the real world, you don’t start with a clean dataset that says “default == yes” and “customer risk == high”. Instead you usually start with messy, disconnected data from various sources such as</p><ul><li>Credit bureau reports.</li><li>Internal banking systems.</li><li>Application forms.</li><li>Loan servicing platforms.</li><li>Transaction-Level behavior.</li><li>Even external APIs.</li></ul><p>and one of the things you should know is that there is no “default” column either any label that says this data belongs to a bad customer. That’s why it’s important to answer few things before even we start</p><ul><li>What should we be predicting?</li><li>How do we define default from the data?</li><li>What time period are we looking at?</li><li>How do we label outcomes when outcomes when the data doesn’t tell us?</li></ul><p>This part of the series is about the work you need to do before you build any machine learning model. It’s about understanding the data, where it comes from, and how to prepare it for modeling. This includes making sense of missing or unclear information, defining what counts as default and making sure the model is answering the right business question. But for now let’s pause for this simple question.</p><blockquote>Where does credit risk data usually come from?</blockquote><h4>Where Credit Risk Data Comes From</h4><p>Before building any credit risk model, the first step is knowing what kind of data you’re working with and where it comes from. In real-world lending, data is not stored in one place Instead, it’s spread across different source systems, each holding a piece of the puzzle. Lenders bring all this data together to train models that predict risk like whether someone will repay a loan or not. Some of the main sources of data include:</p><ol><li><strong>Application Data: </strong>This is the information a person provides when they apply for a loan or credit card. Which typically include Age, Job Title or Employer, Declared Income, Loan amount requested, Purpose of loan (e.g., education, home, car etc.), Address, marital status, and ID details and others. This is the primary information available before the loan is given. Helps understand the behavior of various customers at point of application.</li><li><strong>Credit Bureau Data: </strong>It’s an agency that gathers information about a person’s credit history and provide it to lenders when requested. Some well known include <strong>Experian, Equifax, TransUnion, CIBIL, CRIF</strong>. These usually include many user’s level data like credit scores, active and closed accounts (also called tradelines), credit card balances and limits, loan repayment history, missed and late payments ( delinquencies), Inquiries ( who checked your credit and when).</li><li><strong>Banking or Transaction Data (Open Banking/ Banking APIs): </strong>Some lenders use bank statements data or connect directly to bank accounts via APIs ( like <a href="https://plaid.com/products/transactions/">Plaid</a> or <a href="https://www.yodlee.com/data-enrichment/transaction-data-enrichment">Yodlee</a>). Using these api’s they can get information like Salary credits, spending patterns, utility bill payments, loan emi’s and rent transfers, atm withdrawl’s or cash behavior.</li><li><strong>Loan Servicing Data: </strong>Once a loan is approved and given to the customer, servicing data tracks what happens after that money is disbursed. It includes information such as repayment dates, missed or partial payments, outstanding balance, days past due(DPD), whether the loan was closed, refinanced or charged off.</li><li><strong>Collection &amp; Recovery Data: </strong>If a customer fails to repay and the loan is charged off, the lender tries to recover some of the money. This data includes whether the loan was sent to collections, how much was recovered, and how long recovery took. This helps with modeling l<strong>oss given default (LGD)</strong> and measuring financial outcomes beyond just “Yes” or “No” default.</li><li><strong>Internal Decision Data: </strong>Many lenders also keep track of who was approved or rejected, what rules were applied (e.g., score cut-off), manual override decisions by underwriters. This later helps with auditing, explainability and analyzing model fairness. It also helps with <strong>Reject Inference</strong> trying to understand what would’ve happened if a rejected applicant was approved.</li></ol><p>Each of these data sources plays a different role. Some tell you what the borrower looked like before the loan while others tell you what happened after. You always need both to build a complete model. For example,</p><blockquote>Application + Bureau Data = Prediction Inputs<br>Repayment + Recovery Data = Prediction Outcome</blockquote><h4>Two Perspectives of Data — Training vs Real-Time Predictions</h4><ol><li><strong>Perspective while training the model: </strong>When training the model, we work with historical data from people who applied for credit in the past. Where we already know what has happened like did they repay?, did they default?, did they pay late or not at all?, how much was recovered? and this data also includes other information from applications, bureau data and after the approval stage about repayments, delinquencies, charge-offs and recoveries.</li><li><strong>Using the model in production: </strong>Now image when someone applied for a loan today say through mobile app or website. At this point, they haven’t made any payments yet. In fact, the lender doesn’t know anything about what they’ll do in the future. But the model still has to make a quick decision may be in just few seconds. So, what does the model use to make that decisions? ever thought off, only the information available right now, at the time of application? Usually there is a data pipeline designed to pull required data and do the heavy lifting of transformation before giving the model data for predictions in required format which usually includes basic application info ( such as income, job type, age, household members, etc.), Their credit report ( extracted from bureau’s API) and sometimes their recent bank account activity upto few months (via API’s like Plaid or Open Banking). Don’t worry much about this right now we will see about this in future parts of this series for now this to give you some curious clarity on a perspective that I got when I was doing some research.</li></ol><p><strong>Do you think learning this perspective really help us?</strong></p><p>Many models fail in production because they were trained with information that won’t be available at the <strong>time of prediction. </strong>For Example,</p><ul><li>Including repayment behavior from 3months after approval in your training data.</li><li>Using post-approval flags to engineer features.</li></ul><p>These are called <strong>data leaks </strong>and they make your model look great in training predictions, but useless in real time. To avoid these while building a credit risk model, we should try to</p><ul><li>Train it using only the data that would have been available at the time the loan was approved.</li><li>Then label that data using what happened after approval (e.g., defaulted with in 12 months)</li></ul><p>This helps the model to learn the current perspectives as well as identify the potential risks about how these patterns learned making in the future if it was approved.</p><h4>Defining “Default” When There’s no such column</h4><p>This is one of the most common and misunderstood step in credit risk modeling. Real world data often doesn’t come with a clear yes/no label and even when it does, it may not be suitable for modeling until it’s properly defined according to your stakeholders needs.</p><p>When working on a credit risk data, a lot of people expect the dataset to include a well defined column looking like default = 0 or default = 1 . But in reality all you could see is repayment records, late payments, balances, statuses like charged off or closed but no single column that says this person defaulted. So how do we train a model to predict default if we don’t know who defaulted? Let’s breakdown the reasons behind this</p><ol><li><strong>“Default” means different things to different lenders </strong>means every lender has their own way of defining this some call borrowers “defaulted” after 60 days of missed payments while others wait until 90 to 120 days. While some only mark it as default after legal actions or charge-off.</li><li><strong>Repayment behavior is spread over time </strong>means the dataset you might been working with have monthly snapshots one row per customer per month and default outcome isn’t stored as a single flag instead is been decided from the payment patterns.</li></ol><p>So, to train a model, you need to create a label a column that says whether each past borrower defaulted (1) or not (0). This means as a data scientist it’s important to gather some information from stakeholders and have to define it by yourself based on business needs. Some most common ways include:</p><ol><li><strong>DPD Based: </strong>Mark a borrower as defaulted if they ever go 90+ days past due during a defined period(e.g., within 12 months of loan approval).</li><li><strong>Charge — off Flag:</strong> Use a status code or flag in the system that shows the loan was written off as uncollectible.</li><li><strong>No Payments for X months:</strong> Define default as having no repayments for 4 or more months in a row.</li><li><strong>Business defined rules: </strong>Sometimes risk or finance teams provide a custom list of default conditions based on regulatory or internal policies.</li></ol><p>So does defining this really solve our problem of prediction? like just saying “defaulted or not” isn’t always enough, but also when it happened matters. For example..</p><ul><li>Did the customer default within 6 months of approval?</li><li>Did they go 90+ DPD anytime in the first 12 months?</li><li>Did they miss 3 payments in a row in their first year?</li></ul><p>You have to choose a consistent window so that every record has a fair chance to be labeled called <strong>Prediction Window</strong>. One thing to remember always while doing ML modeling is that there’s no one-size that fits all definitions of default. It always depends on how we define it based on business goals, product types, regulatory guidelines, or the data we are dealing with at that moment.</p><blockquote>No matter what defining it clearly and consistently is what your model understands and predicts from.</blockquote><h4>When and What are we actually predicting?</h4><p>For suppose you have defined what a “default” means according to your use cases and stakeholders needs, then the next big question is</p><blockquote>When do we expect it to happen?</blockquote><p>In modeling you’re almost never predicting if someone will default someday. You’re predicting whether they will default with in a specific time frame. That time frame is called the <strong>prediction window</strong> mentioned above and it’s one of the most important parts of designing your model.</p><p><strong>What is actually a prediction window? </strong>consider this as the time period you care about for observing whether a customer defaults or not. For example,</p><ul><li>Will the borrower default within 6 months of getting the loan?</li><li>Will they go 90+ days due in their first 12 months?</li><li>Will they stay current for the first 3 months?</li></ul><p>You chose this window based on the business goals and products. For example, you are working with a lender and they are giving a short-term personal loans with 12 month repayment plans and asked you</p><blockquote>“Can we predict if someone will default within first 3 months?”</blockquote><p>Because according to this lender if someone goes bad early then it might be a sign of risk for going bad later. Here based on problem you may need to design your dataset in a way that you include only borrowers who took loan at atleast 3 months ago then label them based on defaulted behavior.</p><p>This windowing timing affects how you label the data, what data you can use as input features, or how you interpret model performance. If you don’t set a clear definition of this window your model learns patterns from outside the window which creates leakage and gives misleading results.</p><h4>Prediction Window Vs Observation Window</h4><ol><li><strong>Prediction Window: </strong>Basically how far ahead you are predicting (e.g., 12 month next).</li><li><strong>Observation Window: </strong>How much history you use as input to train model (e.g., last 3 months behavior )</li></ol><p>Most Credit risk models use observation window data to get trained and predict what happens in the next period. Somethings to consider when considering these time frames include:</p><ul><li>Shorter windows are useful for short-term lending or high-risk customers.</li><li>Longer windows are more relevant for credit cards, mortgages or term loans.</li><li>Your labelling logic should match the window exactly don’t mix different time ranges.</li><li>Make sure your input features only use data available before the prediction window starts.</li></ul><p>In Summary a good model should always answer a very specific question rather than set of questions like</p><blockquote>“Based on everything we know right now, what is the chance this customer will default in next 6 months?”</blockquote><p>This question should help you to define the outcome clearly, set the right prediction window, and ensure your data aligns with real-world decision making.</p><h4>Wrapping Up</h4><p>Before we dive into building any models, it’s important to slow down and understand what we’re actually working with the data, the definitions, and the timing. This part of the process may not look exciting, but it’s what sets up everything else to work well.</p><blockquote>If I had an hour to solve a problem, I’d spend 55 minutes thinking about the problem and 5 minutes thinking about solutions.<br>- Albert Einstein</blockquote><p>and that’s exactly what this stage of credit risk modeling is about thinking carefully before predicting. In the next part of this series, we will dive into what actually makes a feature useful from a dump of features extracted or build on top of the baseline. I really thank for reading this so far, if this helped clarify things, consider sharing it with someone else who’s trying to go beyond just running models and understand problem and encourage by following.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99a4c59c9dcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Language Of Lending You Need To Understand Before Modeling Anything]]></title>
            <link>https://vtantravahi.medium.com/the-language-of-lending-you-need-to-understand-before-modeling-anything-57c234f708e5?source=rss-309ac2129d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/57c234f708e5</guid>
            <category><![CDATA[credit-risk]]></category>
            <category><![CDATA[lending]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[credit-risk-modeling]]></category>
            <dc:creator><![CDATA[venkateshtantravahi]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 18:07:02 GMT</pubDate>
            <atom:updated>2025-07-31T18:07:02.829Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re reading this, welcome back to the second part of this series where we’re diving deep into how credit decisions are made using data. In Previous post of <a href="https://vtantravahi.medium.com/how-a-fintech-app-got-me-hooked-on-credit-risk-modeling-fffb67109310">part1</a>, we explored what credit risk really means and why it’s so central to fintech and lending. But before we jump into machine learning, scorecards, or feature engineering, there’s something even more important we need to talk about first:</p><p>The <strong>language of credit </strong>which is the real-world terms and definitions that shape how we label, train, and interpret any credit risk model. Because here’s the thing, you can’t model what you don’t understand. For example,</p><ul><li>What exactly does it mean when someone has “defaulted”?</li><li>Is “delinquent” the same thing as “high risk”?</li><li>How much is a lender really losing when someone doesn’t repay?</li></ul><p>These are not just financial jorgan’s but they are <strong>outcome definitions</strong>. There directly impact</p><ul><li>What your model tries to predict,</li><li>How you measure its performance,</li><li>And how you explain the results to business, compliance, or even regulators.</li></ul><p>So in this article, we’ll explore these model training mindset and look at the terminology that every <strong>credit risk practitioner, data scientist, and fintech builder should be comfortable with</strong>. Don’t worry if it sounds a little fancy or complex at first, we’ll go through everything with explanation&#39;s and practical context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6HJqUVAi7BFrI6l-__8KJw.png" /><figcaption>Credit Risk Terms ( Credits: Author Generated using code)</figcaption></figure><h4>Understanding Borrower Outcomes</h4><p>Getting a loan approved is just the beginning of the story. From the lender’s perspective, the real concern begins after the money is disbursed, when the borrower starts making (or missing ) payments. Every credit risk model eventually ties back to one key question.</p><blockquote>“Did the customer behave the way we expected after we gave them credit?”</blockquote><p>To answer that, we need to understand a few key terms that describe how borrowers perform over time especially when things don’t go as planned.</p><h4>1. Delinquency</h4><p>When you search google you might find many definitions as this might mean different in each situation but it is <strong>first sign of trouble</strong> to put simply. Means if the borrower missed a scheduled payment, lender often track this by how many <strong>days past due (DPD) </strong>the payment is. You’ll commonly hear phrases like</p><ul><li>“30 DPD” — Payment is 30 days late.</li><li>“60 DPD” — Payment is 60 days late.</li><li>“90+ DPD” — Payment is very seriously late.</li></ul><p>Not all delinquency is equally risky. Some borrowers forget a payment and catchup quickly ( this is called a cure, refer below). But some start sliding further and that’s where things can escalate.</p><h4><strong>2. Default</strong></h4><p>Default is what most credit models are designed to predict. It’s not just being late but for long enough that the lender consider the borrower unlikely to recover and there’s no one way of defining it because it can vary based on</p><ul><li>Internal Policy (for example if 90+ DPD)</li><li>Product type ( for example credit cards vs mortagage loans)</li><li>Regulatory Standards ( for example <a href="https://www.bis.org/bcbs/qis/qis3qa_f.htm">Basel</a> defines default based on certain triggers)</li></ul><p>In modeling, you often chose a specific point to label a borrower as “bad” and that label becomes your target variable when training credit risk models.</p><h4>3. Charge-off</h4><p>A charge-off is a final step, not for one who borrows but for the lender’s book. It means the lender no longer expects to collect the remaining loan amount and writes it of as a loss. But that doesn’t mean the borrower is of the books.</p><blockquote>The debt still exists but now it might be sent to collections, sold to a recovery agency or pursued through legal actions.</blockquote><p>Charge-off often happens after 120–180 days of non-payments, but again, timeline varies depending on organization policies.</p><h4>4. Cure</h4><p>Sometimes, a borrower who’s missed payment manages to catch up this is called cure. It’s a positive sign from lender’s perspective, it shows that the risk might’ve been temporary and may be caused by some cash flow issues, but not a long-term inability to pay. In modeling, some lenders track cure rates to understand how many deliquent accounts eventually become “current” again. This can influence both risk strategy and recovery efforts.</p><h4>5. Recovery</h4><p>If a loan has already defaulted or not payed or been charged off, the lender still tried to recover money through collections, settlements or legal means. The amount they get back is tracked as recovery.</p><blockquote>For example, if a $5000 loan is charged off and the lender recovers $2000 later that’s 40% recovery rate.</blockquote><p>In credit risk modeling especially in regulatory or economic models these recoveries feed into <a href="https://finmark.com/profit-loss-projection/"><strong>loss projection</strong></a>, helping estimate how bad a default truly is from a financial point of view.</p><h4>Does understanding these outcomes matter for technical modeling?</h4><p>Every term above relates directly into how risk is defined, modeled and managed.</p><ul><li>Your target variable ( what you’re predicting ) often comes from whether someone defaulted or not.</li><li>You might model the likelihood of delinquency at 30 or 60days to trigger early warnings.</li><li>Charge-offs and recoveries affect how losses are calculated.</li></ul><p>In short, every risk model is built on a definition of “what went wrong” and these terms are how we define it.</p><h4>The 3 Core Risk Metrics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/0*qhuGlh2q7VVfsnR5.png" /><figcaption>Risk Metrics (Image Source: <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.consortiasolutions.com%2Four-products-1%2F&amp;psig=AOvVaw02RDMgLrG8V172ypMmRf08&amp;ust=1753888122171000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBkQjhxqFwoTCPjItces4o4DFQAAAAAdAAAAABAE">IFRS9 Estimator</a> )</figcaption></figure><p>Once you understand what happens after credit is given from above section you might get a question</p><blockquote>Okay, but how do we actually measure and model the risk?</blockquote><p>That’s where these three terms form the backbone of most credit risk systems around the world, especially when it comes to regulatory frameworks like Basel and Internal Credit Strategy.</p><h4><strong>1. PD — Probability of Default</strong></h4><p>One of the most used metric which tells us whether a loan will be payed or not for a specific period of time depending on the product. For example,</p><blockquote>“What’s the chance that person will default in the next 12 months (or some other time frame)?”</blockquote><p>It’s a number between 0 and 1 or think of it as 0% to 100%</p><ul><li>A PD of 0.02 means a 2% chance that this person will default (not pay)</li><li>A PD of 0.35 means a 35% chance or riskier compared.</li></ul><p>This Probability is typically predicted using models like <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html">logistic regression</a> or <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html">gradient boosting</a> which are trained on historical data. We look at customers who defaulted Vs those who don’t and then use patterns in their data to predict future defaults.</p><h4>2. LGD — Loss Given Default</h4><p>So now, you know that there might be chances of defaulting the loan then we might also think of</p><blockquote>“How much of the loan are we actually going to lose?”</blockquote><p>That’s what LGD means, it’s the percentage of the outstanding amount that the lender expects to lose after trying to recover some of it. For example, if the loan was $10,000 and we recover around $2500 then we lose $7500 so LGD is 75%. This depends on multiple factors</p><ul><li>The type of loan (secured Vs unsecured)</li><li>Whether collateral ( like car or house) can be recovered</li><li>The efficiency of the collections process</li></ul><h4>3. EAD — Exposure at Default</h4><p>According to <a href="https://corporatefinanceinstitute.com/resources/commercial-lending/exposure-at-default-ead/">CFI</a> , Exposure at Default (EAD) is the predicted amount of loss a bank may face in the event of, and at the time of, the borrower’s default. To put this as a question..</p><blockquote>“How much money is on the line at the moment of default?”</blockquote><p>This can be very easy when you might first look at, but varies if</p><ul><li>it’s a fixed loan (eg., personal loan ), the exposure might be remaining principal + interest.</li><li>it’s a credit card or line of credit, it could include undrawn balances because customers tend to use up their limits before defaulting.</li></ul><p>So EAD is about predicting the total exposure you’ll be left with if the customer stops paying not just what they owe today.</p><p>Let’s just simply put everything together for better understanding:</p><pre><br>| Term |                What It Means                |       Real-World Examples       |<br>|------|---------------------------------------------|---------------------------------|<br>| PD   | What&#39;s the chance this person will default? | 10% chance of missing payments  |<br>| LGD  | If they default, how much will we lose?     | Likely to lose 70% of loan      |<br>| EAD  | How much money will be owed at that time?   | $8000 balance when default hits |</pre><p>These three metrics often work together to calculate Expected Loss (EL). Which helps lenders to plan for potential losses, set aside capital and make smarter lending decisions.</p><blockquote>EL = PD x LGD x EAD</blockquote><h4>Types of Credit Risk</h4><p>Up to this point, we’ve focused on the individual customers , like did they repay ? did they defualt? or what’s the loss? But credit risk isn’t only about one borrower at a time. Lenders manage thousands or sometimes even millions or customers across different products, industries, and regions. And when we zoom out, we start to see that risk exists at many different layers not just at the personal level. So here we’’ll explore different segments of those risks.</p><h4>1. Credit Risk ( Which we’ve been talking soo far)</h4><blockquote>“will this borrower repay their debt on time, or not?”</blockquote><p>It applies to personal loans, credit cards, mortgages, <a href="https://www.investopedia.com/buy-now-pay-later-5182291">BNPL</a> pretty much any situation where lender gives someone money with expectations to getting it back. This is the kind of risk most credit risk models are build to predict often by estimating the Probability of Default (PD).</p><h4>2. Counterparty Risk</h4><p>Think of this mostly at institutional level or B2B lending such as big financial contracts not as individual loans.</p><blockquote>It’s the risk that the other party in a financial transaction ( like a derivative or trade finance deal) doesn’t fulfill their obligation.</blockquote><p>For example, if a bank enters a contract with another firm to swap interest rates and that firm collapses the bank might lose a lot even if the original agreement had nothing to do with credit scores or consumer behavior. You may not hear often about this kind of modeling a lot but being aware of when you work with or build systems around it.</p><h4>3. Concentration Risk</h4><p>Even if every customer in your portfolio is “safe”, you can still be in trouble if they’re all to similar. It happens when a lender has too much exposure to a specific group like</p><ul><li>A single industry (e.g., 70% of loans are to construction firms)</li><li>A region (e.g., most customers are in one state or city)</li><li>A product type (e.g., too many small business loans)</li></ul><p>If something goes wrong in that group ( say a housing crash or local economic distress), then whole portfolio suffers. Risk teams often monitor for this and set limits to avoid putting all their capital in one group.</p><h4>4. Portfolio Risk</h4><p>It’s the total risk across the lender’s entire book of business across all products, customers and segments. It tells us about</p><ul><li>what is the total expected loss next quarter?</li><li>How much capital do we need to set aside to absorb potential losses?</li><li>which segments of our portfolio are getting riskier over time?</li></ul><p>Portfolio risk is often monitored using dashboards, reports, and portfolio-level-models and this is what you work with mostly if you are a credit risk managers or analysts.</p><h4>Financial Risk Metrics that actually matter</h4><p>If you are a data guy or tech guy who uses data to provide insights you might have probably heard about things like accuracy, precision/recall, auc/roc, or confusion matrix. For a while these have been very useful in credit risk too especially once a model is live and making decisions but does these make any sense to business stakeholders? Are these metrics might be able to answer</p><blockquote>“How is the portfolio performing over time?”<br>“Are customers behaving as expected?”<br>“Where is the risk building up and how fast?”</blockquote><p>That’s where the following metrics comes in to picture answering few things required for the stakeholders.</p><h4>1. Vintage Analysis</h4><p>It tracks how groups of loans (called “vintages”) perform over time. A vintage is typically defined by the month and quater the loans were originated. For example, Jan 2024 vintage = All loans issued in Jan 2024 , Lenders then track vintage ages for,</p><ul><li>what % of those loans went 30+ days past due by month 3?</li><li>How many charged off by month 6?</li><li>How fast are losses building up?</li></ul><p>these helps them to answer</p><ul><li>Are recent vintages performing worse than older ones?</li><li>Did a new policy or model rollout improve outcomes?</li><li>Is risk creeping into newer customer segments?</li></ul><p>So this analysis is essential for early warnings and trend detections that helps lenders to understand where going wrong.</p><h4>2. Bad Rate</h4><p>This is one of the most direct measure of portfolio’s health.</p><blockquote>Bad Rate = % of borrowers who default in a given <a href="https://www.scribbr.com/methodology/population-vs-sample/">population</a>.</blockquote><p>You can calculate bad rates by product , segment or time period. It’s a simple but powerful way to compare risk levels across different segments. If bad rates are high in one segment, then might have to check up the rules of approval.</p><h4>3. Roll Rate</h4><p>A roll rate tells you how likely a borrrower is to “roll forward” into a worse delinquency stage. For example, of all accounts that were 30 days past due last month, what % rolled in to 60+ DPD this month? This helps risk teams to detect early stage of stress, forecast potential defaults, and plan collection strategies. Roll rates are usually tracked monthly and often visualized in matrices showing transactions like</p><pre>Current -&gt; 30 DPD<br>30 DPD -&gt; 60 DPD <br>60 DPD -&gt; 90+ DPD</pre><h4>4. Recovery Rate</h4><p>Try to think of this situation where a loan is charged off, because lenders still need to recover money through various ways such as internal collections, external debt buyers or legal proceedings.</p><blockquote>Recovery rate = % of the charged-off amount that was eventually collected.</blockquote><p>For example, if a $10000 loan is charged-off and $2000 is later recovered, the recovery rate is 20%. It might also vary by loan type, geography, customer segment, and collections strategy. In secured loans (like mortgages or auto ), recovery can be higher because there’s a collateral involved.</p><p>While AUC and precision are great during model development, real-world credit risk work revolved around business risk metrics which might help your model with what actually matters in lending like <strong>money at risk, customer behavior over time and early warning signs</strong>.</p><h4>ScoreCard — The Backbone of traditional credit risk modeling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDr66IjV7oj2ngVo5JeqDg.png" /><figcaption>Score Card (Image Credit: Author Edit)</figcaption></figure><p>When most people think of credit scoring, they think of a number may be 650, 780 that determines whether you’ll get approved or rejected for a loan. Behind the numbers there is a concept called <strong>Credit ScoreCard</strong>. Despite all the automation that’s going with the hands of ML and AI, scorecards are one of the most trusted, widely used tools in credit risk industry especially in regulatory environments like banks, NBFCs and credit unions.</p><h4>SO what is Credit Scorecard?</h4><p>A scorecard is a statistical model usually based on logistic regression that assigns a score to a borrower based on certain characteristics that can include age, income, credit length history, number of missing payments, utilization rate etc., Each of these features are binned (grouped) and assigned a score contribution. The sum of these values become the final score card. Think of it’s like a reward system for example,</p><ul><li>More stable income → +20 points</li><li>High Utilization → -15 points</li><li>Long Credit history → +25 points</li></ul><p>These all added to getup your final score card value. Usually Higher Score → lower predicted risk → more likely to get approved for something.</p><p><strong>What are odds in credit scoring?</strong></p><p>Scorecards often work with odds rather than just raw probabilities. Let’s say a model predicts that a customer has 5% chance of default. That translates to odds of 19:1 meaning for every 19 “good” borrowers, there’s 1 who will default. The scorecard assigns scores that map to these odds using a score-to-odds mapping that looks something like</p><blockquote>Score = Offset + (Factor x log(odds))</blockquote><p>While this mapping things into math may sound somewhat difficult, it simplifies the whole purpose like</p><ul><li>Turning a model’s prediction into a risk score that’s easier to work with.</li><li>The Scores are easier to segment, interpret and use in business rules compared to other metrics (for e.g., approve all applicants above 650)</li></ul><h4>Does People who got rejected are really defaulters?</h4><p>Big question right..!, when you reject someone for a loan, you never find out if they would have defaulted because they never became a customer. This creates a problem when training models.</p><blockquote>How do you know the risk of applicants if you have no outcomes for them?</blockquote><p>This is where <strong>reject inference </strong>used. It’s a process of estimating what would have happened if those rejected applicants had been approved. For that there are different techniques used</p><ul><li>Reweighing accepted data to resemble the full population</li><li>Modeling the rejected population separately</li><li>Semi-supervised learning</li></ul><p>You might now think does doing this make the model perfect? Not at all but it’s often necessary to avoid biasing the model towards only the “safe” population you already approved.</p><h4>Does Scorecards still being used a lot with lot of improvements in modeling?</h4><p>Even with the rise of decision trees, neural networks, and complex ML platforms these scorecards remain dominant in many organizations and they hold some good reasons such as</p><ul><li>Interpretable → Easy to explain why someone got a particular score.</li><li>Auditable → Can be reviewed by compliance, regulators, and legal teams</li><li>Stable → Works well with tabular data and structured environments</li><li>Trusted → Accepted by credit bureaus, banks and regulators</li></ul><p>There are some countries where lenders are often required to explain why someone was rejected and using scorecards make it much easier compared to translating a complex ensemble models decision.</p><h4>Credit Report &amp; Bureau Terminology</h4><p>Behind every credit decision, there’s data. Not just what customer enters in application but a detailed history of how they’ve managed credit in the past. That history comes from organizations called credit bureaus. These agencies that collect and maintain about individuals borrowing behavior. In U.S, common bureaus include <a href="https://www.experian.com/">Experian</a>, <a href="https://www.equifax.com/">Equifax</a>, and <a href="https://www.transunion.com/">TransUnion</a>. In other countries you’ll see names likes CRIF&lt; CIBIL or CreditInfo. Understanding what’s inside a credit report is crucial for anyone building or working with credit risk models. Here are the terms you’ll most encounter.</p><h4>1. Inquiry</h4><p>Every time a lender checks your credit report or pull data from these agencies either to approve a new product or monitor an existing one it created a record called <strong>inquiry. </strong>There are two main types of these</p><ul><li><strong>Hard Inquiry: </strong>Happens when you apply for credit (affects your score).</li><li><strong>Soft Inquiry: </strong>Happens when you’re pre-qualified, or when you check your own score (doesn’t affect score)</li></ul><p>you might ask does this really help us modelling? Yes one feature you can add to modeling is too many inquiries in a short period can signal <strong>credit-seeking behavior</strong> which might indicate higher risk factor.</p><h4>2. Tradeline</h4><p>A tradeline is essentially an account on your credit report — like a credit card, personal loan or auto loan etc., Each of these lines includes</p><ul><li>Account type (credit card, mortgage, or etc.,)</li><li>Open date and status (active, closed, delinquent)</li><li>Credit limit or original loan amount</li><li>Balance and payment history (month-by-month)</li></ul><p>These features help capture a borrower’s credit history depth, payment consistency and current obligations.</p><h4>3. Utilization Rate</h4><p>This is one of the most widely used feature in credit scoring. utilization_rate = current_balance / credit_limit which tells us how much of your available credit you’re using. For example, $3000 balance on $10000 credit limit is 30% utilization rate. and this matters a lot because</p><ul><li>High utilization ( especially &gt; 50–70%) is often considered as red flag.</li><li>Lower utilization suggests more responsible credit usage.</li></ul><p>Lenders often have an eye on <strong>per-account </strong>and <strong>aggregate utilization.</strong></p><h4>4. Thin File Vs Thick File</h4><p>Imagine two people applied for a credit card.</p><ul><li>Person 1 has just moved to the U.S., has no credit card yet, no loans, and no credit history in the system .</li><li>Person 2 has had three credit cards for th epast 6 years, paid off a car loan and has a mortgage with regular payments.</li></ul><p>From a credit model’s perspective, person 2 has a thick file meaning there’s a lot of data to work with. However, person 1 has a thin file means very little information to base a decision on. Does this really matter to model for taking decisions or to deal with?</p><ul><li>Thin filers are harder to score confidently not because they’re necessarily risky, but because there isn’t enough data to tell.</li><li>This leads to greater uncertainty in model predictions.</li><li>Many lenders rely on alternative data (like bank statements, income flows, or behavioral patterns) to get more insights.</li></ul><p>These kind of segmentation really becomes helpful for us to evaluate the model performance across different user types, designing fair lending strategies, avoiding bias against people who are new to credit but otherwise responsible.</p><h4>Let’s Sum up What we have learned:</h4><p>Now that we’ve gone through the key terms used in credit risk, we now should have some clearer idea of how lending decisions are made and what kind of outcomes lenders really care about. We also looked at what it means when someone misses their payments, how lenders measure the risk of default, and how they use scores and reports to decide who gets approved.</p><p>In the upcoming part of this series, we ‘ll look at where all this data actually comes from and also talk about what happens when the data doesn’t clearly say who defaulted and how we arrive to those definitions by ourselves.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57c234f708e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How a Fintech App Got Me Hooked on Credit Risk Modeling]]></title>
            <link>https://vtantravahi.medium.com/how-a-fintech-app-got-me-hooked-on-credit-risk-modeling-fffb67109310?source=rss-309ac2129d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/fffb67109310</guid>
            <category><![CDATA[credit-risk]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[risk-modeling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[venkateshtantravahi]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 16:35:55 GMT</pubDate>
            <atom:updated>2025-07-30T16:35:55.059Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago, I opened a fintech app just to check my credit score. It looked clean, modern and showed my FICO or credit score right at the top, then gave me a few suggestions not only to improve my overall credit profile, but also listed out some personal loan offers that I had never applied for. No paperwork, no wait time? Just a tap away from thousands in instant credit. However, I didn’t took the loan but the moment stayed with me.</p><blockquote>How did this app know I was eligible?<br>What logic told it to trust me or anyone else in seconds?</blockquote><p>As someone with a technical background, those questions weren’t just curiosity. So I started reading and learning more about how lenders evaluate risk, how they use data to make real-time decisions, and what goes on behind the scenes before you ever see “<strong>Approved</strong>” or “<strong>Denied” </strong>message. That’s when I came across one of the most fascinating areas of applied data science I’ve explored to date: <strong>Credit Risk Modeling</strong>.</p><p>And no I don’t mean just picking up and running LightBGM or Logistic regression on public dataset. I’m talking about how real-world credit decisions are made where millions of dollars, consumer fairness, regulatory rules and explainability comes into picture. Where every prediction is more than just a number because it’s a decision that affects the real population. This series is my attempt to take you into that world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xPIlg8N7JnIhm9JGqvwpQ.png" /><figcaption>Credit Risk Banner (Credits: <a href="https://www.canva.com/design/DAGud_1mWhI/2IGuphmH8fG5wQG5Qw18eQ/edit?utm_content=DAGud_1mWhI&amp;utm_campaign=designshare&amp;utm_medium=link2&amp;utm_source=sharebutton">Author’s work</a> using canva)</figcaption></figure><h4>What is Credit Risk, Really?</h4><p>If you search “credit risk” on Google, you’ll probably end up something like this:</p><blockquote>“Credit Risk is the possibility of a loss resulting from a borrower’s failure to repay a loan or meet contractual obligations.”</blockquote><p>That’s technically correct and it’s the definition you’ll find in textbooks, regulatory documents and risk policies. But let’s break down a bit in a way we may feel easier to relate to.</p><p>For Example, Imagine you lend your friend $100, expecting them to pay you back in a month. Now ask yourself</p><ul><li>What’s the chance they forget?</li><li>what if they get into a tough situation and can’t pay you?</li><li>What if they just avoid paying altogether?</li></ul><p><strong><em>That uncertainty or the doubt in whether you’ll get your money back is what credit risk.</em></strong></p><p>And while that might feel small at personal level, zoom out to the world of cosumer lending, credit cards, mortgages, and business loans. That’s where we talk about millions and billions of dollars.</p><p><strong>You might feel why lenders obsess over it? </strong>Because lending is always a risk vs reward game.</p><ul><li>If a bank lends too cautiously, they might lose out potential customers and profits.</li><li>If they lend too freely, they take on too much risk and may end up huge losses.</li></ul><p>So the goal is always to find a balanced way to decide who’s likely to repay and who might not. And those decisions have to be fast, fair and accurate. That’s where <strong>Credit Risk Modeling</strong> steps in.</p><h4>Is Credit Risk a simple Yes/No🤨?</h4><p>What makes this topic so interesting is that it’s not just financial but also deeply statistical. Credit risk isn’t about <strong><em>what happened</em></strong>, it’s about <strong><em>what might also happen</em></strong>.</p><p>When a bank or fintech company gives you a loan or a credit card, they’re essentially betting on your future behavior and they use <strong>your</strong> <strong>data</strong> to make that bet. That’s where Machine learning modeling comes in:</p><ul><li>They look at your income, job, past payment behavior, account history, even spending patterns.</li></ul><blockquote>Then they use statistical or machine learning models to estimate “What’s the probability this person will not pay or default in the next 12 months?”</blockquote><p>One more thing to note that this problem is not a simple Yes/No decision but includes:</p><ul><li><strong>Probability of Default (PD): </strong>How likely is someone to miss payments?</li><li><strong>Loss Given Default (LGD):</strong> If they do default, how much money will be lost?</li><li><strong>Exposure at Default (EAD):</strong> How much money is at stake when they default?</li></ul><p>For now, don’t worry about advanced terms like “PD” or ‘EAD”. We’ll get into later as we explore more. Just remember, it’s all about <strong>predicting the chance of someone not paying back.</strong></p><h4>Why Credit Risk is at the heart of fintech?</h4><p>Let’s pause for a second and think about what most fintech products are really offering us? One thing they might have is great design, smooth onboarding or clever budgeting tools but at their core, many of them exist to help you <strong>borrow, spend, or pay money</strong> in a faster, more flexible way. Whether it’s</p><ul><li>A “Buy Now, Pay Later” button at checkout,</li><li>An instant loan offer after submitting few basic details, or</li><li>a credit card with personalized limit</li></ul><p>All of these are powered by one fundamental engine working in the background <strong>Credit Risk Modeling</strong>. Every time you apply for credit, there’s a system quietly evaluating your profile answering a very important question</p><blockquote>“If we lend to this person, are we likely to get our money back?”</blockquote><p>In the past, this decisions used to be made by people called loan officers who looked at paperwork, asked questions, and used experience ( or sometimes gut feeling) to decide. That worked when lending was small and slow. But in fintech, <strong>Scale and Speed</strong> change everything</p><ul><li>Decisions happen in seconds, not days.</li><li>You’re approving thousands (or millions) of users, not just a few.</li><li>The same system has to work for people from all kinds of backgrounds, incomes, and financial habits.</li></ul><p>There’s simply no way to make this work manually anymore due to increased demand in requests and need more fairly taken decisions, which is why automated <strong>credit risk models</strong> have become essential. These models dont just decide whether to approve someone or not. They do actually mean more such as</p><ul><li>How much credit someone gets</li><li>What interest rate they’re charged</li><li>Whether they need a co-signer</li><li>Even what type of loan product can be offered or suggested</li></ul><p>In other words your entire borrowing experience is shaped by these predictions and most people don’t even realize it’s happening. Credit Risk models have come a long way from human’s reviewing piles of files of historical records and papers to decide → rule based systems when computerising data → machine learning systems looking around patterns across thousands of variables which are trained on historical records. These models are constantly updated, tested and monitored because they directly affect people’s financial lives and even a small inproper decision can have big consequences.</p><h4>Wrapping Up</h4><p>That’s a lot to consume in one part. We talked about how a simple moment with fintech app made us understanding a much deeper system one that shapes who gets access to credit, how much and on what terms. We unpacked what credit risk really means, why it’s so important in the world of digital lending, and how it has evolved from manual decisions to data-driven systems that work at scale, and we did it without diving straight into technical jargons or models code because understanding <strong>why </strong>is as important as the <strong>how</strong>. This series is designed mostly for people with some knowledge around coding or data as we go further into series it will have code and data involved a lot as well as written as detailed as possible for non technical people to grasp concepts around it.</p><h4>What’s Coming Next?</h4><p>In Part2, we’ll focus on what really powers credit risk decisions which is the language of lending and risk. Like,</p><ul><li>What terms like default, delinquency, and charge-off actually mean ?</li><li>How lenders categorize customers as “good” or “bad” based on these outcomes?</li><li>The different types of Credit risks including PD, LGD and EAD.</li></ul><p>We’ll also explore about some key risk metrics used in credit world, like vintage analysis, bad rate, rollout rate and why these are very different from typical ML metrics like accuracy or R². This isn’t just terminology but the foundation that shapes how data is labeled, how features are engineered and how real-world decisions are made.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fffb67109310" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Mind Inside Your CPU]]></title>
            <link>https://vtantravahi.medium.com/the-mind-inside-your-cpu-1857cb8ee652?source=rss-309ac2129d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/1857cb8ee652</guid>
            <category><![CDATA[neurons]]></category>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[electronics]]></category>
            <dc:creator><![CDATA[venkateshtantravahi]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 13:56:43 GMT</pubDate>
            <atom:updated>2025-07-18T13:56:43.997Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered if your computer might be thinking quietly to itself, hidden away beneath its sleek casing? Each time you click a link, stream a movie, or crunch numbers on a spreadsheet, something fascinating happens deep inside your computer’s processor — something oddly familiar. But what if I told you that this intricate dance of electricity closely mirrors how your own brain works?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0O4X2GEgHavW757wA7owQ.png" /><figcaption>Transistors vs neurons(Source: AI Generted)</figcaption></figure><p>Consider this for a moment: billions of microscopic transistors inside your CPU communicate constantly, opening and closing tiny gates to manage floods of data, much like neurons fire signals across countless pathways inside your brain. But how exactly does a collection of lifeless silicon components manage to echo the dynamic, fluid processing of a living mind?</p><p>Are these tiny components truly analogous to neurons in our brains? How can something as simple as a transistor — a tiny electronic switch — produce complex computations that seem almost human-like in their logical elegance?</p><p>By the time you finish this article, you’ll uncover the surprising similarities between the logic gates nestled within your CPU and the neurons quietly firing inside your brain. Prepare yourself to see your computer — and perhaps even your own thinking — in a whole new way.</p><h3>Inside the CPU</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qAg6z3gBR1epbdZf.jpg" /><figcaption>CPU Microscopic View(Source: <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.djdlabs.com%2Fintel-486-under-the-microscope%2F&amp;psig=AOvVaw15kOFbn-1xji7jj-25LHvg&amp;ust=1748439545021000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBcQjhxqGAoTCPCdjp_jw40DFQAAAAAdAAAAABCgAQ">google</a>)</figcaption></figure><p>At the heart of every computer, smartphone, or tablet is a small yet incredibly powerful chip — the <strong>Central Processing Unit (CPU)</strong>. Think of the CPU as the brain of your device. It takes instructions from software (like your favorite apps) and translates them into actions, such as displaying images, calculating numbers, or playing music.</p><blockquote>But what’s actually happening inside this tiny chip?</blockquote><p>The CPU contains billions of tiny electronic switches called <strong>transistors</strong>. Imagine each transistor as a tiny gate: it can either let electricity pass through or block it, representing the binary states we call <strong>1s and 0s</strong>. By combining billions of these transistors into different patterns, your CPU can perform countless tasks.</p><p>These transistors group together to form simple logic devices known as <strong>logic gates</strong> — such as AND, OR, NAND, NOR, and XOR gates. Each type of gate has its own rule for processing inputs. For example, an <strong>AND</strong> gate might say, “I’ll let electricity through only if both inputs are active.” These simple rules, when combined on a massive scale, allow CPUs to execute complex instructions rapidly and accurately. This clever arrangement of transistors is what gives our devices the power to perform tasks almost instantaneously.</p><h3>Neurons and Synapses</h3><p>Inside your brain, billions of tiny cells called <strong>neurons</strong> constantly exchange messages. Think of each neuron as a tiny messenger — when it receives enough signals, it “fires,” passing its own signal along to neighboring neurons. These signals travel across tiny connections called <strong>synapses</strong>, creating complex networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3jvKcw6ep1_dKA_Y.jpg" /><figcaption>Neurons and Synapses (Source: <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.nature.com%2Farticles%2F515293a&amp;psig=AOvVaw3GF5syi7vzteFSKZfNr6ME&amp;ust=1748439873286000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBcQjhxqFwoTCODP-KLkw40DFQAAAAAdAAAAABAL">Getty Images</a>)</figcaption></figure><p>This network is how you think, learn, and feel emotions. When you learn something new, certain pathways become stronger, allowing messages to travel faster — this is how memories form. It’s remarkably similar to how digital devices use pathways to efficiently send signals through transistors, creating structured routes for data to flow.</p><blockquote>But how exactly does this biological process match what happens inside your CPU?</blockquote><p>At first glance, it might seem odd to compare a biological neuron to a transistor. But let’s look closer:</p><p>A neuron only fires when it gets enough stimulation — a specific threshold must be reached. Similarly, a logic gate inside your CPU produces output based on the input it receives. For example, an <strong>AND gate</strong> only “fires” when both inputs are on. A <strong>NAND gate</strong>, on the other hand, fires unless both inputs are on.</p><p>This simple comparison reveals something fascinating: just like your brain combines signals from neurons, your CPU combines signals from transistors. Both systems make decisions based on combinations of inputs, creating intricate networks that can perform surprisingly complex tasks.</p><p>In short, the logic of neurons and the logic of transistors are astonishingly alike, despite one being biological and the other electronic.</p><h3>Learning and Flexibility</h3><p>Though CPUs and brains share striking similarities, there’s one significant difference: flexibility.</p><p>Your brain is incredibly adaptable. Every experience can reshape neural pathways, strengthening connections to learn new skills or form new memories. This adaptability is known as <strong>plasticity</strong>.</p><p>Traditional CPUs, however, are fixed structures — built once, their circuits can’t easily change. But recent innovations are challenging this limitation. Devices called <strong>neuromorphic chips</strong> mimic the brain’s flexibility by adjusting their circuitry dynamically, enabling machines to “learn” from their experiences. Chips like Intel’s <strong>Loihi</strong> and IBM’s <strong>TrueNorth</strong> are leading examples, able to rewire their internal pathways similarly to how your brain adapts over time.</p><p>This exciting leap forward means CPUs might someday become as adaptive as our own brains — bringing machines a step closer to genuinely human-like thinking.</p><h3>Drawbacks of Mimicking Brains</h3><p>While the resemblance between CPUs and our brains is impressive, it’s important to acknowledge their differences too. Our brains effortlessly manage tasks like recognizing faces, understanding language nuances, and adapting instantly to new experiences — all using less power than a small light bulb.</p><p>In contrast, CPUs, despite their speed and accuracy, still struggle with tasks involving deep understanding, context, and adaptability. Current technology remains limited by fixed circuits, high energy consumption, and difficulty in replicating the brain’s immense complexity. There’s still a long way to go before machines can match our brain’s extraordinary efficiency and flexibility.</p><blockquote>So, what does the future hold? Will we ever see CPUs that can genuinely think like humans?</blockquote><p>Recent advancements suggest we might. Neuromorphic computing, AI breakthroughs, and quantum technology promise new horizons where machines adapt dynamically, learn continuously, and even approach genuine creativity and intuition. However, as we edge closer to this reality, we’ll also face ethical questions — like what it truly means for machines to “think” or even potentially feel.</p><p>The journey ahead is exciting, full of promise and complexity. We stand at the beginning of a new era, where the boundary between silicon chips and the human mind grows increasingly blurred.</p><h3>Let’s Wrap it up!!</h3><p>The next time your computer loads a webpage or streams your favorite show, remember: there’s a tiny universe within — a symphony of silicon neurons quietly mirroring the human brain. Perhaps, in our pursuit of technology, we’re really discovering ourselves. After all, the devices we build may just be subtle reflections of our own minds at work.</p><p>Thank you for taking the time to explore these insights with me. I hope you enjoyed this deep dive into the hidden mind within your CPU. If you found this interesting, please consider <a href="https://www.linkedin.com/in/venkateshtantravahi"><strong>following me</strong></a> for more thoughtful explorations of technology, innovation, and how it shapes our lives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1857cb8ee652" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Predictive Power: How Bayes’ Theorem Fuels Naive Bayes Algorithm to Solve Real-World…]]></title>
            <link>https://vtantravahi.medium.com/unlocking-predictive-power-how-bayes-theorem-fuels-naive-bayes-algorithm-to-solve-real-world-cffd97fd2163?source=rss-309ac2129d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/cffd97fd2163</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[bayes-theorem]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <dc:creator><![CDATA[venkateshtantravahi]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 21:22:09 GMT</pubDate>
            <atom:updated>2024-02-10T21:22:09.031Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking Predictive Power: How Bayes’ Theorem Fuels Naive Bayes Algorithm to Solve Real-World Problems</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.canva.com%2Fdesign%2FDAF8K8tRamA%2Fview%3Fembed%26meta&amp;display_name=Canva&amp;url=https%3A%2F%2Fwww.canva.com%2Fdesign%2FDAF8K8tRamA%2Fview&amp;image=https%3A%2F%2Fwww.canva.com%2Fdesign%2FDAF8K8tRamA%2Fscreen%3Ftype%3Dthumbnail&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=canva" width="1024" height="1024" frameborder="0" scrolling="no"><a href="https://medium.com/media/faa3ab7726084c4a96a6f61cb8156a48/href">https://medium.com/media/faa3ab7726084c4a96a6f61cb8156a48/href</a></iframe><h3>Introduction</h3><p>In the constantly shifting realm of machine learning, we can see that many intricate algorithms are rooted in the fundamental principles of statistics and probability. These mathematical domains serve as the crucial framework for comprehending patterns in data, allowing us to make highly accurate forecasts about future events. Among these principles, Bayes’ Theorem shines as a fundamental cornerstone, offering a robust equation for refining the probabilities of hypotheses as new evidence emerges. Not only does this theorem showcase the predictive capabilities of statistical reasoning, but it also serves as the foundation for one of the most widely utilized machine learning algorithms today: the Naive Bayes algorithm.</p><p>At its heart, machine learning is all about interpreting data. This constantly evolving field has revolutionized problem-solving in multiple industries, revolutionizing the way we automate tasks and make complex decisions. Behind these groundbreaking innovations lies a combination of mathematical and computational techniques. A deep comprehension of data structures, like trees, is essential for developing effective algorithms. Take the Naive Bayes algorithm, for example. It harnesses the power of probability calculations to execute tasks with precision, while incorporating the beauty of mathematical reasoning into its design and execution.</p><p>As our journey begins, we will delve into the seamless transition from the fundamentals of statistics to their practical implementation in machine learning through the Naive Bayes algorithm. This powerful method utilizes a tree data structure to effectively organize and analyze data, perfectly exemplifying the fusion of mathematical theory and practical computational frameworks. Throughout our exploration, we will not only reveal the theoretical foundations of the Naive Bayes algorithm but also demonstrate its remarkable adaptability in tackling real-life challenges, such as identifying spam or diagnosing diseases.</p><h3>Understanding the Bayes&#39; Theorem</h3><blockquote>In <a href="https://en.wikipedia.org/wiki/Probability_theory">probability theory</a> and <a href="https://en.wikipedia.org/wiki/Statistics">statistics</a>, <strong>Bayes’ theorem</strong> (alternatively <strong>Bayes’ law</strong> or <strong>Bayes’ rule</strong>), named after <a href="https://en.wikipedia.org/wiki/Thomas_Bayes">Thomas Bayes</a>, describes the <a href="https://en.wikipedia.org/wiki/Probability">probability</a> of an <a href="https://en.wikipedia.org/wiki/Event_(probability_theory)">event</a>, based on prior knowledge of conditions that might be related to the event.</blockquote><p>Bayes’ Theorem, a 250-year-old mathematical formula, is a key component in many predictive models used in machine learning. This theorem, named after the Reverend Thomas Bayes, offers a robust approach for revising our beliefs in the face of new evidence. It serves as a fundamental principle in probability theory, illustrating how the likelihood of an event or hypothesis evolves as additional information is acquired. However, what drove the development of Bayes’ Theorem, and how does it differ from traditional decision-making methods such as decision trees?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2uzB07mx4ee5BKyS.jpg" /><figcaption>Thomas Bayes</figcaption></figure><h4>The Genesis and Significance of Bayes’ Theorem</h4><p>Bayes’ Theorem emerged from the need to make decisions with incomplete information, a common scenario in statistics and scientific inquiry. Traditional models, such as decision trees, often rely on a deterministic approach where decisions branch out based on known conditions. However, they may not adequately account for uncertainty or the dynamic updating of beliefs as new data becomes available. Bayes’ Theorem overcomes these limitations by providing a probabilistic framework that quantitatively adjusts predictions or hypotheses based on the likelihood of new evidence.</p><h4>The Formula</h4><p>The theorem can be mathematically expressed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*nCATrimylOGN3d9wR5vmfA.png" /><figcaption>Bayes Theorem</figcaption></figure><p>Where:</p><ul><li><em>P</em>(<em>A</em>∣<em>B</em>) is the probability of event A occurring given that B is true.</li><li><em>P</em>(<em>B</em>∣<em>A</em>) is the probability of event B occurring given that A is true.</li><li><em>P</em>(<em>A</em>) is the prior probability of A occurring.</li><li><em>P</em>(<em>B</em>) is the total probability of B occurring.</li></ul><h4>A Practical Example: Spam Filtering</h4><p>Let’s apply Bayes’ Theorem to a more technology-centric problem: email spam filtering. This is a common application where the algorithm determines whether an incoming email is spam (unwanted email) or not spam (legitimate email), based on the words contained in the email. This example will illustrate the theorem’s utility in categorizing data based on prior knowledge, showcasing its relevance to everyday technology use.</p><p>Imagine an email service that wants to improve its spam filter. The service has historical data indicating that 20% of all emails are spam. It also knows from analysis that the word “free” appears in 80% of spam emails and in 10% of legitimate emails. Given an incoming email that contains the word “free,” we want to calculate the probability that the email is spam. This is a direct application of Bayes’ Theorem, where we update our belief about the email being spam based on the new evidence (the presence of the word “free”).</p><h4>Applying Bayes’ Theorem</h4><p>To calculate the probability of the email being spam given that it contains the word “free” (P(Spam|”free”)), we’ll use Bayes’ theorem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/0*lPvwRZ8Kovcz7Jvc" /></figure><p>Where:</p><ul><li><em>P</em>(“free”∣Spam)=0.80 is the probability of finding the word “free” in a spam email.</li><li><em>P</em>(Spam)=0.20 is the prior probability of any email being spam.</li><li><em>P</em>(“free”) is the total probability of finding the word “free” in any email, which needs to be calculated as the sum of its probability in both spam and legitimate emails.</li></ul><h4>Calculating the Probabilities</h4><p>First, we need to calculate <em>P</em>(“free”), the overall likelihood of the word “free” appearing in an email. This encompasses its presence in both spam and legitimate emails:</p><p><em>P</em>(“free”)=<em>P</em>(“free”∣Spam)⋅<em>P</em>(Spam)+<em>P</em>(“free”∣Not Spam)⋅<em>P</em>(Not Spam)</p><p>Given:</p><ul><li><em>P</em>(“free”∣Not Spam)=0.10 (probability of “free” in legitimate emails),</li><li><em>P</em>(Not Spam)=1−<em>P</em>(Spam)=0.80 (probability of any email not being spam).</li></ul><p>Let’s calculate <em>P</em>(Spam∣”free”) with these values.</p><pre># Given values for the spam filter example<br>P_Spam = 0.20  # Prior probability of any email being spam<br>P_Free_Given_Spam = 0.80  # Probability of &quot;free&quot; in spam emails<br>P_Free_Given_NotSpam = 0.10  # Probability of &quot;free&quot; in legitimate emails<br>P_NotSpam = 1 - P_Spam  # Probability of any email not being spam<br><br># Calculate P(&quot;free&quot;), the total probability of finding the word &quot;free&quot; in any email<br>P_Free = (P_Free_Given_Spam * P_Spam) + (P_Free_Given_NotSpam * P_NotSpam)<br><br># Calculate P(Spam|&quot;free&quot;), the probability of an email being spam given that it contains the word &quot;free&quot;<br>P_Spam_Given_Free = (P_Free_Given_Spam * P_Spam) / P_Free<br><br>print(P_Free, P_Spam_Given_Free)</pre><p>Upon completing our calculations, we discover that the likelihood of an email including the term “free” (P(“free”)) is roughly 24%. However, even more captivating is the probability of an email being categorized as spam when “free” is present (P(Spam∣”free”)) which comes in at a whopping 66.67%. This serves as a prime example of the practical application of Bayes’ Theorem in a contemporary, tech-driven setting, highlighting the significant impact a single word can have in determining whether an email is considered spam.</p><p>Through the use of Bayesian analysis, this example showcases the incredible utility of email spam filtering. This essential function ensures the reliability and protection of our email communication. By implementing Bayes’ Theorem, spam filters possess the ability to adapt to the unique characteristics of every email, leveraging key words to make informed predictions. This serves as a prime demonstration of the theorem’s impressive ability to utilize prior knowledge, such as the frequency of words in spam versus legitimate emails, to effectively and accurately classify emails in real-time.</p><p>The marvel of Bayes’ Theorem lies in its practicality, especially in applications such as spam filtering, where it exemplifies the power and relevance of probabilistic reasoning in technology. By providing not just a mathematical framework but also a means of interpreting data, it allows algorithms to detect patterns and make informed choices that become increasingly accurate with the influx of more information. Through this lens, we can fully appreciate how statistical concepts are not only improving everyday technologies, but also shaping the very fabric of the digital world.</p><h3>From Bayes’ Theorem to Naive Bayes Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m5vB7yYqDSPdcAzq" /><figcaption>Plot of Gaussian NB</figcaption></figure><p>The foundation of Naive Bayes models lies in the renowned Bayes’ theorem. This theorem allows us to determine the likelihood of an event by considering relevant information about the event’s conditions that have been previously observed. When applied to machine learning, this translates to the ability to predict the probability of a particular class based on a given set of features. However, the term “naive” stems from the assumption that all features are unrelated within the context of the class. Though this assumption may not hold true in actual data, it simplifies the computations and often results in highly effective models.</p><h3>Ideal Use Cases for Naive Bayes</h3><ol><li><strong>High Dimensionality:</strong> Naive Bayes classifiers possess a remarkable ability to tackle intricate problems containing numerous features- high-dimensional datasets like text classification, where each word or group of words can be considered as a unique characteristic.</li><li><strong>Rapid Prototyping:</strong> With their straightforwardness and effectiveness, they prove to be a top-notch option for setting a benchmark and promptly experimenting, delivering comparable performance with significantly less computational resources compared to elaborate models.</li><li><strong>Discrete and Continuous Data:</strong> From discrete quantities like word counts to continuous data like document lengths, different adaptations of Naive Bayes have the versatility to handle various types of data gracefully.</li></ol><h3>Variants of Naive Bayes in `scikit-learn`</h3><p>Scikit-learn provides multiple variations of Naive Bayes that are tailored to specific data distributions:</p><ul><li><strong>GaussianNB:</strong> It is the optimal choice for datasets containing continuous features that conform to a Gaussian distribution. It is frequently utilized in classification tasks where the feature’s chances of being associated with a particular class are believed to follow a Gaussian curve.</li><li><strong>MultinomialNB: </strong>It<strong> </strong>is more suitable for data that can be counted or discrete in nature. It operates under the assumption that the features adhere to a multinomial distribution. This approach is especially advantageous in text classification for features that indicate the occurrence or frequency of terms.</li><li><strong>BernoulliNB: </strong>It is specifically catered towards binary/boolean features, making it a valuable tool for text classification tasks involving binary (word presence or absence) features.</li><li><strong>ComplementNB: </strong>It was created to address the issue of imbalanced datasets and is particularly effective in text classification scenarios. It has been known to outperform the traditional MultinomialNB classifier when working with imbalanced data.</li></ul><h4>Costs and Benefits of Naive Bayes Include</h4><ul><li><strong>Simplicity and Speed:</strong> The beauty of Naive Bayes classifiers lies in their easy implementation and quick results, even when working with large datasets.</li><li><strong>Efficiency in High-dimensional Spaces:</strong> Don’t let their straightforward nature fool you — Naive Bayes classifiers are surprisingly adept at handling high-dimensional spaces, which makes them an ideal choice for tasks such as text classification.</li><li><strong>Good Baseline:</strong> One of the key strengths of Naive Bayes classifiers is their ability to provide a solid baseline for classification performance. This makes them a valuable benchmark against which more complex algorithms can be measured.</li><li>The idea of features behaving independently is often unrealistic when dealing with actual data, leading to potential limitations in classifier performance.</li><li>The issue of zero-frequency can arise when a category in the test data has not been seen in the training data, resulting in a probability of 0. This can pose problems, and mitigating techniques like Laplace smoothing are often employed to handle it.</li><li>While Naive Bayes is effective in classifying, it may struggle to provide accurate probability estimates, particularly when the assumption of independence is not met.</li></ul><p>Although Naive Bayes classifiers have their limitations, they are still a valuable tool for machine learning practitioners due to their simplicity, efficiency, and impressive performance. This is especially true in tasks related to text analysis and classification, where there is often a high dimensionality of data.</p><h3><strong>Let’s Get our ✋Dirty!!</strong></h3><h4>Tackling Loan Default Prediction with Machine Learning</h4><p>For years, the financial industry has grappled with the issue of predicting loan defaults. Successfully identifying potential defaults in advance not only saves institutions substantial amounts of money, but also safeguards their operational stability. Fortunately, machines have revolutionary capabilities that can combat this longstanding problem. In our research, we utilize multiple classification algorithms to foresee loan repayment results and evaluate the strengths of each method.</p><h4>The Classification Challenge</h4><p>Our dataset comprises several features about borrowers, including credit history, purpose of the loan, interest rates, FICO score, and others. The target variable is binary, indicating whether a loan is fully paid or not. The goal is to classify whether new borrowers will pay back their loans, based on historical data.</p><h4>Analyzing the Dataset</h4><p>The initial step involves loading the dataset and understanding its structure. We check for the presence of any categorical variables that require encoding, assess the scale of numerical features, and identify any preprocessing steps needed before modeling.</p><h4>Model Selection Process</h4><p>We decide to compare three different algorithms:</p><ul><li>Gaussian Naive Bayes (NB)</li><li>Decision Tree Classifier</li><li>Random Forest Classifier</li></ul><p>The performance of these models will be evaluated using several metrics, with a focus on the accuracy and the ability to identify defaults correctly.</p><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split, GridSearchCV<br>from sklearn.preprocessing import OneHotEncoder, StandardScaler<br>from sklearn.compose import ColumnTransformer<br>from sklearn.pipeline import Pipeline<br>from sklearn.naive_bayes import GaussianNB<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score, classification_report<br><br># Load the dataset<br>file_path = &#39;loan_data.csv&#39;<br>loan_data = pd.read_csv(file_path)<br><br># Identify categorical and numerical features<br>categorical_features = [&#39;purpose&#39;]<br>numerical_features = loan_data.drop(columns=[&#39;purpose&#39;, &#39;not.fully.paid&#39;]).columns.tolist()<br><br># Preprocessing steps for the pipeline<br>categorical_transformer = Pipeline(steps=[<br>    (&#39;onehot&#39;, OneHotEncoder(handle_unknown=&#39;ignore&#39;))])<br><br>numerical_transformer = Pipeline(steps=[<br>    (&#39;scaler&#39;, StandardScaler())])<br><br># Combine preprocessing steps<br>preprocessor = ColumnTransformer(<br>    transformers=[<br>        (&#39;num&#39;, numerical_transformer, numerical_features),<br>        (&#39;cat&#39;, categorical_transformer, categorical_features)])<br><br># Define the models and parameters for GridSearchCV<br>models_and_parameters = {<br>    &#39;GaussianNB&#39;: {<br>        &#39;model&#39;: GaussianNB(),<br>        &#39;params&#39;: {}<br>    },<br>    &#39;DecisionTreeClassifier&#39;: {<br>        &#39;model&#39;: DecisionTreeClassifier(),<br>        &#39;params&#39;: {&#39;DecisionTreeClassifier__max_depth&#39;: [3, 5, 10, None]}<br>    },<br>    &#39;RandomForestClassifier&#39;: {<br>        &#39;model&#39;: RandomForestClassifier(),<br>        &#39;params&#39;: {<br>            &#39;RandomForestClassifier__n_estimators&#39;: [10, 50, 100],<br>            &#39;RandomForestClassifier__max_depth&#39;: [3, 5, 10, None]<br>        }<br>    }<br>}<br><br># Prepare the features and target variable<br>X = loan_data.drop(&#39;not.fully.paid&#39;, axis=1)<br>y = loan_data[&#39;not.fully.paid&#39;]<br><br># Split the dataset into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)<br><br># Results dictionary<br>results = {}<br><br># Perform grid search for each model<br>for model_name, mp in models_and_parameters.items():<br>    pipeline = Pipeline(steps=[(&#39;preprocessor&#39;, preprocessor),<br>                               (model_name, mp[&#39;model&#39;])])<br>    <br>    # Initialize GridSearchCV<br>    grid_search = GridSearchCV(pipeline, mp[&#39;params&#39;], cv=5, scoring=&#39;accuracy&#39;, n_jobs=-1)<br>    <br>    # Fit GridSearchCV<br>    grid_search.fit(X_train, y_train)<br>    <br>    # Best model<br>    best_model = grid_search.best_estimator_<br>    <br>    # Predictions<br>    y_pred = best_model.predict(X_test)<br>    <br>    # Save the results<br>    results[model_name] = {<br>        &#39;best_params&#39;: grid_search.best_params_,<br>        &#39;best_score&#39;: grid_search.best_score_,<br>        &#39;test_accuracy&#39;: accuracy_score(y_test, y_pred),<br>        &#39;classification_report&#39;: classification_report(y_test, y_pred)<br>    }<br><br># Output the results<br>for model_name, result in results.items():<br>    print(f&quot;Results for {model_name}:&quot;)<br>    print(&quot;Best Parameters:&quot;, result[&#39;best_params&#39;])<br>    print(&quot;Best Cross-Validation Score:&quot;, result[&#39;best_score&#39;])<br>    print(&quot;Test Accuracy:&quot;, result[&#39;test_accuracy&#39;])<br>    print(&quot;Classification Report:\n&quot;, result[&#39;classification_report&#39;])<br>    print(&quot;=&quot;*80)</pre><pre>Results for GaussianNB:<br>Best Parameters: {}<br>Best Cross-Validation Score: 0.7635747437310094<br>Test Accuracy: 0.7682672233820459<br>Classification Report:<br>               precision    recall  f1-score   support<br><br>           0       0.87      0.85      0.86      2408<br>           1       0.31      0.35      0.33       466<br><br>    accuracy                           0.77      2874<br>   macro avg       0.59      0.60      0.60      2874<br>weighted avg       0.78      0.77      0.77      2874<br><br>================================================================================<br>Results for DecisionTreeClassifier:<br>Best Parameters: {&#39;DecisionTreeClassifier__max_depth&#39;: 3}<br>Best Cross-Validation Score: 0.8374095963137334<br>Test Accuracy: 0.8347251217814892<br>Classification Report:<br>               precision    recall  f1-score   support<br><br>           0       0.84      0.99      0.91      2408<br>           1       0.32      0.02      0.03       466<br><br>    accuracy                           0.83      2874<br>   macro avg       0.58      0.51      0.47      2874<br>weighted avg       0.76      0.83      0.77      2874<br><br>================================================================================<br>Results for RandomForestClassifier:<br>Best Parameters: {&#39;RandomForestClassifier__max_depth&#39;: 3, &#39;RandomForestClassifier__n_estimators&#39;: 10}<br>Best Cross-Validation Score: 0.8408413191314124<br>Test Accuracy: 0.83785664578984<br>Classification Report:<br>               precision    recall  f1-score   support<br><br>           0       0.84      1.00      0.91      2408<br>           1       0.00      0.00      0.00       466<br><br>    accuracy                           0.84      2874<br>   macro avg       0.42      0.50      0.46      2874<br>weighted avg       0.70      0.84      0.76      2874<br><br>================================================================================</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ox5YMP6azPvS82aZ" /><figcaption>Confusion Matrix of the above models</figcaption></figure><h4>Gaussian Naive Bayes Classifier</h4><p>The Naive Bayes classifier shows a more balanced classification compared to the Decision Tree and Random Forest. While its accuracy is lower (approximately 76.8%), it manages to predict both classes (0 and 1) with reasonable recall. The recall for class 1 (loans not fully paid) is 35%, which means it correctly identifies 35% of the loans that are not fully paid. This could be crucial for a financial institution since failing to identify defaulting loans could be more costly than misclassifying loans that are paid on time.</p><h4>Decision Tree Classifier</h4><p>The Decision Tree classifier has a higher accuracy (approximately 83.5%) but fails significantly in identifying class 1 instances (loans not fully paid). The recall for class 1 is only 2%, indicating that it almost always predicts that the loan will be paid off, which can be misleading and risky for loan approval processes.</p><h4>Random Forest Classifier</h4><p>The Random Forest classifier has the highest accuracy among the three (approximately 83.8%) but has a recall of 0% for class 1, meaning it fails to correctly identify any of the loans that are not fully paid. It predicts that all loans will be paid off, which, while resulting in high accuracy due to the imbalance in the dataset, could lead to severe financial misjudgments.</p><h4>Imbalance in the Dataset</h4><p>The dataset is imbalanced, as indicated by the number of instances for each class. There are significantly more loans that have been fully paid (class 0) than loans that have not (class 1). This imbalance is also evident in the confusion matrices, where the number of true negatives (correctly predicted fully paid loans) vastly outnumbers the true positives (correctly predicted not fully paid loans).</p><h4>Why Consider Naive Bayes?</h4><p>Considering Naive Bayes over the other models could be beneficial for several reasons:</p><ul><li><strong>Financial Risk Management:</strong> The ability to identify defaulting loans is crucial. Naive Bayes, despite its lower overall accuracy, provides a better balance between sensitivity (recall) and specificity, identifying more instances of the riskier class (loans not fully paid).</li><li><strong>Probabilistic Approach:</strong> Naive Bayes offers a probabilistic perspective, which can be valuable in making risk-based decisions, where understanding the uncertainty of an outcome is important.</li><li><strong>Computationally Efficient:</strong> Naive Bayes is faster and more scalable, requiring less computational resources, which can be a deciding factor when processing large volumes of loan applications.</li></ul><h4>To Summarize</h4><p>In the context of loan default prediction, the cost of false negatives (predicting a defaulting loan as safe) is typically much higher than the cost of false positives (predicting a safe loan as defaulting). Therefore, a model that can better detect the minority class (defaulting loans) is more valuable, even if it sacrifices some overall accuracy. Naive Bayes emerges as a strong candidate in this scenario due to its comparatively better performance in identifying not fully paid loans, which is crucial for minimizing financial risk.</p><h3>Conclusion</h3><p>The enduring power of statistical understanding in our data-driven world is epitomized by Bayes’ Theorem. Its application in the Naive Bayes algorithm exemplifies how a straightforward yet resilient method can successfully tackle intricate predictive tasks, including loan default prediction. This highlights the significance of possessing statistical literacy to effectively interpret and utilize data in diverse fields.</p><p>“Moving forward, we are reminded by Naive Bayes that the most powerful solutions are often rooted in timeless principles that have long been essential in our analytical arsenal. It encourages us to thoughtfully utilize statistical techniques, not just for the purpose of current analysis, but as a gateway to a more insightful, data-centric future.”</p><h4>🟠 <a href="https://medium.com/mlearning-ai/community-mlearning-ai-art-machine-learning-innovators-b81ec864118a">Medium’s Boost</a> / <a href="https://open.substack.com/pub/mlearning/p/new-multimodal-models-data-collection-predictive?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">New Multimodal Models</a>/ <a href="https://open.substack.com/pub/mlearning/p/the-worlds-most-helpful-ai-assistants?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">BEST AI Assistants</a></h4><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cffd97fd2163" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Principal Component Analysis(PCA)]]></title>
            <link>https://vtantravahi.medium.com/principal-component-analysis-pca-37dc2c22cdf0?source=rss-309ac2129d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/37dc2c22cdf0</guid>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pca-analysis]]></category>
            <dc:creator><![CDATA[venkateshtantravahi]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 17:38:24 GMT</pubDate>
            <atom:updated>2024-01-14T17:38:24.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bYWbImJU9CYpwDkX.jpg" /><figcaption>Increase in Data Dimensions</figcaption></figure><h4>Introduction: The Curse of Dimensionality and the Need for PCA</h4><p>Imagine you’re a data scientist working with a vast dataset of astronomical observations, aiming to uncover patterns and insights about distant galaxies. Each observation in your dataset contains hundreds of features: brightness levels in different wavelengths, distances, sizes, and many more. Initially, it seems like having more features should give you more information and better predictive power. But as you delve deeper, you encounter an unexpected problem: the more features you have, the sparser the data becomes in the high-dimensional space. This is the ‘curse of dimensionality’, a phenomenon where the volume of the space increases so much that the available data becomes sparse, making it increasingly difficult to find patterns or make predictions.</p><blockquote>Sparse means <a href="https://www.google.com/search?sca_esv=598290981&amp;rlz=1C1ONGR_enUS1091US1091&amp;sxsrf=ACQVn0_0bLEfji3ZwPx6zMSMGJBsgH5kEg:1705209600004&amp;q=thinly&amp;si=AKbGX_qTCvK6ifvkUBYDz4foaFZio8iuz3Hr0Golv4IvWINnVxpXjIqxde8QyhQQXZwbD50phasV0f9Yb8nIWbhiJbhqVmMjvg%3D%3D&amp;expnd=1">thinly</a> <a href="https://www.google.com/search?sca_esv=598290981&amp;rlz=1C1ONGR_enUS1091US1091&amp;sxsrf=ACQVn0_0bLEfji3ZwPx6zMSMGJBsgH5kEg:1705209600004&amp;q=dispersed&amp;si=AKbGX_onJk-q0LQUYzV7-GRhpJ5DfMYbdxmZjHhonwaBOkFvxiHXeYdKzAGgm8E7HGIXTIhcSlJbmSidYd1y8--pswV0NYrvgxczEmJPOZxppElT2tUkeWE%3D&amp;expnd=1">dispersed</a> or scattered.</blockquote><p>This is where dimensionality reduction techniques become crucial. In essence, dimensionality reduction is about simplifying the complexity of high-dimensional data while retaining as much meaningful information as possible. There are two primary types of dimensionality reduction: projection and manifold learning.</p><ol><li><strong>Projection</strong> involves mapping data points from a high-dimensional space to a lower-dimensional space. It’s like casting a shadow of a three-dimensional object onto a two-dimensional surface. The shadow (or projection) captures certain aspects of the object, although it might lose some details.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A8XZtwDqdDKNni5y.jpg" /><figcaption>Projection Learning (<a href="https://slideplayer.com/slide/13055479/">Image Source</a>)</figcaption></figure><ol><li><strong>Manifold Learning</strong> is a bit more intricate. It assumes that the data lies along a manifold (a curved surface) in a high-dimensional space. Manifold learning techniques aim to unfold this manifold, like opening a crumpled piece of paper, to reveal the simpler, intrinsic structure hidden within the complex high-dimensional data.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*QjOXHSB-FdKVQ6cYc58BoQ.png" /><figcaption>Manifold Learning (<a href="https://www.researchgate.net/figure/Manifold-learning-techniques-MDS-ISOMAP-LLE-t-SNE-and-Spectral-embedding-SE-or_fig3_353943547">Image Source</a>)</figcaption></figure><p>Both methods have their merits, but in this article, we’ll focus on a particular projection technique that stands out for its simplicity and effectiveness: <strong><em>Principal Component Analysis (PCA)</em></strong>. PCA helps in identifying the directions (called principal components) along which the variance in the data is maximum. In other words, PCA finds the lines along which the data is most spread out, and it projects the high-dimensional data along these lines, thereby reducing dimensions while preserving as much variability as possible.</p><p>As we explore PCA further, we’ll delve into its mathematical foundations, including how it preserves variance, identifies principal components, and why it assumes data is centered around the origin. We’ll also look at practical implementations using Python’s Scikit-Learn library, discussing how to choose the right number of dimensions, PCA for compression, and advanced variations like Randomized PCA and Incremental PCA.</p><p>By the end of this journey, you’ll have a deep understanding of PCA, empowering you to tackle the curse of dimensionality in your own datasets, and unveiling patterns that were hidden in the vastness of high-dimensional space.</p><h4>Discussing PCA Mathematics</h4><p>let’s dive into the mathematical core of Principal Component Analysis (PCA). PCA isn’t just a black-box tool; understanding its mathematics can give you deeper insights into data and how PCA manipulates it.</p><ol><li><strong>Preserving Variance: The Goal of PCA</strong></li></ol><p>At the heart of PCA is the concept of variance, which measures how much the data points are spread out. The main goal of PCA is to preserve as much variance as possible when we reduce the dimensionality of the data.</p><p>Let’s say our data set has <em>n</em> dimensions, and we want to reduce it to <em>k</em> dimensions (where <em>k</em>&lt;<em>n</em>). PCA achieves this by finding the <em>k</em> directions (principal components) along which the variance is maximized. These directions are identified using the covariance matrix of the data. The covariance matrix, denoted as Σ, is an <em>n*n</em> matrix where each element represents the covariance between two dimensions.</p><p>The principal components are the eigenvectors of the covariance matrix Σ, and they are sorted by their corresponding eigenvalues in descending order. The eigenvalue associated with each eigenvector indicates the amount of variance captured by that principal component.</p><p>2. <strong>Principal Components: The New Axes</strong></p><p>The principal components are orthogonal to each other, and they form a new set of axes for the data. The first principal component is the direction in which the data varies the most. The second principal component is orthogonal to the first and is the direction of the next highest variance, and so on.</p><p>Mathematically, if we denote our data matrix as <em>X</em> (with zero mean), the first principal component PC₁ can be found by solving the equation:</p><blockquote>∑ v<em>₁ = λ</em>1<em>*v₁</em></blockquote><p>where v₁ is the eigenvector corresponding to the largest eigenvalue <em>λ</em>1​ of Σ. The second principal component PC₂​ is found in a similar manner, subject to the constraint that it’s orthogonal to PC₁​, and so on for subsequent components.</p><p>3. <strong>Why Centering the Data is Important</strong></p><p>PCA assumes that the data is centered around the origin. This is because PCA is sensitive to the scale of the variables. If the data is not centered, the PCA directions are influenced more by the mean of the data than the actual structure of the data. Centering is done by subtracting the mean of each variable from the dataset. Mathematically, if Xᵢⱼ is the jᵗʰ variable for the iᵗʰ observation, then the centered variable \widetilde{xᵢⱼ} is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/90/1*u8let4rLixfPvBVE0q3dOw.png" /></figure><p>where xⱼ​ is the mean of the jᵗʰ variable.</p><p>4. <strong>Projecting Data Down to d-Dimensions</strong></p><p>Once we have the principal components, we can transform the data into the new space defined by these components. This transformation is a projection of the data onto the principal components. If V is the matrix with the eigenvectors as columns, then the projected data Y in the new space is given by:</p><blockquote>Y = XV</blockquote><p>Here, X is the original data matrix, and Y is the transformed data with reduced dimensions.</p><p>In the next section, we’ll see how to implement these concepts using Python’s Scikit-Learn library, covering practical aspects like choosing the right number of dimensions for your PCA, and how to use PCA for data compression and incremental learning.</p><h4>Let’s see in action 💻</h4><p><strong>Step1: Generating and visualizing Data<br></strong>Now, let’s generate our dataset. We’re creating a synthetic 3D dataset for this demonstration. Visualizing this data will help us understand its structure and how PCA might transform it.</p><pre># imports<br>import numpy as np<br>from mpl_toolkits.mplot3d import Axes3D<br>import matplotlib.pyplot as plt<br>from sklearn.decomposition import PCA<br><br># Generating a synthetic 3D dataset<br>np.random.seed(0)<br>X = np.dot(np.random.rand(100, 3), np.random.rand(3, 3))<br><br># Visualizing the original 3D data<br>fig = plt.figure()<br>ax = fig.add_subplot(111, projection=&#39;3d&#39;)<br>ax.scatter(X[:, 0], X[:, 1], X[:, 2])<br>plt.title(&quot;Original 3D Data&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*7UQgFCD5uPLigGPgkQxUmw.png" /><figcaption>Synthetic Generated Data</figcaption></figure><p><strong>Step2: Applying PCA to Reduce Dimensions</strong></p><p>With our 3D dataset ready, the next step is to apply PCA for dimensionality reduction. We aim to project this data onto a 2D plane, capturing as much variance as possible.</p><pre># Applying PCA<br>pca = PCA(n_components=3)<br>X_pca = pca.fit_transform(X)</pre><pre># Plotting Original Data vs. PCA Transformed Data<br>fig = plt.figure(figsize=(12, 6))<br># Plotting the Original 3D Data<br>ax1 = fig.add_subplot(121, projection=&#39;3d&#39;)<br>ax1.scatter(X[:, 0], X[:, 1], X[:, 2], color=&#39;red&#39;, alpha=0.5)<br>ax1.set_title(&quot;Original Data&quot;)<br>ax1.set_xlabel(&quot;X axis&quot;)<br>ax1.set_ylabel(&quot;Y axis&quot;)<br>ax1.set_zlabel(&quot;Z axis&quot;)<br><br># Plotting the PCA Transformed 2D Data<br>ax2 = fig.add_subplot(122)<br>ax2.scatter(X_pca[:, 0], X_pca[:, 1], color=&#39;blue&#39;, alpha=0.5)<br>ax2.set_title(&quot;PCA Transformed Data (2D)&quot;)<br>ax2.set_xlabel(&quot;Principal Component 1&quot;)<br>ax2.set_ylabel(&quot;Principal Component 2&quot;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJcJZ0ZaT1W-0h6VAjAcwA.png" /><figcaption>Original Data Vs PCA</figcaption></figure><p><strong>Step3: Explaining the Variance Ratio</strong></p><p>One key aspect of PCA is understanding how much variance each principal component captures. This is known as the explained variance ratio.</p><pre># Explained Variance Ratio<br>explained_variance = pca.explained_variance_ratio_<br>print(&quot;Explained Variance Ratio:&quot;, explained_variance)<br><br>#output:<br># Explained Variance Ratio: [0.83350234 0.13910518 0.02739248]<br><br># Creating a bar chart for the Explained Variance Ratio<br>plt.bar(range(1, len(explained_variance) + 1), explained_variance, alpha=0.7, align=&#39;center&#39;)<br>plt.title(&#39;Explained Variance by Each Principal Component&#39;)<br>plt.xlabel(&#39;Principal Component&#39;)<br>plt.ylabel(&#39;Variance Ratio&#39;)<br>plt.xticks(range(1, len(explained_variance) + 1))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*5G9EV3PcwUgY-xNbCXFuxQ.png" /><figcaption>Explained Variance Ratio</figcaption></figure><p><strong>Step4: Discussing the Choice of Dimensions</strong></p><p>A crucial decision in PCA is choosing the number of dimensions to reduce to. This often depends on the cumulative explained variance ratio. We typically select enough components to retain a significant percentage of the total variance, like 95%.</p><pre># Cumulative variance<br>cumulative_variance = np.cumsum(explained_variance)<br># Determining the number of components to reach 95% variance<br>n_components_95 = np.argmax(cumulative_variance &gt;= 0.95) + 1<br>print(&quot;Number of components to retain 95% variance:&quot;, n_components_95)<br><br>#output <br># Number of components to retain 95% variance: 2</pre><p><strong>Step5: PCA for Data Compression and Reconstruction</strong></p><p>PCA can also be used for data compression. We can compress the data to fewer dimensions and then reconstruct it back. This process, while lossy, retains much of the original information.</p><pre># Reducing dimensions for compression<br>pca_95 = PCA(n_components=n_components_95)<br>X_reduced = pca_95.fit_transform(X)<br><br># Reconstructing the data from the compressed form<br>X_reconstructed = pca_95.inverse_transform(X_reduced)</pre><p>To understand the impact of compression and reconstruction, let’s visualize the reconstructed data alongside the original data. This comparison will show us the loss of information due to dimensionality reduction.</p><pre># Plotting Original Data<br>fig = plt.figure(figsize=(15, 5))<br><br>ax1 = fig.add_subplot(131, projection=&#39;3d&#39;)<br>ax1.scatter(X[:, 0], X[:, 1], X[:, 2], color=&#39;red&#39;, alpha=0.5)<br>ax1.set_title(&quot;Original Data&quot;)<br>ax1.set_xlabel(&quot;X&quot;)<br>ax1.set_ylabel(&quot;Y&quot;)<br>ax1.set_zlabel(&quot;Z&quot;)<br><br># Plotting Reduced Data<br>ax2 = fig.add_subplot(132)<br>ax2.scatter(X_reduced[:, 0], X_reduced[:, 1], color=&#39;blue&#39;, alpha=0.5)<br>ax2.set_title(&quot;Reduced Data (2D)&quot;)<br>ax2.set_xlabel(&quot;Principal Component 1&quot;)<br>ax2.set_ylabel(&quot;Principal Component 2&quot;)<br><br># Plotting Reconstructed Data<br>ax3 = fig.add_subplot(133, projection=&#39;3d&#39;)<br>ax3.scatter(X_reconstructed[:, 0], X_reconstructed[:, 1], X_reconstructed[:, 2], color=&#39;green&#39;, alpha=0.5)<br>ax3.set_title(&quot;Reconstructed Data&quot;)<br>ax3.set_xlabel(&quot;X&quot;)<br>ax3.set_ylabel(&quot;Y&quot;)<br>ax3.set_zlabel(&quot;Z&quot;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUa9Q0_s5djHkmw22piA0g.png" /><figcaption>Original vs Reduced vs Reconstructed Dara</figcaption></figure><p><strong>Step6: Exploring Variants: Randomized and Incremental PCA</strong></p><p>Finally, let’s explore PCA variants like Randomized PCA, which is faster for large datasets, and Incremental PCA, suitable for datasets too large to fit in memory. These variants can be particularly useful in different scenarios and offer flexibility in handling diverse data sizes and computational constraints.</p><pre>from sklearn.decomposition import IncrementalPCA, PCA<br><br># Randomized PCA<br>randomized_pca = PCA(n_components=n_components_95, svd_solver=&#39;randomized&#39;)<br>X_reduced_randomized = randomized_pca.fit_transform(X)<br><br># Incremental PCA<br>incremental_pca = IncrementalPCA(n_components=n_components_95)<br>X_reduced_incremental = incremental_pca.fit_transform(X)<br><br># Plotting Results of Randomized PCA and Incremental PCA<br>fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))<br><br># Randomized PCA<br>ax1.scatter(X_reduced_randomized[:, 0], X_reduced_randomized[:, 1], color=&#39;purple&#39;, alpha=0.5)<br>ax1.set_title(&quot;Randomized PCA&quot;)<br>ax1.set_xlabel(&quot;Principal Component 1&quot;)<br>ax1.set_ylabel(&quot;Principal Component 2&quot;)<br><br># Incremental PCA<br>ax2.scatter(X_reduced_incremental[:, 0], X_reduced_incremental[:, 1], color=&#39;orange&#39;, alpha=0.5)<br>ax2.set_title(&quot;Incremental PCA&quot;)<br>ax2.set_xlabel(&quot;Principal Component 1&quot;)<br>ax2.set_ylabel(&quot;Principal Component 2&quot;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*N34xAo1_yn9IiCWoPtXSWg.png" /><figcaption>Randomized vs Incremental PCA</figcaption></figure><h4>Transition to Real-World Application</h4><p>Up to this point, we’ve explored PCA through synthetic examples, which has allowed us to understand the mechanics and mathematics behind this powerful dimensionality reduction technique. These examples serve as a stepping stone to grasping the core concepts without the added complexity of real-world noise and data irregularities. However, the true value of</p><p>PCA is best demonstrated with actual, complex datasets where the intricacies of data patterns come to life.</p><p>We will now take our PCA exploration further by applying it to the Wine Quality dataset. This dataset, with its rich and nuanced physicochemical properties, offers a perfect opportunity to see PCA in action on real-world data. By reducing the dimensionality, we aim to uncover the underlying structure of the data and identify the principal components that capture the essence of wine quality.</p><p>To see the step-by-step application of PCA on the Wine Quality dataset, including preprocessing, variance analysis, and visualizations, check out the detailed Jupyter Notebook I’ve prepared. It will walk you through the entire process, providing insights into how PCA can be a valuable tool in your data analysis arsenal.</p><p><a href="https://colab.research.google.com/drive/19W2OOz5jV_Ylq177M2A1I4ZS31Ek-HgZ?usp=sharing">Google Colaboratory</a></p><h4>Conclusion</h4><p>As we have journeyed from the abstract complexities of high-dimensional spaces to the tangible realities of the Wine Quality dataset, Principal Component Analysis (PCA) has proven to be an indispensable ally. We began with an exploration of the curse of dimensionality, an inevitable challenge in modern data analysis, where the expansion of our feature space can paradoxically obscure the insights we seek. With each added dimension, our data became sparser, and the risk of overfitting grew.</p><p>PCA emerged as a guiding light, offering a pathway through the curse by projecting our data into a lower-dimensional space that preserves its intrinsic variability. We navigated through the mathematical foundations of PCA, understanding how it identifies the principal components that act as the axes along which the essence of our data is most clearly revealed.</p><p>Taking theory into practice, we applied PCA to a synthetic dataset, which laid the groundwork for our real-world application. In the Wine Quality dataset, PCA did more than just simplify data; it unveiled the relationships and patterns that contribute to the quality of wine, patterns that may have remained hidden in the shadow of higher dimensions.</p><p>As we conclude this exploration, it is my hope that the insights gained here illuminate your path in data science, whether you’re reducing dimensions, uncovering hidden patterns, or making data-driven decisions. I am grateful for your engagement and curiosity throughout this article.</p><p>For more discussions on the intersection of data analysis and real-world applications, and to continue our exploration of machine learning together, I invite you to connect with me on LinkedIn. Your thoughts, questions, and insights are always welcome as we further our shared journey in the vast and ever-evolving landscape of data science.</p><p><a href="https://www.linkedin.com/in/venkateshtantravahi/">Follow me on LinkedIn</a> for more articles and discussions on data science.</p><p>Thank you for reading, and may your data be ever in your favor!</p><h4><a href="https://mlearning.substack.com/about">WRITER at MLearning.ai</a> / <a href="https://open.substack.com/pub/mlearning/p/ai-comprehensive-guide-hallucinations-llm?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">Hallucinations in AI</a> / <a href="https://open.substack.com/pub/mlearning/p/20k-ai-art-prompts-generator-guide-collection?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">20K+ Art Prompts</a></h4><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37dc2c22cdf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>