<?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 Austin Adeyanju on Medium]]></title>
        <description><![CDATA[Stories by Austin Adeyanju on Medium]]></description>
        <link>https://medium.com/@austin.adeyanju?source=rss-b4b36c503c01------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bU-gwjuSJlI0h-D6M3MZcQ.jpeg</url>
            <title>Stories by Austin Adeyanju on Medium</title>
            <link>https://medium.com/@austin.adeyanju?source=rss-b4b36c503c01------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:15:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@austin.adeyanju/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The DevOps interview questions that quietly trip people up]]></title>
            <link>https://medium.com/@austin.adeyanju/the-devops-interview-questions-that-quietly-trip-people-up-0b32bd673384?source=rss-b4b36c503c01------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b32bd673384</guid>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Austin Adeyanju]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 10:52:39 GMT</pubDate>
            <atom:updated>2026-06-30T10:52:39.192Z</atom:updated>
            <content:encoded><![CDATA[<p>And what interviewers are actually listening for underneath each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tWq_-lp4Eg64JZEz.png" /></figure><p>There’s a strange thing that happens in DevOps interviews. People who run production systems every day sit down, get asked something they genuinely know, and the answer comes out thin. After enough of these on both sides of the table, I think I know why.</p><p>The gap usually isn’t knowledge. It’s that interviewers are listening for a specific thing under each question, and you can answer correctly while missing it completely.</p><p>Here are a few of the questions where that happens most, and what’s going on underneath them.</p><p><strong>“A pod is stuck in CrashLoopBackOff. How do you debug it?”</strong></p><p>The weak answer lists possible causes. The strong answer is a loop you can hear: describe the pod to read the events and the last exit code, pull the previous container’s logs with --previous, check the probes, and confirm the image tag is actually what you think it is. Exit code 137 means an OOM kill, so go look at the memory limits. What they&#39;re testing isn&#39;t whether you can recite causes. It&#39;s whether you have a method, or you&#39;re guessing.</p><p><strong>“What’s the difference between a liveness and a readiness probe?”</strong></p><p>Easy to answer, easy to answer shallowly. Liveness decides whether to restart the container. Readiness decides whether to send it traffic. The tell is whether you know that putting a database check in your liveness probe means a slow database will restart-loop a perfectly healthy app. Restarting and routing are two separate concerns, and the question is really asking whether you understand that.</p><p><strong>“How do you let GitHub Actions deploy to AWS without storing static keys?”</strong></p><p>The answer is OIDC. AWS trusts GitHub’s provider, and a role’s trust policy says which repo and branch may assume it. Short-lived credentials, no stored secret. The part that separates people who’ve done it from people who’ve read about it is the trust policy condition. The sub claim has to match exactly, down to the format like repo:org/name:ref:refs/heads/main. A small mismatch is the difference between a working deploy and an afternoon lost to a &quot;not authorized to perform sts:AssumeRoleWithWebIdentity&quot; error.</p><p><strong>“It’s 3am and the service is down. What do you do first?”</strong></p><p>Juniors start diagnosing. Seniors start sizing it up: is it really down, for everyone or just some, and did anything change right before it broke? If a deploy lines up with the alert, rolling it back is often faster than understanding the failure first. And you communicate while you work, even if it’s just “investigating, update in ten.” The signal here is whether you put recovery ahead of diagnosis under pressure. You don’t owe a root cause at minute five. You owe a path back to working.</p><p><strong>“Tell me about a time you broke production.”</strong></p><p>“I’ve never broken anything” is the wrong answer. So is a long story blaming someone else. They want ownership and learning: what happened, how you recovered, and what you changed so it can’t happen the same way again. Failures are inputs to better systems, and this question checks whether you treat them that way.</p><p>Notice the pattern. None of these are really about trivia. They’re about judgment, method, and whether you’ve felt the thing you’re describing. That’s what gets the offer once your technical bar is cleared.</p><p>I kept running into this same gap often enough that I wrote it all down. The <a href="https://meediax.gumroad.com/l/dupzk">DevOps Interview Prep Pack</a> is 45 questions across Kubernetes, AWS, Terraform, CI/CD, incident response, Linux and networking, and the behavioral round. Each one has a model answer and a short note on what the interviewer is really listening for, the same way the examples above work. It comes with a job-search tracker and a 30-day prep plan too.</p><p>If you want to see the format first, there’s a free sample with ten of the questions: <a href="https://meediax.gumroad.com/l/dpqjpl">https://meediax.gumroad.com/l/dpqjpl</a>.</p><p>The full pack is here: <a href="https://meediax.gumroad.com/l/dupzk">https://meediax.gumroad.com/l/dupzk</a>.</p><p>What questions have tripped you up in interviews? I’m always collecting more.</p><p><em>Originally published at </em><a href="https://open.substack.com/pub/engineeredgrowth1/p/the-devops-interview-questions-that?r=6rkxd&amp;utm_campaign=post&amp;utm_medium=web&amp;showWelcomeOnShare=true"><em>https://engineeredgrowth1.substack.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b32bd673384" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Customer Churn with Logistic Regression: My ML Zoomcamp 2025 Module 3 Journey]]></title>
            <link>https://medium.com/@austin.adeyanju/predicting-customer-churn-with-logistic-regression-my-ml-zoomcamp-2025-module-3-journey-972f40bf8f47?source=rss-b4b36c503c01------2</link>
            <guid isPermaLink="false">https://medium.com/p/972f40bf8f47</guid>
            <dc:creator><![CDATA[Austin Adeyanju]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 18:25:06 GMT</pubDate>
            <atom:updated>2026-01-22T18:25:06.608Z</atom:updated>
            <content:encoded><![CDATA[<p>In Module 3 of ML Zoomcamp 2025, I learned how machine learning can help businesses anticipate customer behavior — specifically, predicting who’s likely to churn. This module introduced me to the world of classification models, feature importance, and the logic behind logistic regression. It wasn’t just about building a model — it was about understanding how data tells a story about loyalty, risk, and human behavior.</p><h3>💼 The Project: Predicting Customer Churn</h3><p>The goal of this module’s project was clear — <strong>identify customers likely to stop using a service</strong> before they actually do.</p><p>We used a <strong>Kaggle dataset</strong> with historical customer information and built a <strong>binary classification model</strong> that outputs a probability of churn for each user.<br> If the likelihood is high, the company can send personalized discounts or promotions to retain that customer.</p><p>In formula terms, it’s represented as:</p><p>g(xi)=yig(x_i) = y_ig(xi​)=yi​</p><p>Where yi∈{0,1}y_i \in \{0, 1\}yi​∈{0,1} — with 0 meaning <em>not churning</em> and 1 meaning <em>churning</em>.</p><p>This real-world use case made me appreciate how <strong>machine learning directly supports customer retention strategies</strong>.</p><h3>🧹 Step 1: Data Preparation</h3><p>The first step was all about <strong>cleaning and structuring data</strong> for modeling.<br> Using <strong>Pandas</strong>, I learned to:</p><ul><li>Lowercase column names</li><li>Replace spaces with underscores</li><li>Convert yes/no answers into binary (1/0) values</li><li>Handle missing data with fillna()</li></ul><p>These transformations may seem small, but they’re essential for consistency and preventing model errors.</p><h3>🧮 Step 2: Setting Up the Validation Framework</h3><p>We split the data into <strong>training</strong> and <strong>test sets</strong> using Scikit-Learn’s train_test_split.</p><p>This ensured our model could generalize to unseen data — a critical part of building trust in predictions.</p><p>It was also the first time I used Scikit-Learn’s validation tools instead of manual splits, which streamlined the workflow.</p><h3>🔍 Step 3: Exploratory Data Analysis (EDA)</h3><p>Before modeling, we explored the data to understand patterns and distributions.</p><p>EDA revealed:</p><ul><li>The overall churn rate</li><li>The balance between categories</li><li>Which numerical or categorical variables might influence churn</li></ul><p>Using commands like:</p><pre>df.isnull().sum()<br>df.x.value_counts(normalize=True)</pre><p>I could visualize imbalances and decide which features might be meaningful later.</p><h3>📊 Step 4: Measuring Feature Importance</h3><p>This part was fascinating — discovering <strong>what makes customers leave</strong>.</p><h3>🔹 Churn Rate and Risk Ratio</h3><p>By comparing the churn rate across categories, we saw which groups were more likely to leave.<br> A <strong>risk ratio &gt; 1</strong> indicated higher churn likelihood, while &lt;1 meant the opposite.</p><h3>🔹 Mutual Information</h3><p>From information theory, mutual information measures <strong>how much one feature tells us about another</strong>.<br> Here, it told us how strongly each feature related to churn.</p><h3>🔹 Correlation Coefficient</h3><p>For numerical features, correlation revealed whether variables moved together or inversely.</p><ul><li>Positive correlation → churn increases with the feature</li><li>Negative correlation → churn decreases with the feature</li></ul><p>These insights made me realize that <strong>feature analysis isn’t just technical — it’s storytelling through data</strong>.</p><h3>⚙️ Step 5: One-Hot Encoding</h3><p>Categorical variables needed conversion into numbers before modeling.<br>We used Scikit-Learn’s DictVectorizer() to perform <strong>One-Hot Encoding</strong>, turning each category into its own binary feature.</p><p>For example, “Contract Type: Month-to-Month” became a new column with 1 or 0 values. This expanded our feature set while preserving the meaning behind categories.</p><h3>📈 Step 6: Logistic Regression — The Core of Classification</h3><p>Then came the main event — <strong>Logistic Regression</strong>.<br> It’s similar to linear regression but designed for <strong>binary outcomes</strong>.<br> Instead of predicting a continuous value, it predicts a <strong>probability between 0 and 1</strong> using the <strong>sigmoid function</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*gx48q02vM-jRQfWbkLXhHA.png" /><figcaption>Sigmoid function</figcaption></figure><p>This simple mathematical curve makes logistic regression powerful for tasks like churn prediction, fraud detection, and customer segmentation.</p><h3>🧠 Step 7: Training and Evaluating the Model</h3><p>Using Scikit-Learn’s LogisticRegression() class, we trained the model and tested it on validation data.</p><pre>from sklearn.linear_model import LogisticRegression<br>model = LogisticRegression()<br>model.fit(X_train, y_train)<br>pred = model.predict(X_val)</pre><p>Then we evaluated performance using <strong>accuracy</strong> — the percentage of correctly predicted outcomes.</p><p>The validation and test results were close, meaning the model generalized well.</p><h3>🔍 Step 8: Model Interpretation</h3><p>By inspecting the model coefficients, we learned <strong>which features most influenced churn</strong>. For example, higher tenure or long-term contracts often reduced churn probability, while month-to-month plans increased it.</p><p>It was eye-opening to see business logic reflected mathematically in model weights.</p><h3>🚀 Step 9: Using the Model</h3><p>Finally, we retrained the model on the combined <strong>training + validation</strong> sets and made predictions on the test data. The accuracy remained consistent, confirming the model’s reliability.</p><p>This phase completed the <strong>full ML lifecycle</strong> — from raw data to actionable insights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=972f40bf8f47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Notebook to Production: Building an End-to-End Customer Conversion System]]></title>
            <link>https://medium.com/@austin.adeyanju/from-notebook-to-production-building-an-end-to-end-customer-conversion-system-1a145b32d19e?source=rss-b4b36c503c01------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a145b32d19e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[digital-marketing]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Austin Adeyanju]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 13:55:17 GMT</pubDate>
            <atom:updated>2026-01-01T15:29:20.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5XcvA7Bdln6RHjLCZSU41A.png" /></figure><p>Every data scientist knows the struggle: You build a model with 95% accuracy in a Jupyter Notebook, show it to your manager, and then… it dies there. It never makes it into the hands of the marketing team who actually need it.</p><p>Today, we are going to fix that.</p><p>In this guide, I will walk you through building a <strong>Full-Stack Machine Learning Application</strong> that doesn’t just predict <em>who</em> will buy, but automatically decides <em>what marketing action</em> to take.</p><p>We will go from a raw Excel file to a deployed API on Google Cloud, complete with a frontend dashboard.</p><h3>🏗️ The Tech Stack</h3><p>We aren’t just training a model; we are building a product. Here is the stack:</p><ul><li><strong>The Brain:</strong> XGBoost (Classification + Regression)</li><li><strong>The Glue:</strong> Flask (Python API)</li><li><strong>The Package:</strong> Docker (Containerization)</li><li><strong>The Cloud:</strong> Google Cloud Run (Serverless Deployment)</li><li><strong>The Face:</strong> Streamlit (User Interface)</li></ul><h3>Step 1: The Strategy (RFM Analysis)</h3><p>Raw transactional data (e.g., “User 123 bought socks on Tuesday”) is useless for machine learning. We need to summarize user behavior.</p><p>We used the <strong>RFM Framework</strong> to transform thousands of transaction rows into a single “Customer Snapshot”:</p><ul><li><strong>Recency:</strong> How many days since their last purchase?</li><li><strong>Frequency:</strong> How often do they buy?</li><li><strong>Monetary:</strong> How much have they spent in total?</li></ul><p>We also engineered two targets to answer two different business questions:</p><ol><li><strong>Who will convert?</strong> (Binary Classification)</li><li><strong>When will they convert?</strong> (Regression)</li></ol><p>A snippet of our Feature Engineering.</p><pre>features = history_df.groupby(&#39;Customer ID&#39;).agg({<br>    &#39;InvoiceDate&#39;: lambda x: (snapshot_date - x.max()).days, # Recency<br>    &#39;Invoice&#39;: &#39;nunique&#39;,                                  # Frequency<br>    &#39;TotalSum&#39;: &#39;sum&#39;                                        # Monetary<br>})</pre><h3>Step 2: The Models</h3><p>We trained two separate <strong>XGBoost</strong> models.</p><p>Why XGBoost? It handles tabular data better than deep learning in most cases, requires less preprocessing, and is incredibly fast.</p><ul><li><strong>The Classifier:</strong> Predicts the <em>probability</em> (0–100%) that a user buys in the next 30 days.</li><li><strong>The Regressor:</strong> Predicts the <em>number of days</em> until that purchase happens.</li></ul><p>Crucially, we saved these models using joblib with <strong>compression</strong>. This small detail became vital later when we tried to dockerize the app, reducing our model size by 90%.</p><h3>Step 3: From “Prediction” to “Action”</h3><p>A probability score of 0.85 means nothing to a marketing manager. They need to know what to <em>do</em>.</p><p>We built a decision engine inside our API that translates math into marketing strategy:</p><pre>def determine_action(prob, days_to_buy, value):<br>    if prob &gt; 0.8 and value &gt; 2000:<br>        return &quot;VIP ALERT: Send Early Access Catalog.&quot;<br>    elif prob &gt; 0.5 and days_to_buy &lt; 7:<br>        return &quot;URGENCY: Send &#39;Free Shipping for 48 Hours&#39; nudge.&quot;<br>    elif prob &lt; 0.3:<br>        return &quot;RISK: Add to Re-engagement Campaign.&quot;</pre><p>This transforms our tool from a “Predictor” into an “Automation System.”</p><h3>Testing API Locally</h3><p><strong>Run in your terminal:</strong> python test_api_local.py</p><p><strong>You should receive a JSON response like below:</strong></p><pre>✅ SUCCESS!<br>API Response:<br><br>{<br>  &quot;estimated_days_to_buy&quot;: 18.1,<br>  &quot;probability_to_convert&quot;: 0.9511,<br>  &quot;recommended_action&quot;: &quot;VIP ALERT: Send Early Access Catalog. (Expected buy in 18 days)&quot;<br>}</pre><h3>Step 4: The Docker Struggle (And How We Fixed It)</h3><p>This was the hardest part of the project.</p><p>Initially, my Docker image was a massive <strong>3.3GB</strong>.</p><ul><li><strong>The Culprit:</strong> My requirements.txt was installing xgboost without version pinning, which accidentally pulled in massive NVIDIA GPU drivers (even though I was using a CPU).</li><li><strong>The Mistake:</strong> I was copying my local virtual environment (.venv) into the container.</li></ul><p><strong>The Optimization Strategy:</strong></p><ul><li><strong>Clean </strong><strong>.dockerignore:</strong> We ensured local temp files (.git, .venv, data/) were ignored.</li><li><strong>Version Pinning:</strong> We pinned xgboost==1.7.6, which avoids the 400MB NVIDIA bloat.</li><li><strong>Multi-Stage Build:</strong> We used a builder stage in Docker to keep the final image clean.</li></ul><p><strong>Result:</strong> The image dropped from <strong>3.3GB → 1.2GB</strong>.</p><h3>Step 5: Going Live on Google Cloud Run</h3><p>We chose <strong>Google Cloud Run</strong> because it is “Serverless.” You give it a container, and it gives you a URL. It scales to zero (costs $0) when no one is using it.</p><p>The deployment process was three commands:</p><ul><li><strong>Tag:</strong> Label the image with the Google Artifact Registry address.</li><li><strong>Push:</strong> Upload the 1.2GB image to the cloud.</li><li><strong>Deploy:</strong> Launch the service.</li></ul><p><em>NB: Remember to replace </em><em>your-project-id with your ctual GCP Project ID.</em></p><pre># 1. Tag the image<br>docker tag conversion-api us-central1-docker.pkg.dev/your-project-id/my-models/conversion-api<br><br># 2. Push to Cloud<br>docker push us-central1-docker.pkg.dev/your-project-id/my-models/conversion-api<br><br># 3. Launch the service<br>gcloud run deploy conversion-api-service \<br>    --image us-central1-docker.pkg.dev/your-project-id/my-models/conversion-api \<br>    --region us-central1 \<br>    --allow-unauthenticated \<br>    --memory 2Gi</pre><p><strong>Result:</strong> You will receive a public URL (e.g., <a href="https://conversion-api-service-xyz.a.run.app)./">https://conversion-api-service-xyz.a.run.app).</a></p><p>We encountered a “Permission Denied” error during the push, which we solved by authenticating Docker specifically with Google: gcloud auth configure-docker.</p><h3>API Usage (cURL / Postman)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRFpCXEnxwjYoQzDAUuCBA.png" /><figcaption>API usage in Postman</figcaption></figure><p><strong>Endpoint:</strong> POST /predict_action</p><p><strong>Payload:</strong></p><pre>{<br>    &quot;Recency&quot;: 10,<br>    &quot;Frequency&quot;: 5,<br>    &quot;Monetary&quot;: 500<br>}</pre><p><strong>Response:</strong></p><pre>{<br>    &quot;probability_to_convert&quot;: 0.85,<br>    &quot;estimated_days_to_buy&quot;: 5.2,<br>    &quot;recommended_action&quot;: &quot;VIP ALERT: Send Early Access Catalog.&quot;<br>}</pre><h3>Step 6: The Frontend (Streamlit)</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJEgcmR9d-N4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJEgcmR9d-N4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJEgcmR9d-N4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c671f000c3e252f82d953a1c7bf1e996/href">https://medium.com/media/c671f000c3e252f82d953a1c7bf1e996/href</a></iframe><p>Finally, we wanted to see the model in action. We built a simple UI using <strong>Streamlit</strong>.</p><p>It connects to our Google Cloud API, allowing us to tweak “Recency” and “Frequency” sliders to see how the model’s predictions change in real-time.</p><p>The final result?</p><p>A Marketing Manager can now enter a customer profile and instantly see:</p><ul><li>✅ <strong>Probability:</strong> 95%</li><li>📅 <strong>Timeline:</strong> Buying in 18 days</li><li>🚀 <strong>Action:</strong> “Send VIP Catalog”</li></ul><h3>🏁 Conclusion</h3><p>This project was more than just fitting a curve to data. It was an exercise in <strong>ML Engineering</strong>.</p><p>We learned that:</p><ul><li><strong>Models are small parts of the system:</strong> The data pipeline and API logic are just as important.</li><li><strong>Optimization matters:</strong> A 3GB container is expensive and slow; a 1GB container is production-ready.</li><li><strong>Actionable output wins:</strong> Predicting “0.85” is okay; predicting “Send Email” is valuable.</li></ul><p><strong>🔗 [</strong><a href="https://github.com/sojiadeyanju/user-conversion-prediction.git"><strong>Link to GitHub Repository</strong></a><strong>]</strong></p><p><em>If you found this guide helpful, follow me for more Full-Stack Data Science projects!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a145b32d19e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Machine Learning Models on Kubernetes: A Practical Guide with FastAPI, Docker, and Kind]]></title>
            <link>https://medium.com/@austin.adeyanju/deploying-machine-learning-models-on-kubernetes-a-practical-guide-with-fastapi-docker-and-kind-048fdf1483f4?source=rss-b4b36c503c01------2</link>
            <guid isPermaLink="false">https://medium.com/p/048fdf1483f4</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Austin Adeyanju]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 18:01:58 GMT</pubDate>
            <atom:updated>2025-12-15T18:01:58.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*op1D1jUqKwJ65N2jpbkqyA.png" /><figcaption>Deploy ML Models on Kubernetes</figcaption></figure><h3>Introduction: From Model Training to Scalable Production</h3><p>You’ve trained a brilliant machine learning model, and it performs flawlessly in your notebook. But the true test — and often the biggest challenge — is moving that model into a production environment where it can handle millions of real-time requests reliably and cost-effectively.</p><p>Simply running it on a single large server is inefficient and prone to failure. Module 10 of the <a href="https://datatalks.club/blog/machine-learning-zoomcamp.html">Machine Learning Zoomcamp</a> walks you through a robust, modern setup for deploying an ONNX-based machine learning inference service using <strong>FastAPI</strong> for low-latency API handling, containerizing it with <strong>Docker</strong>, and orchestrating it on a local <strong>Kubernetes (K8s)</strong> cluster with <strong>Kind</strong>. We’ll cover everything from initial setup to auto-scaling and resource management, giving you the blueprint for a production-ready MLOps pipeline.</p><h3>Why Kubernetes for ML Model Deployment?</h3><p>Kubernetes (K8s) is an open-source container orchestration system for automating deployment, scaling, and management of containerized applications. For machine learning models, it offers several key advantages:</p><ul><li><strong>Scalability:</strong> Easily scale your inference service up or down based on demand.</li><li><strong>High Availability:</strong> Automatically restarts failed containers and distributes traffic across healthy instances.</li><li><strong>Resource Management:</strong> Efficiently allocates CPU and memory resources to your services.</li><li><strong>Portability:</strong> Deploy your models consistently across different environments (local, cloud, on-prem).</li></ul><h3>1. Setting Up Your Local Kubernetes Cluster with Kind</h3><p>For local development and testing, <strong>Kind (Kubernetes in Docker)</strong> is an excellent choice. It allows you to run a full-fledged Kubernetes cluster directly within Docker containers on your machine.</p><p>First, ensure you have the necessary tools installed:</p><ul><li><strong>kubectl</strong>: The command-line tool for interacting with Kubernetes clusters.</li><li><strong>Kind</strong>: The tool that creates and manages your local clusters.</li></ul><p>Once installed, creating a cluster is as simple as running:</p><p>Bash</p><pre>kind create cluster</pre><p>This command provisions a basic Kubernetes cluster inside a Docker container, ready for your deployments.</p><h3>2. Building Your FastAPI Service for ONNX Model Inference</h3><p>Our ML model inference service will be built using <strong>FastAPI</strong>, a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. We’ll use an <strong>ONNX</strong> (Open Neural Network Exchange) model for clothing classification.</p><h4>Dependencies:</h4><p>You’ll need a few key Python packages:</p><ul><li>fastapi: The web framework.</li><li>uvicorn: An ASGI server to run your FastAPI application.</li><li>onnxruntime: To load and run your ONNX model.</li><li>keras-image-helper: For convenient image preprocessing.</li></ul><h4>Inference Logic:</h4><p>The core of our service is a /predict endpoint that accepts an image URL, processes it, and returns a classification:</p><p>Python</p><pre># app.py<br>from fastapi import FastAPI<br>from pydantic import BaseModel<br>import onnxruntime as rt<br>import numpy as np<br>from keras_image_helper import create_preprocessor<br>import requests<br>from io import BytesIO<br>from PIL import Image</pre><pre># Load the ONNX model<br>model_path = &quot;clothing-model.onnx&quot; # Ensure your ONNX model is in the same directory<br>sess = rt.InferenceSession(model_path)<br>input_name = sess.get_inputs()[0].name<br>output_name = sess.get_outputs()[0].name</pre><pre>preprocessor = create_preprocessor(&#39;xception&#39;, target_size=(299, 299))</pre><pre>class ImageRequest(BaseModel):<br>    url: str</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/health&quot;)<br>def health_check():<br>    return {&quot;status&quot;: &quot;ok&quot;}</pre><pre>@app.post(&quot;/predict&quot;)<br>async def predict(request: ImageRequest):<br>    response = requests.get(request.url)<br>    img = Image.open(BytesIO(response.content))<br>    X = preprocessor.from_pil(img)</pre><pre>    # Make prediction<br>    pred = sess.run([output_name], {input_name: X})<br>    result = pred[0][0] # Assuming a single output</pre><pre>    # Example: Map prediction to class names<br>    classes = [&#39;dress&#39;, &#39;hat&#39;, &#39;longsleeve&#39;, &#39;outwear&#39;, &#39;skirt&#39;, &#39;t-shirt&#39;] # Replace with your actual classes<br>    score = dict(zip(classes, result))</pre><pre>    return {&quot;prediction&quot;: score}</pre><p>This code snippet shows the essential components: loading the ONNX model, defining a /health endpoint for Kubernetes probes, and a /predict endpoint to perform inference.</p><h3>3. Containerizing Your Service with Docker</h3><p>Docker is fundamental for packaging your application and its dependencies into a single, isolated unit. This ensures that your service runs consistently across any environment.</p><p>Create a Dockerfile in the root of your project:</p><p>Dockerfile</p><pre># Dockerfile<br>FROM python:3.10-slim-buster</pre><pre>WORKDIR /app</pre><pre># Install uv (fast Python package installer)<br>RUN curl -LsSf <a href="https://astral.sh/uv/install.sh">https://astral.sh/uv/install.sh</a> | sh<br>ENV PATH=&quot;/root/.cargo/bin:${PATH}&quot;</pre><pre>COPY requirements.txt .<br>RUN uv pip install -r requirements.txt --system</pre><pre>COPY . .</pre><pre>EXPOSE 8000</pre><pre>CMD [&quot;uvicorn&quot;, &quot;app:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>And your requirements.txt:</p><pre>fastapi<br>uvicorn<br>onnxruntime<br>keras-image-helper<br>requests<br>Pillow</pre><p>Build your Docker image and tag it:</p><p>Bash</p><pre>docker build -t clothing-classifier .</pre><p>You can test it locally:</p><p>Bash</p><pre>docker run -p 8000:8000 clothing-classifier</pre><p>Then, try sending a request to http://localhost:8000/health or your /predict endpoint.</p><p>Finally, you need to load this image into your Kind cluster so Kubernetes can access it:</p><p>Bash</p><pre>kind load docker-image clothing-classifier</pre><h3>4. Deploying to Kubernetes</h3><p>Deploying to Kubernetes involves defining your desired application state using YAML configuration files. We’ll need two main resources: a <strong>Deployment</strong> and a <strong>Service</strong>.</p><h4>Deployment (deployment.yaml):</h4><p>A Deployment describes how to run your application, including the Docker image to use and the number of desired replicas.</p><p>YAML</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: clothing-classifier-deployment<br>spec:<br>  replicas: 2 # Start with 2 instances of our service<br>  selector:<br>    matchLabels:<br>      app: clothing-classifier<br>  template:<br>    metadata:<br>      labels:<br>        app: clothing-classifier<br>    spec:<br>      containers:<br>      - name: clothing-classifier<br>        image: clothing-classifier:latest # Our Docker image<br>        ports:<br>        - containerPort: 8000<br>        resources:<br>          requests:<br>            cpu: &quot;250m&quot; # Request 0.25 CPU core<br>            memory: &quot;500Mi&quot; # Request 500 MiB memory<br>          limits:<br>            cpu: &quot;500m&quot; # Limit to 0.5 CPU core<br>            memory: &quot;1Gi&quot; # Limit to 1 GiB memory<br>        livenessProbe: # Health check for pod restarts<br>          httpGet:<br>            path: /health<br>            port: 8000<br>          initialDelaySeconds: 5<br>          periodSeconds: 5<br>        readinessProbe: # Health check for serving traffic<br>          httpGet:<br>            path: /health<br>            port: 8000<br>          initialDelaySeconds: 5<br>          periodSeconds: 5</pre><p>Apply the deployment:</p><p>Bash</p><pre>kubectl apply -f deployment.yaml</pre><h4>Service (service.yaml):</h4><p>A Service provides a stable network endpoint for your Pods. It acts as a load balancer, distributing incoming traffic across your running application instances.</p><p>YAML</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: clothing-classifier-service<br>spec:<br>  selector:<br>    app: clothing-classifier<br>  ports:<br>    - protocol: TCP<br>      port: 80 # External port<br>      targetPort: 8000 # Container port<br>  type: LoadBalancer # For local testing, Kind provides a load balancer</pre><p>Apply the service:</p><p>Bash</p><pre>kubectl apply -f service.yaml</pre><p>Since we’re using a local Kind cluster, you’ll likely need to use <strong>port forwarding</strong> to access the service from your host machine:</p><p>Bash</p><pre>kubectl port-forward service/clothing-classifier-service 8080:80</pre><p>Now you can send requests to <a href="http://localhost:8080/predict.">http://localhost:8080/predict.</a></p><h3>5. Scaling with Horizontal Pod Autoscaler (HPA)</h3><p>One of Kubernetes’ most powerful features is its ability to automatically scale your applications. The <strong>Horizontal Pod Autoscaler (HPA)</strong> automatically increases or decreases the number of Pod replicas based on observed metrics like CPU utilization.</p><p>First, ensure you have the <strong>Metrics Server</strong> installed in your cluster, which HPA relies on to gather resource metrics:</p><p>Bash</p><pre>kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml</pre><p>Then, define your HPA (hpa.yaml):</p><p>YAML</p><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: clothing-classifier-hpa<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: clothing-classifier-deployment<br>  minReplicas: 2 # Minimum number of replicas<br>  maxReplicas: 5 # Maximum number of replicas<br>  metrics:<br>  - type: Resource<br>    resource:<br>      name: cpu<br>      target:<br>        type: Utilization<br>        averageUtilization: 50 # Target 50% CPU utilization</pre><p>Apply the HPA:</p><p>Bash</p><pre>kubectl apply -f hpa.yaml</pre><p>Now, if you put your service under heavy load (e.g., with a stress testing tool or hey command-line tool), you&#39;ll observe the HPA automatically creating new Pods to handle the increased demand, and scaling them back down when the load subsides.</p><h3>6. Health Checks and Resource Management</h3><p>Kubernetes uses <strong>probes</strong> to monitor the health of your application and <strong>resource requests/limits</strong> to manage resource consumption.</p><ul><li><strong>Liveness Probe</strong>: Defined in our deployment.yaml, the liveness probe checks if your application is running correctly. If it fails, Kubernetes will restart the Pod. This ensures that your service remains responsive even if it encounters an internal error.</li><li><strong>Readiness Probe</strong>: Also in deployment.yaml, the readiness probe determines if a Pod is ready to serve traffic. If a Pod is not ready (e.g., still loading a large model), it won&#39;t receive requests, preventing users from experiencing errors during startup.</li><li><strong>Resource Requests and Limits</strong>: These are crucial for efficient cluster management.</li><li><strong>Requests (</strong><strong>requests.cpu, </strong><strong>requests.memory):</strong> The minimum amount of CPU and memory your Pod needs. Kubernetes uses these values for scheduling decisions.</li><li><strong>Limits (</strong><strong>limits.cpu, </strong><strong>limits.memory):</strong> The maximum amount of CPU and memory your Pod can consume. If a Pod exceeds its memory limit, it will be terminated. If it exceeds its CPU limit, it will be throttled. These prevent a single misbehaving Pod from consuming all resources on a node.</li></ul><h3>Conclusion: The Blueprint for MLOps Success</h3><p>By adopting this integrated approach — FastAPI for performance, Docker for portability, and Kubernetes for orchestration — you move beyond simple model serving to truly production-grade MLOps. This architecture ensures <strong>elasticity</strong> (scaling automatically with HPA), <strong>reliability</strong> (guaranteed uptime via Probes), and <strong>efficiency</strong> (controlled resource consumption via requests and limits). This comprehensive blueprint is the foundation for managing any complex, high-traffic machine learning system in a cost-effective and highly available manner.</p><h3>What Next? Take Your Deployment to the Cloud!</h3><p>In this guide, we used Kind for a local environment, but the exact same YAML files and Docker image can be deployed to any major cloud provider’s managed Kubernetes service (EKS, GKE, AKS).</p><p>Here are your next steps to expand this pipeline:</p><ol><li><strong>Observability:</strong> Integrate <strong>Prometheus</strong> and <strong>Grafana</strong> to monitor real-time metrics (latency, error rate, CPU) beyond the basic HPA metrics.</li><li><strong>CI/CD Pipeline:</strong> Automate the process using <strong>GitHub Actions</strong> or <strong>GitLab CI</strong> to automatically build the Docker image and apply the Kubernetes YAML whenever you update your model or code.</li><li><strong>Advanced Traffic Management:</strong> Explore <strong>Service Mesh</strong> tools like <strong>Istio</strong> or <strong>Linkerd</strong> to enable advanced features like A/B testing, canary rollouts, and fine-grained traffic shifting for seamless model updates.</li></ol><p>Machine Learning Zoomcamp is a free 4-month course teaching machine learning engineering. You’ll learn Python ML basics through to production deployment, build real projects, and join a supportive community. <a href="https://airtable.com/shryxwLd0COOEaqXo">Join the course here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=048fdf1483f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Serverless: Deploying Deep Learning Models with AWS Lambda and TensorFlow Lite]]></title>
            <link>https://medium.com/@austin.adeyanju/going-serverless-deploying-deep-learning-models-with-aws-lambda-and-tensorflow-lite-86bba1e13e9f?source=rss-b4b36c503c01------2</link>
            <guid isPermaLink="false">https://medium.com/p/86bba1e13e9f</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Austin Adeyanju]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 09:46:04 GMT</pubDate>
            <atom:updated>2025-12-08T09:46:04.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-IbfgHdNdfBYyK-Z901LaA.jpeg" /><figcaption>AWS Lambda. Source: <a href="https://aws.amazon.com/">aws.com</a></figcaption></figure><p>In the world of Machine Learning, training a model is often just half the battle. In a previous session, we built and trained a clothes classification model using Keras and TensorFlow to categorize items like t-shirts and pants. But currently, that model effectively lives in a Jupyter Notebook. To create real business value, you need to <strong>deploy</strong> it.</p><p>But deployment can be daunting. Do you spin up a dedicated EC2 instance? How do you handle scaling if traffic spikes? What about the cost of keeping a server running 24/7 even when no one is using it?</p><p>This is where <strong>Serverless</strong> architecture comes in. By using <strong>AWS Lambda</strong>, we can execute our code without ever managing a server. However, there is a catch: deep learning frameworks like TensorFlow are heavy, often exceeding the size limits of serverless environments.</p><p>In this module, we will solve this problem by converting our model to <strong>TensorFlow Lite</strong>, wrapping it in a Docker container, and deploying it to AWS Lambda. By the end, you will have a scalable, cost-effective API ready for production.</p><h3>What is AWS Lambda? ☁️</h3><p>AWS Lambda is a serverless computing service that lets you execute code without provisioning or managing infrastructure.</p><p><strong>Why choose Lambda for Model Deployment?</strong></p><ul><li><strong>Serverless Architecture:</strong> You don’t need to provision or manage servers.</li><li><strong>Cost-Effective:</strong> You pay only for requests and compute time; idle time is free. It even offers a free tier with 1 million requests per month.</li><li><strong>Automatic Scaling:</strong> It adjusts automatically based on the volume of requests.</li><li><strong>Focus on Code:</strong> It allows data scientists to focus on the logic rather than the infrastructure.</li></ul><h3>The Challenge: TensorFlow is Heavy 🏋️</h3><p>While TensorFlow is powerful, it is a massive framework, unpacking to approximately 1.7 GB. This presents significant challenges in a serverless environment:</p><ol><li><strong>Historical Constraints:</strong> AWS Lambda previously had a strict package size limit of 50 MB. While Docker has increased these limits, size still matters.</li><li><strong>Performance:</strong> Large frameworks lead to increased storage costs, slower loading times, and a larger RAM footprint.</li></ol><h3>The Solution: TensorFlow Lite 🚀</h3><p>To solve the size and performance issues, we switch to <strong>TensorFlow Lite (TF-Lite)</strong>. TF-Lite is a lightweight alternative designed specifically for <em>inference</em> (making predictions) rather than training.</p><p>By converting our original Keras model into the TF-Lite format, we can significantly reduce the model size and improve performance.</p><h3>Step-by-Step Implementation Guide</h3><h3>1. Setting up the Lambda Function 🛠️</h3><p>To get started, navigate to the AWS Management Console and search for the Lambda service.</p><ul><li><strong>Create a Function:</strong> Select “Author from scratch”.</li><li><strong>Configuration:</strong> Name your function (e.g., mlzoomcamp-test), and select the runtime (e.g., Python 3.9) and architecture (x86_64).</li></ul><h3>2. The Python Logic (lambda_function.py)</h3><p>The handler function receives two parameters: event (input data) and context (execution details).</p><p>Here is the script that handles image preprocessing, loads the TensorFlow Lite interpreter, and runs prediction logic:</p><p>Python</p><pre>import tflite_runtime.interpreter as tflite<br>from keras_image_helper import create_preprocessor</pre><pre># Initialize the preprocessor for the Xception model<br>preprocessor = create_preprocessor(&#39;xception&#39;, target_size=(299, 299))</pre><pre># Load the TFLite model and allocate tensors<br>interpreter = tflite.Interpreter(model_path=&#39;clothing-model.tflite&#39;)<br>interpreter.allocate_tensors()</pre><pre># Get input and output details<br>input_index = interpreter.get_input_details()[0][&#39;index&#39;]<br>output_index = interpreter.get_output_details()[0][&#39;index&#39;]</pre><pre># Define the classes (labels) for the model<br>classes = [<br>    &#39;dress&#39;, &#39;hat&#39;, &#39;longsleeve&#39;, &#39;outwear&#39;, &#39;pants&#39;,<br>    &#39;shirt&#39;, &#39;shoes&#39;, &#39;shorts&#39;, &#39;skirt&#39;, &#39;t-shirt&#39;<br>]</pre><pre>def predict(url):<br>    # Preprocess the image from the URL<br>    X = preprocessor.from_https://medium.com/url(url)</pre><pre>    # Set the input tensor<br>    interpreter.set_tensor(input_index, X)</pre><pre>    # Run the inference<br>    interpreter.invoke()</pre><pre>    # Get the prediction result<br>    preds = interpreter.get_output_details(output_index)</pre><pre>    # Combine classes with predictions<br>    return dict(zip(classes, preds[0]))</pre><pre>def lambda_handler(event, context):<br>    # Extract the URL from the input event<br>    url = event.get(&#39;url&#39;)<br>    <br>    # Generate prediction<br>    result = predict(url)<br>    <br>    # Return the result as a JSON-compatible dictionary<br>    return result</pre><h3>3. Packaging with Docker 🐳</h3><p>For deep learning dependencies, we package our code using Docker. When installing TF-Lite via pip, there is a crucial detail to remember:</p><ul><li><strong>Use the RAW file:</strong> When installing from a GitHub URL, ensure you use the raw path (/raw/ or ?raw=true).</li><li><strong>Avoid:</strong> Using the standard blob link, which results in a zipfile.BadZipFile error.</li></ul><p><strong>ENTRYPOINT vs. CMD</strong></p><ul><li><strong>ENTRYPOINT</strong>: Specifies the command that will always run when the container starts.</li><li><strong>CMD</strong>: Specifies arguments fed to the ENTRYPOINT. For Lambda, we typically overwrite the CMD arguments.</li></ul><p><strong>The </strong><strong>Dockerfile:</strong></p><p>Dockerfile</p><pre># Use the AWS Lambda Python base image<br>FROM public.ecr.aws/lambda/python:3.10</pre><pre># Install Keras Image Helper<br>RUN pip install keras-image-helper</pre><pre># Install TensorFlow Lite Runtime<br># IMPORTANT: Use the raw GitHub link to avoid &quot;BadZipFile&quot; errors<br>RUN pip install <a href="https://github.com/alexeygrigorev/tflite-aws-lambda/raw/main/tflite/tflite_runtime-2.14.0-cp310-cp310-linux_x86_64.whl">https://github.com/alexeygrigorev/tflite-aws-lambda/raw/main/tflite/tflite_runtime-2.14.0-cp310-cp310-linux_x86_64.whl</a></pre><pre># Copy the model file and the lambda function code into the container<br>COPY clothing-model.tflite .<br>COPY lambda_function.py .</pre><pre># Set the CMD to your handler (filename.function_name)<br>CMD [ &quot;lambda_function.lambda_handler&quot; ]</pre><h3>4. Testing Locally 🧪</h3><p>Before deploying, verify the container locally.</p><ul><li><strong>Build:</strong> docker build -t clothing-model .</li><li><strong>Run:</strong> docker run -it --rm -p 8080:8080 clothing-model:latest</li><li><strong>Test:</strong> Use a python script to POST data to <a href="http://localhost:8080/2015-03-31/functions/function/invocations.">http://localhost:8080/2015-03-31/functions/function/invocations.</a></li></ul><h3>5. Deploying to AWS Elastic Container Registry (ECR) 🚀</h3><p>To get the image into Lambda, we push it to ECR.</p><p>Bash</p><pre># 1. Create Repository<br>aws ecr create-repository --repository-name clothing-model</pre><pre># 2. Login<br>aws ecr get-login-password --region &lt;region&gt; | docker login --username AWS --password-stdin &lt;account-id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com</pre><pre># 3. Tag and Push<br>docker tag clothing-model:latest &lt;account-id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/clothing-model:latest<br>docker push &lt;account-id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/clothing-model:latest</pre><h3>6. Exposing via API Gateway 🌐</h3><p>To make your function accessible via a public URL, we use <strong>Amazon API Gateway</strong>.</p><ul><li><strong>Create API:</strong> Select <strong>REST API</strong> in the API Gateway console.</li><li><strong>Create Resource:</strong> Add a resource (e.g., /predict).</li><li><strong>Create Method:</strong> Add a <strong>POST</strong> method and link it to your Lambda function.</li><li><strong>Deploy:</strong> Deploy the API to a stage (e.g., test) to get your public Invoke URL.</li></ul><h3>Automating with Serverless Framework ⚡</h3><p>For a production-grade workflow, you can automate the entire ECR, Lambda, and API Gateway setup using the <strong>Serverless Framework</strong>.</p><p>Create a serverless.yml file:</p><p>YAML</p><pre>service: clothing-model<br>provider:<br>  name: aws<br>  region: us-east-1<br>  ecr:<br>    images:<br>      appimage:<br>        path: ./<br>functions:<br>  predict:<br>    image:<br>      name: appimage<br>    events:<br>      - http:<br>          path: predict<br>          method: post</pre><p>Run serverless deploy to build, push, and deploy your entire stack in one command.</p><h3>Testing Your Live Service</h3><p>Once deployed, you can verify your API using this script:</p><p>Python</p><pre>import requests</pre><pre>url = &#39;https://[YOUR-ID].execute-api.[REGION].amazonaws.com/test/predict&#39;<br>data = {&#39;url&#39;: &#39;http://bit.ly/mlbookcamp-pants&#39;}</pre><pre>result = requests.post(url, json=data).json()<br>print(result)</pre><h3>Key Takeaways 🔑</h3><ul><li><strong>Serverless Efficiency:</strong> AWS Lambda handles infrastructure and scaling, letting you focus on code.</li><li><strong>Cost Control:</strong> You only pay for what you use, making it ideal for sporadic workloads.</li><li><strong>TF-Lite is Essential:</strong> Converting massive TensorFlow models to TF-Lite is critical for performance and size management in serverless environments.</li><li><strong>Docker Nuances:</strong> Always use raw URLs for pip install when building Docker images for Lambda to avoid file errors.</li></ul><h3>Next Steps: Challenge Yourself 🚀</h3><p>Don’t stop here!</p><ul><li><strong>Try different models:</strong> Deploy “Cats vs Dogs” or other Keras models.</li><li><strong>Explore other libraries:</strong> Lambda works great with Scikit-Learn and XGBoost too.</li><li><strong>Go Multi-Cloud:</strong> Try similar serverless services on Google Cloud or Microsoft Azure.</li></ul><p>Congratulations! You have successfully taken a local Keras model and transformed it into a production-ready serverless API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86bba1e13e9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classifying Hair Texture from Scratch: A PyTorch CNN Tutorial]]></title>
            <link>https://medium.com/@austin.adeyanju/classifying-hair-texture-from-scratch-a-pytorch-cnn-tutorial-571513859799?source=rss-b4b36c503c01------2</link>
            <guid isPermaLink="false">https://medium.com/p/571513859799</guid>
            <dc:creator><![CDATA[Austin Adeyanju]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 18:33:31 GMT</pubDate>
            <atom:updated>2025-12-01T18:33:31.571Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Building a custom Convolutional Neural Network to distinguish hair types using PyTorch 2.0+</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S90sSqv49rlsqHYv_i0jSQ.jpeg" /><figcaption><strong>Convolutional Neural Network</strong></figcaption></figure><p>Computer vision has transformed how we analyze textures and biological features. While pre-trained models like ResNet or VGG are powerful, building a CNN from scratch is the best way to understand the fundamental mechanics of feature extraction.</p><p>In this project, I built a binary classifier to distinguish between hair textures (e.g., <strong>Curly vs. Straight</strong>) using PyTorch. Here is a breakdown of the architecture, data augmentation pipeline, and training logic.</p><h3>1. The Goal &amp; The Data</h3><p>The objective was to take raw image inputs and output a binary probability indicating the hair type. The dataset is based on the <a href="https://www.kaggle.com/datasets/kavyasreeb/hair-type-dataset">Kaggle Hair Type Dataset</a>.</p><p>Since real-world image data is rarely perfect, a robust <strong>Data Augmentation</strong> pipeline was essential. Using torchvision.transforms, I applied random rotations, cropping, and flipping to the training set. This forces the model to learn the <em>texture</em> of the hair rather than memorizing the specific orientation of the original images.</p><p><strong>The Pre-processing Pipeline:</strong></p><p>Python</p><pre>train_transforms = transforms.Compose([<br>    transforms.RandomRotation(50),<br>    # Scale and ratio changes simulate different zoom levels/aspect ratios<br>    transforms.RandomResizedCrop(200, scale=(0.9, 1.0), ratio=(0.9, 1.1)),<br>    transforms.RandomHorizontalFlip(),<br>    transforms.ToTensor(),<br>    # Standard ImageNet normalization helps convergence<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406], <br>                         std=[0.229, 0.224, 0.225])<br>])</pre><p><em>Note: For the test set, I used only resizing and normalization to ensure a deterministic evaluation benchmark.</em></p><h3>2. The Model Architecture</h3><p>I designed a custom CNN architecture optimized for binary classification. The structure follows a classic “Encoder-Decoder” pattern (or Feature Extractor -&gt; Classifier).</p><p><strong>Input Shape:</strong> (3, 200, 200) (Channels, Height, Width)</p><p><strong>The Layers:</strong></p><ul><li><strong>Convolutional Layer:</strong> 32 filters, $3\times3$ kernel, ReLU activation. This layer detects edges and simple textures.</li><li><strong>Max Pooling:</strong> $2\times2$ pooling to downsample the spatial dimensions, reducing computation and controlling overfitting.</li><li><strong>Flatten:</strong> Converts the 2D feature maps into a 1D vector.</li><li><strong>Dense Layers:</strong> A hidden layer with 64 neurons, leading to a final output neuron.</li><li><strong>Output Activation:</strong> Sigmoid.</li></ul><p><strong>The Code:</strong></p><p>Python</p><pre>class HairClassifier(nn.Module):<br>    def __init__(self):<br>        super(HairClassifier, self).__init__()<br>        <br>        # Conv Block<br>        self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3)<br>        self.relu = nn.ReLU()<br>        self.pool = nn.MaxPool2d(kernel_size=2)<br>        <br>        # Flatten<br>        self.flatten = nn.Flatten()<br>        <br>        # Calculation: (200 - 3 + 1) / 2 = 99<br>        self.flat_features = 32 * 99 * 99 <br>        <br>        # Dense Block<br>        self.fc1 = nn.Linear(self.flat_features, 64)<br>        self.fc2 = nn.Linear(64, 1) # Single neuron for binary output<br>        self.sigmoid = nn.Sigmoid()</pre><pre>    def forward(self, x):<br>        x = self.pool(self.relu(self.conv1(x)))<br>        x = self.flatten(x)<br>        x = self.relu(self.fc1(x))<br>        x = self.sigmoid(self.fc2(x))<br>        return x</pre><h3>3. Training Configuration</h3><p>To ensure reproducibility — a critical aspect of ML engineering — I set strict random seeds for Numpy, PyTorch, and CUDA backends (SEED = 42).</p><p>Optimizer &amp; Loss:</p><p>Since the model ends with a Sigmoid activation (outputting a probability between 0 and 1), the mathematically correct loss function is Binary Cross Entropy.</p><ul><li><strong>Loss Function:</strong> nn.BCELoss()</li><li><strong>Optimizer:</strong> torch.optim.SGD with lr=0.002 and momentum=0.8.</li></ul><p>I used Stochastic Gradient Descent (SGD) with momentum rather than Adam to have more fine-grained control over the convergence in this specific shallow architecture.</p><h3>4. Evaluating Performance</h3><p>During the training loop, I tracked two specific metrics to gauge stability vs. generalization:</p><ul><li><strong>Median Training Accuracy:</strong> To see the “typical” performance of the model while ignoring outliers during the volatile early epochs.</li><li><strong>Mean Test Loss:</strong> To check if the model was generalizing well to unseen data.</li></ul><p><strong>The Results Logic:</strong></p><p>Python</p><pre># Calculating Median Training Accuracy<br>median_acc = np.median(train_accuracies)</pre><pre># Calculating Mean Test Loss<br>mean_test_loss = np.mean(test_losses)</pre><h3>Conclusion &amp; Next Steps</h3><p>This project demonstrates that you don’t always need massive pre-trained transformers to perform image classification. A well-structured CNN with proper data augmentation can effectively learn to distinguish texture features like hair types.</p><p><strong>Future improvements:</strong></p><ul><li>Implementing <strong>Dropout</strong> layers to further prevent overfitting.</li><li>Expanding to <strong>Multi-class classification</strong> (Wavy, Kinky, Curly, Straight) by changing the output layer to 4 neurons and using CrossEntropyLoss.</li></ul><p><em>This article is based on Module 8 of the </em><a href="https://datatalks.club/blog/machine-learning-zoomcamp.html"><em>Machine Learning Zoomcamp</em></a><em> course thanks to @AlexeyGrigorev. If you’re interested in learning more about practical machine learning, consider joining the course at DataTalks.Club.</em></p><p><a href="https://medium.com/@meediax.digital/learning-machine-learning-insights-from-ml-zoomcamp-2025-module-1-bf9364453390">Read my notes on Module 1 here</a>.<br><a href="https://medium.com/@meediax.digital/building-a-car-price-prediction-model-with-linear-regression-my-ml-zoomcamp-2025-module-2-f01892be28b5">Read my notes on Module 2 here.</a><br><a href="https://medium.com/@meediax.digital/predicting-customer-churn-with-logistic-regression-my-ml-zoomcamp-2025-module-3-journey-86541c91e628">Read my notes on Module 3 here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=571513859799" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Raw Data to Production: Building a Crop Yield Prediction System — ML Zoomcamp Project]]></title>
            <link>https://medium.com/@austin.adeyanju/from-raw-data-to-production-building-a-crop-yield-prediction-system-ml-zoomcamp-project-772f0b597e12?source=rss-b4b36c503c01------2</link>
            <guid isPermaLink="false">https://medium.com/p/772f0b597e12</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Austin Adeyanju]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 22:49:26 GMT</pubDate>
            <atom:updated>2025-11-17T22:49:26.297Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Raw Data to Production: Building a Crop Yield Prediction System — ML Zoomcamp Project</h3><p>A complete journey of developing, deploying, and scaling an AI model that helps farmers optimize agricultural decisions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7s-HGdvASa1K8kS0KM06Q.png" /></figure><h3>Introduction</h3><p>“It started with a simple question: Can we use AI to help farmers predict their crop yields more accurately? Twelve days later, I had a production-grade machine learning system deployed on Google Cloud, serving predictions in real-time…”</p><h3>Chapter 1: The Problem</h3><ul><li>Agricultural uncertainty costs billions</li><li>Traditional prediction methods are outdated</li><li>The opportunity for AI/ML intervention</li></ul><h3>Chapter 2: Data Collection &amp; Analysis</h3><ul><li>Sourcing agricultural data</li><li>10,000+ records analyzed</li><li>Key features identified</li><li>Surprising correlations discovered</li></ul><h3>Chapter 3: The ML Journey</h3><ul><li>Testing 7 different algorithms</li><li>Why Gradient Boosting won</li><li>Feature importance revelations</li><li>Hyperparameter tuning challenges</li></ul><h3>Chapter 4: From Notebook to Production</h3><ul><li>Building the Flask API</li><li>Docker containerization struggles</li><li>CORS issues and solutions</li><li>Google Cloud Run deployment</li></ul><h3>Chapter 5: The User Interface</h3><ul><li>Why UI matters for ML adoption</li><li>Building an accessible web interface</li><li>Batch prediction capabilities</li><li>User feedback integration</li></ul><h3>Chapter 6: Results &amp; Impact</h3><ul><li>91% accuracy achieved</li><li>Potential 15–20% yield improvements</li><li>Real farmer feedback</li><li>Future enhancements planned</li></ul><h3>Conclusion</h3><p>“This project taught me that building ML models is just 30% of the work. The real challenge is making them accessible, scalable, and useful to end-users…”</p><p><strong>Key Takeaways:</strong> <a href="https://crop-yield-ui.web.app/">[Crop Yield prediction API]</a></p><p><strong>Code &amp; Demo:</strong> <a href="https://github.com/sojiadeyanju/mlzoomcamp_2025-midterm-project">[Project Repo]</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=772f0b597e12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering Decision Trees and Ensemble Learning: The Heart of Machine Learning Models]]></title>
            <link>https://medium.com/@austin.adeyanju/mastering-decision-trees-and-ensemble-learning-the-heart-of-machine-learning-models-e698f5112c9c?source=rss-b4b36c503c01------2</link>
            <guid isPermaLink="false">https://medium.com/p/e698f5112c9c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Austin Adeyanju]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 14:46:18 GMT</pubDate>
            <atom:updated>2025-11-05T15:37:36.427Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From simple trees to powerful ensembles — learn how Decision Trees, Random Forests, and XGBoost transform predictive modeling.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onqQ6MBjH42XHkY6iv253w.png" /><figcaption>Mastering Decision Trees &amp; Ensembles</figcaption></figure><h3>🧠 Introduction</h3><p>In this module, we explore one of the most powerful families of algorithms in machine learning — <strong>Decision Trees</strong> and their ensemble counterparts (<strong>Random Forests</strong> and <strong>XGBoost</strong>).</p><p>We’ll use a <strong>Credit Risk Scoring Project</strong> as our case study: predicting whether a bank should lend money to a client based on their financial history.</p><p>A <strong>“0”</strong> means <em>client will likely repay</em> → loan approved.<br>A <strong>“1”</strong> means <em>potential defaulter</em> → loan denied.</p><h3>🧹 Data Cleaning &amp; Preparation</h3><ul><li>Download and reformat categorical columns (status, home, marital, records, job).</li><li>Replace extreme values in income, assets, and debt with NaN.</li><li>Fill missing values with 0.</li><li>Keep only clients with status = ok or default.</li><li>Split into:<br>* 60% training<br>* 20% validation<br>* 20% test (using random seed = 11).</li><li>Convert target (status) to binary: <br>* 0 → ok<br>* 1 → default.</li></ul><h3>🌳 Decision Trees</h3><p>Decision Trees make predictions using a <strong>series of if/else rules</strong> based on feature thresholds.</p><ul><li><strong>Pros:</strong> Simple to interpret, flexible for both classification and regression.</li><li><strong>Cons:</strong> Prone to <strong>overfitting</strong>, especially with deep trees.</li></ul><blockquote><em>💡 A </em><strong><em>Decision Stump</em></strong><em> is a shallow tree with only one split — useful for understanding base logic.</em></blockquote><h3>Key Parameters:</h3><ul><li>max_depth: limits how deep the tree can grow.</li><li>min_samples_leaf: ensures each leaf has enough data to generalize.</li><li>export_text: shows readable decision rules.</li></ul><p>To prevent overfitting: reduce max_depth and adjust min_samples_leaf.</p><h3>⚙️ Decision Tree Learning Algorithm</h3><p>At each node:</p><ol><li>Evaluate all features and possible thresholds.</li><li>Choose the split that minimizes <strong>impurity</strong> (or misclassification rate).</li><li>Repeat recursively until stopping criteria are met.</li></ol><h3>Impurity Criteria:</h3><ul><li><strong>Gini Impurity</strong></li><li><strong>Entropy</strong></li><li>(For regression: <strong>MSE</strong>)</li></ul><h3>Stopping Conditions:</h3><ul><li>Node is pure (0% impurity).</li><li>max_depth reached.</li><li>Group too small or max number of leaves reached.</li></ul><h3>🧩 Parameter Tuning</h3><p>Tuning <strong>max_depth</strong> and <strong>min_samples_leaf</strong> is crucial for balancing <strong>bias vs variance</strong>:</p><ul><li>Increase max_depth → more complex, higher variance.</li><li>Decrease max_depth → simpler, higher bias.</li></ul><p>Use <strong>heatmaps</strong> to visualize combinations of these hyperparameters and find the sweet spot for model AUC.</p><pre>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.metrics import roc_auc_score<br>import seaborn as sns<br>import pandas as pd</pre><h3>🌲 Ensemble Learning &amp; Random Forests</h3><p><strong>Ensemble learning</strong> combines multiple “weak” models (e.g., decision trees) to create a stronger predictor.</p><h3>🪵 Random Forests</h3><ul><li>Each tree is trained on a <strong>bootstrapped</strong> sample (random rows + random features).</li><li>Predictions from all trees are <strong>aggregated</strong> (majority vote).</li><li>Reduces overfitting and improves generalization.</li></ul><p><strong>Key Parameters:</strong></p><ul><li>max_depth: controls complexity.</li><li>n_estimators: number of trees.</li><li>random_state: ensures reproducibility.</li></ul><blockquote><em>🌿 Randomness in data sampling and feature selection keeps trees </em>decorrelated<em> and robust.</em></blockquote><h3>⚡Gradient Boosting &amp; XGBoost</h3><p>Unlike Random Forests (parallel), <strong>Gradient Boosting</strong> builds models <strong>sequentially</strong> — each model corrects the errors of the previous one.</p><h3>🔥 XGBoost (Extreme Gradient Boosting)</h3><ul><li>Highly optimized implementation of gradient boosting.</li><li>Handles both classification and regression.</li><li>Requires data wrapped in a special structure: <strong>DMatrix</strong>.</li></ul><h3>Key Hyperparameters:</h3><pre>| Parameter         | Purpose                              |<br>| ------------------|:------------------------------------:|<br>| eta               | Learning rate; controls step size    |<br>| max_depth         | Tree depth (complexity)              |<br>| min_child_weight  | Minimum samples per leaf             |<br>| subsample         |  Fraction of data used per iteration |<br>| colsample_bytree  |  Fraction of features per tree       |<br>| lambda / alpha    |  L2/L1 regularization                |</pre><blockquote><em>🚧 On Mac, XGBoost may require installing a compatible version of </em><em>libomp.<br> Use </em><em>conda install -c conda-forge xgboost for smooth setup.</em></blockquote><h3>🧠 Model Selection</h3><p>Compare AUC scores across:</p><ul><li><strong>Decision Tree</strong></li><li><strong>Random Forest</strong></li><li><strong>XGBoost</strong></li></ul><p>Choose the model that best generalizes across <strong>train</strong>, <strong>validation</strong>, and <strong>test</strong> sets. Usually, <strong>XGBoost</strong> performs best on tabular data but needs careful tuning to prevent overfitting.</p><h3>🏁 Summary</h3><pre>| Algorithm     | Description              | Strengths        | Weaknesses      |<br>| ------------- | ------------------------ | ---------------- | --------------- |<br>| Decision Tree | Simple if/else rules     | Interpretability | Overfitting     |<br>| Random Forest | Ensemble of trees        | Robust, stable   | Slower training |<br>| XGBoost       | Sequential boosted trees | Best performance | Complex tuning  |</pre><h3>💬 Explore More</h3><ul><li>Try <strong>Extra Trees Classifier</strong> for faster training.</li><li>Use <strong>feature importance</strong> from trees for interpretability.</li><li>Apply to regression tasks with DecisionTreeRegressor or RandomForestRegressor.</li></ul><h3>💡 Final Thoughts</h3><p>Whether you’re serving predictions for a marketing app, recommendation engine, or internal analytics system — this deployment pipeline helps you <strong>go from notebook to production</strong> confidently.</p><p><a href="https://datatalks.club/blog/machine-learning-zoomcamp.html">Machine Learning Zoomcamp</a> is a free 4-month course teaching machine learning engineering. You’ll learn Python ML basics through to production deployment, build real projects, and join a supportive community.</p><p>If you’re starting your journey in machine learning, I’d highly recommend checking out <a href="https://datatalks.club/blog/machine-learning-zoomcamp.html">ML Zoomcamp</a>. Module 1 is an excellent reminder that the best ML projects begin not with code, but with the <em>right questions</em>.</p><p><a href="https://medium.com/@meediax.digital/learning-machine-learning-insights-from-ml-zoomcamp-2025-module-1-bf9364453390">Read my notes on Module 1 here</a>.<br><a href="https://medium.com/@meediax.digital/building-a-car-price-prediction-model-with-linear-regression-my-ml-zoomcamp-2025-module-2-f01892be28b5">Read my notes on Module 2 here.</a><br><a href="https://medium.com/@meediax.digital/predicting-customer-churn-with-logistic-regression-my-ml-zoomcamp-2025-module-3-journey-86541c91e628">Read my notes on Module 3 here</a>.<br><a href="https://medium.com/@meediax.digital/mastering-binary-classification-metrics-a-complete-note-on-ml-model-evaluation-11f16e770ef2">Read my notes on Module 4 here.</a><br><a href="https://medium.com/@meediax.digital/end-to-end-ml-model-deployment-workflow-mlzoomcamp-module-5-notes-1c11205dc96d">Read my notes on Module 5 here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e698f5112c9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ End-to-End ML Model Deployment Workflow — MLZoomcamp Module 5 Notes]]></title>
            <link>https://medium.com/@austin.adeyanju/end-to-end-ml-model-deployment-workflow-mlzoomcamp-module-5-notes-1c11205dc96d?source=rss-b4b36c503c01------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c11205dc96d</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[ml-model-deployment]]></category>
            <dc:creator><![CDATA[Austin Adeyanju]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 16:25:51 GMT</pubDate>
            <atom:updated>2025-10-27T16:25:51.561Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧠 <strong>End-to-End ML Model Deployment Workflow — MLZoomcamp Module 5 Notes</strong></h3><p><strong><em>From training to cloud — a complete guide to taking your machine learning model live.</em></strong></p><blockquote><em>💡 </em>Turn your Jupyter experiments into production-ready APIs that scale effortlessly.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgiNuVIqCy955M4ddVWSVg.png" /><figcaption>End-to-End ML Model Deployment Workflow</figcaption></figure><h3>🚀 Introduction</h3><p>So, you’ve trained a great machine learning model — now what?<br> Model deployment is the bridge between <strong>experimentation</strong> and <strong>real-world application</strong>. Whether you’re predicting churn, detecting fraud, or recommending content, deployment ensures your model is accessible to other systems and users — without retraining or re-running code.</p><p>This note will walk us through the <strong>five key stages of ML model deployment</strong>: <strong>Train → Serve → Isolate → Package → Deploy </strong>using tools like <strong>FastAPI</strong>, <strong>Docker</strong>, and <strong>Fly.io</strong> (with AWS and Pipenv alternatives).</p><h3>⚙️ Step 1: Train and Save Your Model</h3><p>After you’ve trained and validated your model, the next step is to <strong>save</strong> it for reuse — no need to retrain every time you serve predictions.</p><pre>import pickle<br><br>with open(&#39;model.bin&#39;, &#39;wb&#39;) as f_out:<br>    pickle.dump((dict_vectorizer, model), f_out)</pre><p>🔒 <strong>Tip:</strong> Always save your preprocessing steps (like DictVectorizer) along with the model for consistent feature handling during inference.</p><blockquote><em>⚠️ </em>Security Note:<em> Never unpickle files from untrusted sources.</em></blockquote><h3>🌐 Step 2: Serve Your Model with FastAPI (or Flask)</h3><p>Once saved, your model needs an <strong>API endpoint</strong> that other systems can call to get predictions.</p><p>FastAPI makes this fast, modern, and simple — plus it automatically generates interactive docs!</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel<br><br>class Customer(BaseModel):<br>    gender: str<br>    tenure: int<br>    monthlycharges: float<br>    totalcharges: float<br><br>app = FastAPI()<br><br>@app.post(&quot;/predict&quot;)<br>def predict(customer: Customer):<br>    # Load model and predict<br>    return {&quot;churn_probability&quot;: 0.72, &quot;churn&quot;: True}</pre><p>Run locally:</p><pre>uvicorn app:app --reload --port 9696</pre><p>🧭 Visit → <a href="http://localhost:9696/docs"><strong>http://localhost:9696/docs</strong></a><br>You’ll see an interactive Swagger UI where you can test predictions directly!</p><h3>🧩 Step 3: Isolate Dependencies (with Pipenv or UV)</h3><p>Different projects need different library versions.<br>To prevent version conflicts, always use <strong>virtual environments</strong>.</p><h3>🐍 Option 1: Pipenv</h3><pre>pip install pipenv<br>pipenv install fastapi scikit-learn uvicorn<br>pipenv shell</pre><h3>⚡ Option 2: UV (Rust-based, faster alternative)</h3><pre>pip install uv<br>uv init<br>uv add fastapi scikit-learn uvicorn<br>uv run python app.py</pre><blockquote><em>🧱 Each project runs in its own environment, keeping dependencies clean and reproducible.</em></blockquote><h3>📦 Step 4: Package Your App with Docker</h3><p>Docker helps you <strong>encapsulate your application</strong>, dependencies, and environment into a lightweight container that runs anywhere.</p><p><strong>Dockerfile Example:</strong></p><pre>FROM python:3.8-slim<br>WORKDIR /app<br>COPY [&quot;requirements.txt&quot;, &quot;./&quot;]<br>RUN pip install -r requirements.txt<br>COPY [&quot;app.py&quot;, &quot;model.bin&quot;, &quot;./&quot;]<br>EXPOSE 9696<br>ENTRYPOINT [&quot;uvicorn&quot;, &quot;app:app&quot;, &quot;--host=0.0.0.0&quot;, &quot;--port=9696&quot;]</pre><p>Build and run:</p><pre>docker build -t churn-prediction .<br>docker run -p 9696:9696 churn-prediction</pre><blockquote><em>🐳 </em>Docker ensures consistency — your app runs the same locally, on staging, or in production.</blockquote><h3>☁️ Step 5: Deploy to the Cloud</h3><p>Once your container is ready, it’s time to make your model accessible on the internet.</p><h3>🚀 Option 1: Fly.io (Developer-Friendly)</h3><pre>fly launch<br>fly deploy</pre><ul><li>Auto-scales globally</li><li>Free tier for small apps</li><li>Super fast deployments</li></ul><h3>🧱 Option 2: AWS Elastic Beanstalk (Enterprise Grade)</h3><pre>eb init -p docker -r eu-north-1 churn-serving<br>eb create churn-serving-env</pre><ul><li>Scales automatically with traffic</li><li>Supports Docker-based ML APIs</li><li>Integrates with AWS security and load balancing</li></ul><blockquote><em>☁️ Other options: </em><strong><em>Heroku</em></strong><em>, </em><strong><em>Google Cloud Run</em></strong><em>, or </em><strong><em>Render</em></strong><em> — choose based on budget and scalability needs.</em></blockquote><h3>🧭 The Full Workflow at a Glance</h3><p><strong>Train → Serve → Isolate → Package → Deploy</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*r6mHiDimij8cOjUpIs34DA.png" /><figcaption>Full workflow at a glance</figcaption></figure><h3>💡 Final Thoughts</h3><p>Deploying an ML model isn’t just about writing code — it’s about <strong>engineering for reliability, scalability, and automation</strong>.</p><p>By following this workflow, you’ll ensure your models are:<br> ✅ Reproducible<br> ✅ Scalable<br> ✅ Easy to maintain</p><p>Whether you’re serving predictions for a marketing app, recommendation engine, or internal analytics system — this deployment pipeline helps you <strong>go from notebook to production</strong> confidently.</p><p><a href="https://datatalks.club/blog/machine-learning-zoomcamp.html">Machine Learning Zoomcamp</a> is a free 4-month course teaching machine learning engineering. You’ll learn Python ML basics through to production deployment, build real projects, and join a supportive community.</p><p>If you’re starting your journey in machine learning, I’d highly recommend checking out <a href="https://datatalks.club/blog/machine-learning-zoomcamp.html">ML Zoomcamp</a>. Module 1 is an excellent reminder that the best ML projects begin not with code, but with the <em>right questions</em>.</p><p><a href="https://medium.com/@meediax.digital/learning-machine-learning-insights-from-ml-zoomcamp-2025-module-1-bf9364453390">Read my notes on Module 1 here</a>.<br><a href="https://medium.com/@meediax.digital/building-a-car-price-prediction-model-with-linear-regression-my-ml-zoomcamp-2025-module-2-f01892be28b5">Read my notes on Module 2 here.</a><br><a href="https://medium.com/@meediax.digital/predicting-customer-churn-with-logistic-regression-my-ml-zoomcamp-2025-module-3-journey-86541c91e628">Read my notes on Module 3 here</a>.<br><a href="https://medium.com/@meediax.digital/mastering-binary-classification-metrics-a-complete-note-on-ml-model-evaluation-11f16e770ef2">Read my notes on Module 4 here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c11205dc96d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Binary Classification Metrics: A Complete Note on ML Model Evaluation]]></title>
            <link>https://medium.com/@austin.adeyanju/mastering-binary-classification-metrics-a-complete-note-on-ml-model-evaluation-11f16e770ef2?source=rss-b4b36c503c01------2</link>
            <guid isPermaLink="false">https://medium.com/p/11f16e770ef2</guid>
            <category><![CDATA[classification-metrics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[model-evaluation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[binary-classification]]></category>
            <dc:creator><![CDATA[Austin Adeyanju]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 13:55:23 GMT</pubDate>
            <atom:updated>2025-10-17T13:55:23.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgxDSaSRJ_-24J0Fw0qF3g.png" /></figure><p>One of the most critical yet often misunderstood aspects of machine learning is model evaluation. Building a model is only half the battle; understanding whether it actually works well is equally important. This comprehensive note explores the evaluation metrics covered in Week 4 of the <a href="https://datatalks.club/blog/machine-learning-zoomcamp.html">Machine Learning Zoomcamp</a>, using a real-world customer churn prediction dataset from Kaggle.</p><p>By the end of this article, you’ll understand why accuracy alone can be misleading and how to choose the right metrics for your classification problems.</p><h3>The Problem with Accuracy: Why a Single Metric Isn’t Enough</h3><h3>What is Accuracy?</h3><p>Accuracy is the most intuitive metric for classification models. It simply measures the fraction of correct predictions:</p><pre>Accuracy = (Number of Correct Predictions) / (Total Number of Predictions)</pre><p>Sounds straightforward, right? Let’s see why it can be deceptive.</p><h3>The Dummy Model Trap</h3><p>Consider a customer churn prediction scenario where 73% of customers don’t churn and only 27% do. If we build a “dummy model” that simply predicts no one will churn (by setting the decision threshold to 1), we’d achieve 73% accuracy without any real intelligence!</p><p>Now, imagine our carefully crafted logistic regression model achieves 80% accuracy. That’s only a 7% improvement over doing nothing. This reveals the fundamental issue: <strong>accuracy doesn’t work well with imbalanced datasets</strong>.</p><h3>Understanding Class Imbalance</h3><p>Class imbalance occurs when one category significantly outnumbers the other in your dataset. In such cases, a model can achieve high accuracy by simply predicting the majority class most of the time, while completely failing to identify the minority class that might be more important.</p><p>This is why we need more sophisticated metrics.</p><h3>The Confusion Matrix: Breaking Down Model Predictions</h3><p>The confusion matrix is a powerful tool that breaks down all possible outcomes of a binary classifier into four categories:</p><h3>The Four Categories</h3><p><strong>Positive Class</strong> (Prediction: Customer WILL churn)</p><ul><li><strong>True Positive (TP)</strong>: Correctly predicted churn</li><li><strong>False Positive (FP)</strong>: Incorrectly predicted churn (customer stayed)</li></ul><p><strong>Negative Class</strong> (Prediction: Customer WILL NOT churn)</p><ul><li><strong>True Negative (TN)</strong>: Correctly predicted no churn</li><li><strong>False Negative (FN)</strong>: Incorrectly predicted no churn (customer left)</li></ul><h3>Confusion Matrix Structure</h3><pre>Predictions<br>                Negative    Positive<br>Actual Negative    TN          FP<br>       Positive    FN          TP</pre><p>This simple table unlocks a wealth of information about model performance and leads us to more nuanced metrics.</p><h3>Precision and Recall: Understanding Different Types of Errors</h3><h3>Precision: Quality of Positive Predictions</h3><p>Precision answers the question: “Of all the customers we predicted would churn, how many actually did?”</p><pre>Precision = TP / (TP + FP)</pre><p><strong>Mnemonic</strong>: Precision is about <strong>Predictions</strong> — from the predicted positives, how many did we get right?</p><p>High precision means when your model predicts churn, it’s usually correct. This is crucial when false alarms are costly, such as when you’re offering retention incentives to customers you think will leave.</p><h3>Recall: Coverage of Actual Positives</h3><p>Recall (also called Sensitivity or True Positive Rate) answers: “Of all the customers who actually churned, how many did we catch?”</p><pre>Recall = TP / (TP + FN)</pre><p><strong>Mnemonic</strong>: Recall is about <strong>Reality</strong> — from the real positives, how many did we predict right?</p><p>High recall means your model catches most of the churners, even if it makes some false alarms along the way. This matters when missing a positive case is very costly.</p><h3>The Precision-Recall Tradeoff</h3><p>In the churn prediction example, the model achieved 67% precision and 54% recall. These metrics revealed problems that the 80% accuracy masked. The model was missing nearly half of the customers who would actually churn — a significant business problem!</p><p>You can rarely optimize both precision and recall simultaneously. Increasing one typically decreases the other, requiring you to choose based on business priorities.</p><h3>ROC Curves: Evaluating Performance Across All Thresholds</h3><h3>Historical Context</h3><p>ROC (Receiver Operating Characteristic) curves originated during World War II for evaluating radar signal detection. Today, they’re essential for assessing binary classifiers.</p><h3>Understanding FPR and TPR</h3><p><strong>False Positive Rate (FPR)</strong></p><pre>FPR = FP / (TN + FP)</pre><p>The fraction of negatives incorrectly classified as positive. We want to minimize this.</p><p><strong>True Positive Rate (TPR)</strong> — Same as Recall</p><pre>TPR = TP / (TP + FN)</pre><p>The fraction of positives correctly identified. We want to maximize this.</p><h3>Why ROC Curves Matter</h3><p>Most classifiers output probabilities, and we convert these to predictions using a threshold (commonly 0.5). But why 0.5? ROC curves show model performance across all possible thresholds, helping you:</p><ol><li>Understand the tradeoff between TPR and FPR</li><li>Compare your model against random and ideal baselines</li><li>Choose the optimal threshold for your specific use case</li></ol><h3>Plotting ROC Curves</h3><p>You can visualize ROC curves in two ways:</p><ul><li>FPR and TPR vs. thresholds</li><li>TPR vs. FPR (more common)</li></ul><p>A random model produces a diagonal line from (0,0) to (1,1). An ideal model hugs the top-left corner. Your model should fall somewhere in between, ideally closer to the ideal model.</p><h3>AUC: Summarizing ROC Performance in One Number</h3><h3>What is AUC?</h3><p>Area Under the ROC Curve (AUC or AUROC) condenses the entire ROC curve into a single metric between 0 and 1.</p><ul><li><strong>AUC = 0.5</strong>: Random model (no better than chance)</li><li><strong>AUC = 1.0</strong>: Perfect model</li><li><strong>AUC = 0.8–0.9</strong>: Generally considered good</li><li><strong>AUC &lt; 0.7</strong>: Often needs improvement</li></ul><h3>Probabilistic Interpretation</h3><p>AUC can be interpreted as the probability that your model ranks a randomly chosen positive example higher than a randomly chosen negative example. This makes it a robust metric even with class imbalance.</p><h3>Implementation in Python</h3><pre>from sklearn.metrics import roc_auc_score, roc_curve, auc<br><br># Calculate ROC curve<br>fpr, tpr, thresholds = roc_curve(y_true, y_pred_proba)<br><br># Calculate AUC<br>auc_score = roc_auc_score(y_true, y_pred_proba)<br><br># or<br>auc_score = auc(fpr, tpr)</pre><h3>Cross-Validation: Getting Reliable Performance Estimates</h3><h3>The Problem with Single Train-Test Splits</h3><p>When you split your data once into training and test sets, you get a single performance estimate. But what if that particular split was lucky or unlucky? How confident are you in that number?</p><h3>K-Fold Cross-Validation Explained</h3><p>Cross-validation provides a more robust performance estimate by:</p><ol><li>Dividing the training data into k partitions (folds)</li><li>Training the model k times, each time using k-1 folds for training and 1 fold for validation</li><li>Calculating the average performance and standard deviation across all folds</li></ol><h3>When to Use Cross-Validation</h3><p><strong>Use cross-validation when:</strong></p><ul><li>Your dataset is small to moderate in size</li><li>You need to understand performance variability</li><li>You’re tuning hyperparameters</li><li>You want a more reliable performance estimate</li></ul><p><strong>Use simple train-test split when:</strong></p><ul><li>Your dataset is very large</li><li>Training is computationally expensive</li><li>You have a separate, large validation set</li></ul><h3>Implementation in Python</h3><pre>from sklearn.model_selection import KFold<br>from tqdm import tqdm<br><br>kfold = KFold(n_splits=5, shuffle=True, random_state=1)<br><br>scores = []<br>for train_idx, val_idx in tqdm(kfold.split(X)):<br>    X_train, X_val = X[train_idx], X[val_idx]<br>    y_train, y_val = y[train_idx], y[val_idx]<br>    <br>    # Train and evaluate model<br>    model.fit(X_train, y_train)<br>    score = model.score(X_val, y_val)<br>    scores.append(score)<br><br>print(f&quot;Average: {np.mean(scores):.3f} ± {np.std(scores):.3f}&quot;)</pre><p>The standard deviation tells you how stable your model is across different data subsets.</p><h3>Choosing the Right Metric for Your Problem</h3><p>Different problems require different metrics. Here’s a decision framework:</p><h3>Use Accuracy When:</h3><ul><li>Classes are balanced</li><li>All errors are equally costly</li><li>You need a simple, interpretable metric</li></ul><h3>Use Precision When:</h3><ul><li>False positives are costly</li><li>Example: Spam detection (don’t want legitimate emails marked as spam)</li></ul><h3>Use Recall When:</h3><ul><li>False negatives are costly</li><li>Example: Cancer detection (can’t afford to miss positive cases)</li></ul><h3>Use F1 Score When:</h3><ul><li>You need a balance between precision and recall</li><li>Formula: F1 = 2 × (Precision × Recall) / (Precision + Recall)</li></ul><h3>Use AUC When:</h3><ul><li>You have class imbalance</li><li>You want a threshold-independent metric</li><li>You need to compare multiple models</li></ul><h3>Practical Tips and Best Practices</h3><h3>1. Always Start with a Baseline</h3><p>Create a simple dummy model (like always predicting the majority class) to establish a baseline. Your real model should significantly outperform it.</p><h3>2. Look at Multiple Metrics</h3><p>Never rely on a single metric. Examine accuracy, precision, recall, and AUC together to get a complete picture.</p><h3>3. Visualize Your Results</h3><p>Plot confusion matrices, ROC curves, and precision-recall curves. Visual patterns often reveal insights that numbers alone don’t.</p><h3>4. Consider Business Context</h3><p>The “best” metric depends on your business problem. Work with stakeholders to understand the cost of different types of errors.</p><h3>5. Use Cross-Validation for Hyperparameter Tuning</h3><p>When selecting model parameters, use cross-validation to avoid overfitting to a single validation set.</p><h3>Key Python Libraries and Methods</h3><p>Here’s a quick reference for the essential tools covered:</p><pre># NumPy utilities<br>np.linspace(0, 1, 50)  # Generate evenly spaced thresholds<br>np.repeat([0, 1], [100, 50])  # Create arrays with repeated values<br><br># Scikit-learn metrics<br>from sklearn.metrics import (<br>    accuracy_score,<br>    confusion_matrix,<br>    precision_score,<br>    recall_score,<br>    roc_curve,<br>    roc_auc_score,<br>    auc<br>)<br><br># Cross-validation<br>from sklearn.model_selection import KFold<br><br># Progress tracking<br>from tqdm import tqdm<br><br># Counting utilities<br>from collections import Counter</pre><h3>Summary: Key Takeaways</h3><ol><li><strong>Accuracy is misleading</strong> with imbalanced datasets. Always check class distribution first.</li><li><strong>Confusion matrices</strong> break down model performance into four meaningful categories, enabling deeper analysis.</li><li><strong>Precision and recall</strong> address different business concerns. Choose based on which type of error is more costly.</li><li><strong>ROC curves and AUC</strong> provide threshold-independent evaluation and work well with imbalanced data.</li><li><strong>Cross-validation</strong> gives more reliable performance estimates and helps with hyperparameter tuning.</li><li><strong>Always use multiple metrics</strong> to get a complete picture of model performance.</li><li><strong>Business context matters</strong>. The best metric depends on the specific costs and benefits in your application.</li></ol><h3>Further Exploration</h3><p>To deepen your understanding, try these exercises:</p><ol><li>Calculate precision and recall for a dummy classifier that always predicts “FALSE”</li><li>Plot precision-recall curves (similar to ROC curves) at different thresholds</li><li>Calculate the area under the precision-recall curve</li><li>Apply these metrics to other classification datasets</li><li>Experiment with different decision thresholds to see how metrics change</li></ol><h3>Resources</h3><ul><li><a href="https://datatalks.club/blog/machine-learning-zoomcamp.html">Machine Learning Zoomcamp</a></li><li><a href="https://www.kaggle.com/blastchar/telco-customer-churn">Telco Customer Churn Dataset on Kaggle</a></li><li><a href="https://github.com/DataTalksClub/machine-learning-zoomcamp/blob/master/04-evaluation/notebook.ipynb">Complete Course Notebooks</a></li><li><a href="https://anandology.com/python-practice-book/iterators.html">Python Iterators and Generators</a></li></ul><h3>Conclusion</h3><p>Evaluating machine learning models properly is crucial for building systems that work in production. While accuracy might seem sufficient at first glance, this module demonstrates why understanding precision, recall, ROC curves, and cross-validation is essential for any data scientist or machine learning engineer.</p><p>The metrics you choose directly impact business decisions, so invest time in understanding their nuances. Your stakeholders — and your models — will thank you.</p><p><strong>What evaluation challenges have you faced in your projects? Share your experiences in the comments below!</strong></p><p><em>This article is based on Module 4 of the Machine Learning Zoomcamp course thanks to @AlexeyGrigorev. If you’re interested in learning more about practical machine learning, consider joining the course at DataTalks.Club.</em></p><p><a href="https://medium.com/@meediax.digital/learning-machine-learning-insights-from-ml-zoomcamp-2025-module-1-bf9364453390">Read my notes on Module 1 here</a>.<br><a href="https://medium.com/@meediax.digital/building-a-car-price-prediction-model-with-linear-regression-my-ml-zoomcamp-2025-module-2-f01892be28b5">Read my notes on Module 2 here.</a><br><a href="https://medium.com/@meediax.digital/predicting-customer-churn-with-logistic-regression-my-ml-zoomcamp-2025-module-3-journey-86541c91e628">Read my notes on Module 3 here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11f16e770ef2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>