<?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 Blessing Orazulume on Medium]]></title>
        <description><![CDATA[Stories by Blessing Orazulume on Medium]]></description>
        <link>https://medium.com/@blessingoraz?source=rss-c1cc23102f91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s7fSlWtBgYHdIrcD17rLLA.jpeg</url>
            <title>Stories by Blessing Orazulume on Medium</title>
            <link>https://medium.com/@blessingoraz?source=rss-c1cc23102f91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:54:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@blessingoraz/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[How I Turned Raw Audio into CNN-Ready Features for Baby Cry Classification]]></title>
            <link>https://medium.com/training-models-raising-kids/how-i-turned-raw-audio-into-cnn-ready-features-for-baby-cry-classification-cf0190a72e0d?source=rss-c1cc23102f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf0190a72e0d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlzoomcamp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Blessing Orazulume]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 05:38:42 GMT</pubDate>
            <atom:updated>2026-01-22T05:38:42.946Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jtspMJLCOlXc73r4VKm_Q.jpeg" /><figcaption>Image from grok</figcaption></figure><p>When I started working on a baby cry classification project, the model architecture wasn’t my biggest challenge.</p><p><strong>Audio preprocessing was.</strong></p><p>Unlike images or tabular data, raw audio isn’t something you can feed directly into a convolutional neural network (CNN). You have to make careful choices about how to represent sound in a way that preserves meaning <em>and</em> works well with deep learning models.</p><p>In this article, I’ll walk through:</p><ul><li>The challenges of using audio in machine learning,</li><li>Why <strong>mel-spectrograms</strong> are a great fit for CNNs,</li><li>The key preprocessing decisions I made (sampling rate, clip length, resizing),</li><li>And lessons I learned while moving from training to deployment.</li></ul><h3>The Challenge of Audio in Machine Learning</h3><p>At its core, audio is a <strong>1-dimensional time-series signal</strong>.</p><p>A raw waveform looks like this:</p><blockquote><strong>amplitude vs time</strong></blockquote><p>While this works well for signal processing, it’s not ideal for CNNs, which excel at learning <strong>local spatial patterns</strong> (edges, textures, shapes).</p><p>Some challenges with raw audio:</p><ul><li>Variable length recordings</li><li>Sensitivity to noise</li><li>High sampling rates → huge input sizes</li><li>Harder for CNNs to learn meaningful temporal structure directly</li></ul><p>So the question becomes:</p><p>“<strong><em>How do we convert sound into something that looks more like an image, without losing important information?</em></strong>”</p><h3>Why Spectrograms (and Not Raw Audio)?</h3><p>A <strong>spectrogram</strong> is a visual representation of sound that shows:</p><ul><li>time on the x-axis,</li><li>frequency on the y-axis,</li><li>intensity (energy) as color.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqJ84DX7D16z8d_LdleH1Q.png" /><figcaption>A mel-spectrogram grid of each of the baby cry class</figcaption></figure><p>Instead of asking <em>“what is the amplitude at this time?”</em>, we ask:</p><p><em>Which frequencies are present at this moment in time?</em></p><p>This representation makes patterns in sound much more visible and learnable for CNNs.</p><h3>Why Mel-Spectrograms Work So Well for CNNs</h3><p>A <strong>mel-spectrogram</strong> is a spectrogram mapped onto the <strong>mel scale</strong>, which approximates how humans perceive pitch.</p><p>Key reasons I chose mel-spectrograms:</p><h4>1. Human-centric frequency scaling</h4><p>Humans perceive low-frequency changes more distinctly than high-frequency ones. The mel scale compresses high frequencies and expands low ones, making patterns more meaningful.</p><h4>2. Compact representation</h4><p>Instead of thousands of frequency bins, you can work with a fixed number (e.g. 128 mel bands).</p><h4>3. Image-like structure</h4><p>Mel-spectrograms are 2D arrays which are perfect for CNNs.</p><p>In short: <strong>Mel-spectrograms turn audio into images of sound.</strong></p><h3>My Preprocessing Pipeline (Step by Step)</h3><p>Here’s the exact pipeline I used to turn raw audio into CNN-ready features.</p><h4>1. Resampling to 8 kHz</h4><p>Audio datasets often contain recordings with different sampling rates (44.1 kHz, 16 kHz, etc.). I resampled everything to <strong>8 kHz</strong>:</p><p><strong>Why 8 kHz?</strong></p><ul><li>Baby cries are dominated by lower frequencies</li><li>Reduces computation</li><li>Still preserves relevant information</li></ul><p>This is a common tradeoff between fidelity and efficiency.</p><h3>2. Fixed Clip Length: 7 Seconds</h3><p>CNNs require fixed-size inputs.</p><p>I standardized all clips to <strong>7 seconds</strong>:</p><ul><li>Longer clips were truncated</li><li>Shorter clips were zero-padded</li></ul><p><strong>Why 7 seconds?</strong></p><ul><li>It is long enough to capture a full cry pattern and short enough for fast inference.</li><li>It is also consistent with the dataset distribution</li></ul><pre>import numpy as np<br>import librosa<br><br>TARGET_SR = 8000<br>CLIP_SECONDS = 7.0<br>FIXED_LEN = int(TARGET_SR * CLIP_SECONDS)<br><br>N_MELS = 128<br>N_FFT = 1024<br>HOP_LENGTH = 256<br><br>def load_and_fix_length(path, target_sr=TARGET_SR, fixed_len=FIXED_LEN):<br>    # load and resample if needed<br>    y, sr = librosa.load(path, sr=target_sr, mono=True)<br>    <br>    # trim or pad to fixed length<br>    if len(y) &gt; fixed_len:<br>        y = y[:fixed_len]  # simple: take first 7 seconds<br>    elif len(y) &lt; fixed_len:<br>        y = np.pad(y, (0, fixed_len - len(y)))<br>    return y</pre><h4>3. Mel-Spectrogram Extraction</h4><p>From each audio clip, I computed a mel-spectrogram using:</p><h3>3. Mel-Spectrogram Extraction</h3><p>From each audio clip, I computed a mel-spectrogram using:</p><ul><li>n_mels = 128</li><li>n_fft = 1024</li><li>hop_length = 256</li></ul><p>This produces a time-frequency representation that captures both:</p><ul><li><strong>temporal patterns</strong> (how cries evolve),</li><li><strong>spectral patterns</strong> (frequency structure).</li></ul><p>This produces a time-frequency representation that captures both:</p><ul><li><strong>temporal patterns</strong> (how cries evolve),</li><li><strong>spectral patterns</strong> (frequency structure).</li></ul><h4>4. Resizing to 224 × 224</h4><p>My CNN backbone was <strong>ResNet18</strong>, which expects image-like inputs.</p><p>So I resized each mel-spectrogram to:</p><pre>(224 x 224)</pre><p>Final tensor shape:</p><pre>(1, 224, 224)</pre><p>Since ResNet expects 3 channels, I simply repeated the single channel:</p><pre>(3, 224, 224)</pre><p>This is a common, effective trick.</p><h3>Training vs Inference Preprocessing</h3><p>One subtle but important lesson:</p><blockquote><strong>Training preprocessing and inference preprocessing don’t need to use the same libraries but they must produce the same representation.</strong></blockquote><h3>During training</h3><ul><li>I used <strong>librosa</strong> for convenience and experimentation.</li><li>It’s excellent for research and feature extraction.</li></ul><h3>During deployment</h3><ul><li>I moved away from librosa due to <strong>serverless constraints</strong> (numba, JIT, Lambda issues).</li><li>I reimplemented the same logic using lighter dependencies (NumPy + SciPy).</li></ul><p>As long as:</p><ul><li>sampling rate,</li><li>mel filter parameters,</li><li>normalization,</li><li>resizing</li></ul><p>are consistent, the model behaves correctly.</p><h3>Lessons Learned</h3><h4>1. Audio preprocessing matters as much as the model</h4><p>Small preprocessing changes can significantly affect performance.</p><h4>2. Mel-spectrograms are a great bridge to CNNs</h4><p>They let you reuse powerful image models for audio tasks.</p><h4>3. Design for deployment early</h4><p>Some libraries are great for training but painful in production.</p><h4>4. Consistency beats perfection</h4><p>Exact numerical equivalence isn’t required — functional equivalence is.</p><h3>Final Thoughts</h3><p>Turning raw audio into CNN-ready features is less about fancy math and more about <strong>practical engineering decisions</strong>.</p><p>Once you understand:</p><ul><li>How sound becomes frequency patterns,</li><li>Why Mel-spectrograms work,</li><li>And how to standardize inputs,</li></ul><p>audio ML becomes far more approachable.</p><p>If you’re curious, the full project, which includes training, ONNX export, and AWS Lambda deployment, is available on my <a href="https://github.com/blessingoraz/baby-cry-classifier"><strong>GitHub Repository</strong></a></p><p>Thanks for reading!</p><p><em>This publication is the beginning of something exciting for my career and for me personally. Let’s see where this journey takes us.</em></p><p><em>And also thank you so much </em><a href="https://www.linkedin.com/in/agrigorev/"><em>Alexey Grigorev</em></a><em> and the datatalksclub team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf0190a72e0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/training-models-raising-kids/how-i-turned-raw-audio-into-cnn-ready-features-for-baby-cry-classification-cf0190a72e0d">How I Turned Raw Audio into CNN-Ready Features for Baby Cry Classification</a> was originally published in <a href="https://medium.com/training-models-raising-kids">Training Models, Raising Kids</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Baby Cry Classifier — My ML Zoomcamp Capstone Project (Week 1: Getting Started)]]></title>
            <link>https://medium.com/training-models-raising-kids/baby-cry-classifier-my-ml-zoomcamp-capstone-project-week-1-getting-started-6b8bc62e32c0?source=rss-c1cc23102f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b8bc62e32c0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[mlzoomcamp]]></category>
            <dc:creator><![CDATA[Blessing Orazulume]]></dc:creator>
            <pubDate>Fri, 12 Dec 2025 10:58:12 GMT</pubDate>
            <atom:updated>2025-12-12T10:59:26.862Z</atom:updated>
            <content:encoded><![CDATA[<h3>Baby Cry Classifier — My ML Zoomcamp Capstone Project (Week 1: Getting Started)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-BBRFqsWmtigqSQ3" /><figcaption>Photo by <a href="https://unsplash.com/@carlosmart626?utm_source=medium&amp;utm_medium=referral">Carlos Martinez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the most stressful things about building a portfolio project is simply deciding <strong>what project to build</strong>. If you’re anything like me, you’ve probably spent hours scrolling through datasets on Kaggle thinking:</p><blockquote><em>“This one looks cool…<br> But will I actually finish it?”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Q1liLT1xj3V-zPKXaQaF9g.jpeg" /><figcaption>I just want one project that won’t break my brain.</figcaption></figure><p>For me, the best projects always come from something I genuinely care about or something happening in my real life. And right now?</p><p>I’ve been on parental leave for almost <strong>11 months</strong>, and the cries of my baby are <strong>always ringing in my ears</strong>. Sometimes I feel like I can recognize the cries better than Google Translate 😅.</p><p>So when I stumbled on a <a href="https://www.kaggle.com/datasets/mennaahmed23/baby-cry-dataset/data"><strong>Baby Cry Dataset</strong> on Kaggle</a>, I instantly knew <em>“Yes. This is the one.”</em></p><p>If you’re ever stuck picking a project, here’s my top advice:</p><blockquote>Pick something that’s close to your life. If it motivates you, you’ll finish it.</blockquote><h3>Why Baby Cry Classification?</h3><p>In <a href="https://medium.com/training-models-raising-kids/deep-learning-part-2-316a4dd3c729">Module 8 of ML Zoomcamp</a>, we explored <strong>neural networks</strong> and built an image classifier using a CNN. For my capstone, I wanted to apply the same idea—but on <strong>audio</strong> rather than images.</p><p>The dataset includes eight types of baby cries:</p><ul><li><strong>belly_pain</strong></li><li><strong>discomfort</strong></li><li><strong>lonely</strong></li><li><strong>burping</strong></li><li><strong>tired</strong></li><li><strong>cold_hot</strong></li><li><strong>scared</strong></li><li><strong>hungry</strong></li></ul><p>And guess what?</p><p>The class distribution is highly imbalanced. (hungry has hundreds of samples, cold/hot has only a few)</p><p>This means I’ll need to pay attention to how the model handles the underrepresented classes.</p><h3>A Simple Look at the Data (EDA)</h3><p>Audio EDA is not as visually exciting as image EDA, but there <em>are</em> a few important things to check before training your model.</p><p>Here’s what I looked at:</p><h3>1. Class distribution</h3><p>A simple bar chart showed me immediately that the dataset is skewed — which means I need:</p><ul><li>Data augmentation</li><li>Class weights</li><li>Possibly downsampling or merging similar classes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*viU3wXsXxT8Hkq_0glqqCw.png" /></figure><h3>2. Sampling rate</h3><p>Audio files often have different sampling rates (e.g., 16kHz, 44.1kHz).<br> In a CNN model, all components must be consistent.</p><p>I printed the sampling rate for a few files to check what I’m working with.</p><h3>3. Duration of each file</h3><p>Some files were short, some were long. For CNNs, we require all audio to be converted into <strong>equal-length mel spectrograms</strong>.</p><p>That means:</p><ul><li><strong>Trim</strong> long audio</li><li><strong>Pad</strong> short audio with silence</li><li><strong>Resample</strong> to one sampling rate</li></ul><p>This ensures every sample becomes the same size “image.”</p><h3>4. Mel Spectrograms</h3><p>Audio can’t be fed directly into a CNN. We convert it into an image-like representation: a <strong>mel spectrogram</strong>.</p><p>It looks like a heatmap of sound frequency over time. Different cries produce distinct spectrogram patterns, which is what the CNN learns.</p><h3>How CNN Works With Audio</h3><p>This is the fun part:</p><ol><li>Convert audio → mel spectrogram</li><li>Treat spectrogram like an image</li><li>Feed into a CNN</li><li>CNN learns patterns (e.g., babies cry differently when hungry vs scared)</li></ol><p>If you’re wondering:</p><p>“Do I need an LSTM? Or a transformer? Or a complicated model?”</p><p>No. A <strong>simple CNN</strong> performs well on small datasets.</p><h3>Tutorials I Watched/Read to Understand Audio + CNNs</h3><p>These were extremely helpful and beginner-friendly:</p><ul><li><strong>Basics of Audio Processing</strong><br> <a href="https://www.kaggle.com/code/animeshprakash/audio-processing-basics-tutorial">https://www.kaggle.com/code/animeshprakash/audio-processing-basics-tutorial</a></li><li><strong>Mel Spectrogram Explained Simply</strong><br> <a href="https://towardsdatascience.com/mel-spectrograms-explained-6f3e98d0f4d3">https://towardsdatascience.com/mel-spectrograms-explained-6f3e98d0f4d3</a></li><li><strong>Librosa audio loading</strong><br> <a href="https://librosa.org/doc/latest/generated/librosa.load.html">https://librosa.org/doc/latest/generated/librosa.load.html</a></li><li><strong>Intro to CNN (TensorFlow)</strong><br> <a href="https://www.tensorflow.org/tutorials/images/cnn">https://www.tensorflow.org/tutorials/images/cnn</a></li><li><strong>Audio Augmentation Tools</strong><br> <a href="https://audiomentations.readthedocs.io/">https://audiomentations.readthedocs.io/</a></li></ul><p>If you are new to audio ML, these are sufficient to get started.</p><h3>Why This Project Means Something to Me</h3><p>This project is special because it connects two parts of my life:</p><ul><li>My journey as a <strong>mom of two</strong></li><li>My journey into <strong>machine learning and applied AI engineering</strong></li></ul><p>I love the idea of building something that feels personal and useful — even if it’s not perfect. For me, the motivation comes naturally because it solves a problem I experience every day.</p><h3>Follow the Project on GitHub</h3><p>You can follow along with my code, notebooks, and deployment steps:</p><p>👉 <a href="https://github.com/blessingoraz/baby-cry-classifier"><strong>GitHub Repository Link</strong></a></p><p>If you find helpful tutorials, share them with me — I’m learning too!</p><p><em>This publication is the beginning of something exciting for my career and for me personally. Let’s see where this journey takes us.</em></p><p><em>And also thank you so much </em><a href="https://www.linkedin.com/in/agrigorev/"><em>Alexey Grigorev</em></a><em> and the datatalksclub team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b8bc62e32c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/training-models-raising-kids/baby-cry-classifier-my-ml-zoomcamp-capstone-project-week-1-getting-started-6b8bc62e32c0">Baby Cry Classifier — My ML Zoomcamp Capstone Project (Week 1: Getting Started)</a> was originally published in <a href="https://medium.com/training-models-raising-kids">Training Models, Raising Kids</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Machine Learning Models the Serverless Way: A Beginner-Friendly Introduction to AWS…]]></title>
            <link>https://medium.com/training-models-raising-kids/deploying-machine-learning-models-the-serverless-way-a-beginner-friendly-introduction-to-aws-eafd231c9491?source=rss-c1cc23102f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/eafd231c9491</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[mlzoomcamp]]></category>
            <dc:creator><![CDATA[Blessing Orazulume]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 00:57:20 GMT</pubDate>
            <atom:updated>2025-12-10T00:57:20.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5CKBCPIRMpop7DzgKupRSw.png" /></figure><h3>Deploying Machine Learning Models the Serverless Way: A Beginner-Friendly Introduction to AWS Lambda</h3><p>In this lesson from Module 9, we explored how serverless architecture simplifies ML deployment, why it matters, and how AWS Lambda allows you to run your model without managing servers. If you’re building machine learning systems and want a simple, cost-effective way to deploy them, this guide is for you.</p><h3>Lesson 1: Introduction to Serverless</h3><p>Serverless isn’t <em>no servers</em> — servers still exist, but <strong>you don’t manage them</strong>. You write your code, upload it, and the cloud provider handles everything else:</p><ul><li>Scaling</li><li>Infrastructure</li><li>Availability</li><li>Security patches</li><li>Load balancing</li></ul><p>For machine learning practitioners, this is huge. Instead of worrying about DevOps, you focus on the model.</p><h3>Why Serverless for ML Deployment?</h3><p>Think of the typical ML workflow:</p><ol><li>Train a model</li><li>Export it (e.g., ONNX, TFLite, SavedModel)</li><li>Deploy it so real users or applications can make predictions</li></ol><p>Traditionally, deployment meant:</p><ul><li>Renting a server</li><li>Installing dependencies</li><li>Keeping it running 24/7</li><li>Paying for compute even when idle</li><li>Monitoring CPU usage, memory, and crashes</li></ul><p>With <strong>serverless</strong>, you skip all of that.</p><h4>Use Case: Deploying a CNN Classification Model</h4><p>In this module, the goal was to deploy a <strong>Convolutional Neural Network (CNN)</strong> used for image classification.</p><p>To accomplish this:</p><ul><li>We converted our model into a lightweight format, i.e <strong>TensorFlow Lite</strong> or <strong>ONNX</strong>.</li><li>We wrapped the preprocessing + prediction in a Lambda function.</li><li>We deployed it serverlessly using AWS Lambda + API Gateway.</li></ul><p>Because serverless charges <strong>per invocation</strong>, it’s highly cost-effective for ML workloads that don’t run continuously.</p><h3>Lesson 2: Understanding AWS Lambda</h3><p>AWS Lambda is the star of serverless deployment.</p><h4>What is AWS Lambda?</h4><p>AWS Lambda is a compute service that lets you:</p><ul><li>Run code without provisioning servers</li><li>Pay only when your code runs</li><li>Automatically scale depending on traffic</li><li>Deploy in seconds</li></ul><p>This makes it ideal for ML inference workloads.</p><p>When deploying a CNN, the inference step typically involves:</p><ol><li><strong>Receiving an image</strong></li><li><strong>Preprocessing (resize, normalize, reshape)</strong></li><li><strong>Running the model</strong></li><li><strong>Returning prediction scores</strong></li></ol><p>AWS Lambda handles these steps beautifully — especially when packaged in a Docker container.</p><h3>Deploying a CNN Model Using AWS Lambda (High-Level Overview)</h3><p>Here’s what deploying a model looks like when using Lambda:</p><h4>Step 1 — Export Your Model</h4><p>Your CNN model is exported in a deployable format such as:</p><ul><li>TensorFlow Lite (.tflite)</li><li>ONNX (.onnx)</li></ul><p>These formats are lightweight and fast for inference.</p><p>Example:</p><pre>import onnxruntime as ort<br><br>session = ort.InferenceSession(&quot;model.onnx&quot;)</pre><h4>Step 2 — Package Your Code in a Lambda Function</h4><p>Your lambda_function.py includes:</p><ul><li>image downloading</li><li>image preprocessing</li><li>calling the model</li><li>returning predictions</li></ul><p>A minimal template:</p><pre>def lambda_handler(event, context):<br>    url = event.get(&quot;url&quot;)<br>    image = download_image(url)<br>    X = preprocess(image)<br>    score = predict(X)<br>    return {&quot;score&quot;: score}</pre><h4>Step 3 — Deploy Using a Docker Image (Best for ML Models)</h4><p>AWS Lambda allows deployment via Docker images up to <strong>10 GB</strong>, which is perfect for models with heavy dependencies like:</p><ul><li>NumPy</li><li>SciPy</li><li>ONNX Runtime</li><li>Pillow</li></ul><p>Sample Dockerfile:</p><pre>FROM public.ecr.aws/lambda/python:3.9<br><br>COPY model.onnx .<br>COPY lambda_function.py .<br><br>RUN pip install onnxruntime pillow numpy<br><br>CMD [&quot;lambda_function.lambda_handler&quot;]</pre><p>Build and push to ECR:</p><pre>docker build -t hairstyle-lambda .<br>docker tag hairstyle-lambda:latest &lt;ACCOUNT_ID&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/hairstyle-lambda:v1<br>docker push &lt;ECR_URI&gt;</pre><h4>Step 4 — Create a Lambda Function Using the Container Image</h4><p>In AWS Console:</p><ul><li>Choose <strong>Create function</strong></li><li>Select <strong>Container image</strong></li><li>Choose your ECR image</li><li>Set memory (e.g., 1024 MB)</li><li>Set timeout (e.g., 30 seconds)</li></ul><h4>Step 5 — Expose Your Model Over the Internet (API Gateway)</h4><p>To allow clients to send images to your model over HTTP:</p><ul><li>Add an API Gateway trigger</li><li>Choose POST method</li><li>Set it to forward requests to Lambda</li></ul><p>Call the model:</p><pre>curl -X POST \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;url&quot;: &quot;IMAGE_URL&quot;}&#39; \<br>  https://your-api-id.execute-api.region.amazonaws.com/default/predict</pre><p>You get back:</p><pre>{ &quot;score&quot;: 0.093 }</pre><p>Your model is now live!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*6ZDOQ2-A4seOyRyx.gif" /></figure><h3>Key Takeaways</h3><ul><li>Serverless computing removes the operational burden of managing servers.</li><li>AWS Lambda is ideal for deploying ML inference workloads.</li><li>You can package complex ML models using Docker and deploy them as Lambda container images.</li><li>Lambda + API Gateway enables your model to be called over the internet like a real API.</li><li>TensorFlow Lite and ONNX models are lightweight and suitable for serverless deployments.</li><li>You pay only for actual usage — making serverless extremely cost-effective.</li><li>Serverless deployment is a practical skill for modern applied AI engineers.</li></ul><p><em>This publication is the beginning of something exciting for my career and for me personally. Let’s see where this journey takes us.</em></p><p><em>And also thank you so much </em><a href="https://www.linkedin.com/in/agrigorev/"><em>Alexey Grigorev</em></a><em> and the datatalksclub team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eafd231c9491" width="1" height="1" alt=""><hr><p><a href="https://medium.com/training-models-raising-kids/deploying-machine-learning-models-the-serverless-way-a-beginner-friendly-introduction-to-aws-eafd231c9491">Deploying Machine Learning Models the Serverless Way: A Beginner-Friendly Introduction to AWS…</a> was originally published in <a href="https://medium.com/training-models-raising-kids">Training Models, Raising Kids</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning (Part 3)]]></title>
            <link>https://medium.com/training-models-raising-kids/deep-learning-part-3-b1bf9061b213?source=rss-c1cc23102f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1bf9061b213</guid>
            <category><![CDATA[mlzoomcamp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Blessing Orazulume]]></dc:creator>
            <pubDate>Thu, 04 Dec 2025 10:29:32 GMT</pubDate>
            <atom:updated>2025-12-04T10:29:32.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8yvSvty6zJSk_RaFYm965Q.png" /></figure><p>As I continue my deep learning journey, I’ve learned that building a neural network is only half the story. The real magic happens when you:</p><ul><li>Train it efficiently</li><li>Prevent it from overfitting</li><li>Save the best version</li><li>Use data wisely</li><li>Scale to bigger and better models</li></ul><p>This post covers Lessons 7 through 12 — the concepts that make deep learning work in the real world.</p><h3>Lesson 7: Checkpointing(Saving Your Model the Smart Way)</h3><p>Training deep learning models can take hours, even days. What happens if:</p><ul><li>Your laptop shuts down?</li><li>Your runtime resets in Google Colab?</li><li>Training diverges after epoch 15?</li><li>Epoch 8 had the best performance, but you don’t know it?</li></ul><p>This is where checkpointing comes in.</p><h4>What is Checkpointing?</h4><p>Checkpointing means saving your model weights after every epoch, or only when training improves, so you never lose progress.</p><h4>Why it’s essential</h4><p>It prevents losing hours of training and lets you restore the model to its best version. It also helps avoid overfitting by keeping the best validation accuracy model.</p><h4>With Keras</h4><pre>from tensorflow.keras.callbacks import ModelCheckpoint<br><br>checkpoint = ModelCheckpoint(<br>    filepath=&quot;best_model.h5&quot;,<br>    monitor=&quot;val_loss&quot;,<br>    save_best_only=True,<br>    mode=&quot;min&quot;<br>)<br><br>model.fit(train_data, validation_data=val_data, callbacks=[checkpoint])</pre><h4>Callbacks = automated training helpers</h4><p>Checkpointing is performed using <strong>callbacks</strong>, mini-programs that are triggered during training.</p><p>Other callbacks:</p><ul><li>ReduceLROnPlateau</li><li>EarlyStopping</li><li>TensorBoard</li></ul><h3>Lesson 8: Adding More Layers to a Neural Network</h3><p>Adding more layers = making the network <strong>deeper</strong>.<br>Deeper networks can learn more complex patterns.</p><h3>Example:</h3><p><strong>Shallow network:</strong></p><pre>Input → Dense(32) → Output</pre><p><strong>Deeper network:</strong></p><pre>Input → Dense(32) → Dense(64) → Dense(128) → Output</pre><h4>Why add more layers?</h4><ul><li>More layers = more representational power</li><li>Can learn higher-level abstractions</li></ul><p><strong>Example:</strong><br>=&gt; First layer might learn edges<br>=&gt; Second layer might learn stripes<br>=&gt; Third layer might learn sleeves<br>=&gt; Fourth layer learns full shirts</p><h3>But deeper ≠ always better</h3><p>More layers also mean:</p><ul><li>harder to train</li><li>risk of overfitting</li><li>longer training time</li></ul><h3>A safe beginner-friendly architecture:</h3><pre>model = Sequential([<br>    Dense(128, activation=&#39;relu&#39;),<br>    Dense(64, activation=&#39;relu&#39;),<br>    Dense(32, activation=&#39;relu&#39;),<br>    Dense(10, activation=&#39;softmax&#39;)<br>])</pre><h3>Lesson 9: Regularization &amp; Dropout</h3><p>Overfitting is when your model memorizes training data but performs poorly on unseen data.</p><p>Dropout is one of the simplest and most effective ways to fight overfitting.</p><h4>What is Dropout?</h4><p>During training, dropout <strong>turns off random neurons</strong>.</p><p>Example:</p><p>If dropout rate = 0.5<br> ➡️ Half the neurons get disabled during training<br> ➡️ The model is forced to generalize, not memorize</p><h4>Keras example:</h4><pre>model = Sequential([<br>    Dense(128, activation=&#39;relu&#39;),<br>    Dropout(0.5),<br>    Dense(64, activation=&#39;relu&#39;),<br>    Dropout(0.3),<br>    Dense(10, activation=&#39;softmax&#39;)<br>])</pre><h4>Other types of regularization:</h4><ul><li>L1 regularization</li><li>L2 regularization</li><li>Weight decay</li></ul><p>But dropout is the easiest to understand.</p><h3>Lesson 10: Data Augmentation(Expanding Your Dataset Without Collecting More Data)</h3><p>Sometimes you have only 200–500 images. This is not enough for training a robust model. Data augmentation fixes this.</p><h4>What is Data Augmentation?</h4><p>It creates <strong>new versions</strong> of your existing images: rotated, flipped, zoomed, cropped, color-shifted.</p><p>This increases the diversity of your data.</p><h4>Result:</h4><ul><li>less overfitting</li><li>better generalization</li><li>stronger model</li></ul><h4>Keras Example</h4><pre>datagen = ImageDataGenerator(<br>    rotation_range=50,<br>    horizontal_flip=True,<br>    zoom_range=0.2,<br>    width_shift_range=0.1,<br>    height_shift_range=0.1<br>)</pre><h3>Lesson 11: Training a Larger Model</h3><p>As one grows comfortable, one moves from small, simple models to deeper, more powerful models.</p><h4>What changes when training larger models?</h4><ol><li><strong>Need more GPU memory: </strong>Large models don’t fit on CPU easily.</li><li><strong>Longer training time:</strong> A model like ResNet50 has 23 million parameters.</li><li><strong>More regularization is needed: </strong>Because large models overfit faster.</li><li><strong>Batch size and learning rate matter more: </strong>Poor hyperparameters will destabilize training.</li></ol><h4>Larger models usually use:</h4><ul><li>Batch normalization</li><li>Dropout</li><li>Skip connections</li><li>Transfer learning</li></ul><h4>Example of a larger model using transfer learning (Keras):</h4><pre>base = EfficientNetB0(weights=&#39;imagenet&#39;, include_top=False, pooling=&#39;avg&#39;)<br><br>x = Dense(256, activation=&#39;relu&#39;)(base.output)<br>x = Dropout(0.4)(x)<br>out = Dense(10, activation=&#39;softmax&#39;)(x)<br><br>model = Model(inputs=base.input, outputs=out)</pre><p><em>This publication is the beginning of something exciting for my career and for me personally. Let’s see where this journey takes us.</em></p><p><em>And also thank you so much </em><a href="https://www.linkedin.com/in/agrigorev/"><em>Alexey Grigorev</em></a><em> and the datatalksclub team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1bf9061b213" width="1" height="1" alt=""><hr><p><a href="https://medium.com/training-models-raising-kids/deep-learning-part-3-b1bf9061b213">Deep Learning (Part 3)</a> was originally published in <a href="https://medium.com/training-models-raising-kids">Training Models, Raising Kids</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning (Part 2)]]></title>
            <link>https://medium.com/training-models-raising-kids/deep-learning-part-2-316a4dd3c729?source=rss-c1cc23102f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/316a4dd3c729</guid>
            <category><![CDATA[mlzoomcamp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Blessing Orazulume]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 23:36:10 GMT</pubDate>
            <atom:updated>2025-12-01T23:36:10.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8yvSvty6zJSk_RaFYm965Q.png" /></figure><h3>Lesson 4: What Convolutional Neural Networks Really Do</h3><p>Convolutional Neural Networks (CNNs) are the <em>workhorses</em> of modern computer vision.<br> They power everything from:</p><ul><li>facial recognition</li><li>medical imaging models</li><li>self-driving car perception systems</li><li>fashion classification</li></ul><p>But what exactly is happening inside a CNN?</p><p>Let’s break it down.</p><h3>1. The Input: An Image</h3><p>A CNN takes in an image, for example:</p><pre>200 × 200 × 3   # height × width × RGB channels</pre><p>The goal is to predict the type of image (shirt, shoe, dress?).</p><h3>2. Convolutional Layers — The Heart of CNNs</h3><p>A <strong>convolutional layer</strong> contains <strong>filters</strong> (also called kernels).<br> Think of filters as smaller images that “slide” across your input.</p><h4>What do filters do?</h4><p>Each filter searches for a <strong>specific pattern</strong> in the image. For example: vertical edges, curves, textures, corners, color gradients</p><p>As each filter scans the image, it produces a <strong>feature map</strong>, where:</p><ul><li><strong>High values → strong similarity</strong></li><li><strong>Low values → no match</strong></li></ul><p>If you have <strong>32 filters</strong>, you get <strong>32 feature maps</strong>.</p><h4>Learning filters, not hand-coding them</h4><p>Earlier computer vision required manually designing filters. CNNs <em>learn</em> the best filters automatically.</p><h4>Hierarchy of features</h4><ul><li><strong>Layer 1:</strong> simple patterns → edges</li><li><strong>Layer 2:</strong> shapes → circles, triangles, textures</li><li><strong>Layer 3+:</strong> object parts → sleeves, collars, soles of shoes</li></ul><p>This is why deep CNNs are so good at recognizing complex objects.</p><h3>3. Pooling Layers — Making Features Smaller and Stronger</h3><p>Pooling layers reduce the spatial size of feature maps.</p><p>Most common:</p><pre>nn.MaxPool2d(2, 2)</pre><p>This takes a <strong>2×2</strong> region and keeps only the <strong>maximum</strong> value.</p><h3>4. Dense Layers — Final Decision Makers</h3><p>After several convolution + pooling layers, you flatten everything into a vector.</p><p>PyTorch example:</p><pre>self.classifier = nn.Sequential(<br>    nn.Linear(32 * 7 * 7, 128),<br>    nn.ReLU(),<br>    nn.Linear(128, 10)<br>)</pre><p>Here’s a simple pipeline summary:</p><pre>Image → Convolution Layer → Feature Maps → Pooling → More Convolutions → Flatten → Dense Layer → Prediction</pre><h3>Lesson 5: Transfer Learning</h3><p>Training a CNN from scratch is expensive:</p><ul><li>millions of parameters</li><li>huge datasets needed</li><li>long training time</li></ul><p>That’s where <strong>transfer learning</strong> comes in.</p><h3>What is Transfer Learning?</h3><p>Instead of training an entire CNN from scratch, you:</p><ul><li><strong>Start with a pre-trained model</strong> (e.g., ResNet, EfficientNet, Xception, MobileNet).</li><li><strong>Freeze</strong> the convolutional layers<br> → These contain <em>generic</em> learned features like edges and textures</li><li><strong>Replace</strong> the top (dense) layers with your own<br> → These learn <em>specific</em> features for your dataset</li><li><strong>Train the dense layers</strong></li></ul><h4><strong>Using Xception as a base model (Keras example)</strong></h4><pre>from tensorflow.keras.applications import Xception<br><br>base_model = Xception(weights=&quot;imagenet&quot;, include_top=False, pooling=&quot;avg&quot;)<br><br>for layer in base_model.layers:<br>    layer.trainable = False</pre><p>We keep the CNN layers (generic features) and remove the classifier.</p><p>Then we add our own:</p><pre>from tensorflow.keras import layers, models<br><br>inputs = layers.Input(shape=(224, 224, 3))<br>x = base_model(inputs, training=False)<br>outputs = layers.Dense(10, activation=&quot;softmax&quot;)(x)<br><br>model = models.Model(inputs, outputs)</pre><h3>What about batch size?</h3><p>Batch size = number of images processed <em>before</em> a weight update.</p><ul><li><strong>Small batch</strong> → slow but stable</li><li><strong>Large batch</strong> → fast but can generalize poorly</li><li>Common values: 32, 64, 128</li></ul><h3>And what is an Epoch?</h3><p>An epoch = 1 full pass through the entire training dataset.</p><p>If your dataset has 200 images and the batch size is 20, then one epoch = 10 steps.</p><p>Training typically takes 10–50 epochs.</p><h3>Lesson 6: Adjusting Learning Rates — The Secret to Good Training</h3><p>The learning rate (LR) controls how quickly your model updates its weights.</p><p>Think of learning rate like reading speed:</p><ul><li>Too fast → you skip words</li><li>Too slow → you get bored</li><li>Just right → you absorb everything efficiently</li></ul><h3>High Learning Rate (too fast)</h3><ul><li>Training appears fast</li><li>Poor validation performance</li><li>Model bounces around the solution</li><li>Risk of <strong>overfitting</strong></li></ul><h3>Low Learning Rate (too slow)</h3><ul><li>Very stable</li><li>But training is extremely slow</li><li>Risk of <strong>underfitting</strong></li><li>Might get stuck in local minima</li></ul><h3>Medium Learning Rate (ideal)</h3><ul><li>Balanced speed and accuracy</li><li>Most models use lr = 0.001 or lr = 0.0001</li></ul><p>Example with Keras:</p><pre>optimizer = Adam(learning_rate=0.0001)</pre><p>Example with PyTorch:</p><pre>optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)</pre><h3>Key Takeaways</h3><ul><li>CNNs learn patterns in images automatically</li><li>Hierarchical feature learning makes CNNs powerful</li><li>Reuse pre-trained models instead of training from scratch</li><li>Freeze convolutional layers, retrain dense layers</li><li>Optimizers like Adam control how weights update</li><li>LR controls how fast the model learns</li></ul><p><em>This publication is the beginning of something exciting for my career and for me personally. Let’s see where this journey takes us.</em></p><p><em>And also thank you so much </em><a href="https://www.linkedin.com/in/agrigorev/"><em>Alexey Grigorev</em></a><em> and the datatalksclub team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=316a4dd3c729" width="1" height="1" alt=""><hr><p><a href="https://medium.com/training-models-raising-kids/deep-learning-part-2-316a4dd3c729">Deep Learning (Part 2)</a> was originally published in <a href="https://medium.com/training-models-raising-kids">Training Models, Raising Kids</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning (Part 1)]]></title>
            <link>https://medium.com/training-models-raising-kids/deep-learning-part-1-9b22a19604e9?source=rss-c1cc23102f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b22a19604e9</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlzoomcamp]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Blessing Orazulume]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 23:09:10 GMT</pubDate>
            <atom:updated>2025-12-01T23:09:10.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8yvSvty6zJSk_RaFYm965Q.png" /></figure><p>In the last few weeks, I’ve been learning how to classify images using deep learning. Before this, my world of machine learning primarily lived in <strong>tabular data</strong>. But image data? That felt like a completely different universe.</p><p>Here is a summary of what I learned, broken down into three digestible lessons.</p><h3>Lesson 1: Fashion Classification — Why Traditional ML Struggles With Images</h3><p>When I started, I assumed I could use logistic regression to classify fashion images. After all, it works beautifully on many classification tasks. But here’s what I quickly learned:</p><h4>Traditional ML models like Logistic Regression, Random Forest, Linear Regression:</h4><ul><li>Work best on tabular data</li><li>Expect engineered features (age, height, income, etc.)</li><li>Cannot automatically extract patterns from raw pixels</li></ul><p>This means if you pass an image (which might be 200 × 200 × 3 = 120,000 pixel values) directly into Logistic Regression, it will fail terribly. The model doesn’t know how to detect patterns like:</p><ul><li>Edges</li><li>Colors</li><li>Shapes</li><li>Textures</li></ul><p>Humans can instantly differentiate between a boot and a handbag. Models like Logistic Regression cannot.</p><h3>Enter Neural Networks</h3><p>Neural networks, especially <strong>Convolutional Neural Networks (CNNs)</strong>, shine here because they learn hierarchical features:</p><ul><li>Low-level: edges, curves</li><li>Mid-level: patterns, textures</li><li>High-level: full objects</li></ul><p>So for multi-class image problems (e.g., 10 fashion classes), traditional ML models struggle, but neural networks thrive.</p><p>Here’s a simple example of using a neural network for image classification using Keras:</p><pre>from tensorflow.keras import layers, models<br><br>model = models.Sequential([<br>    layers.Conv2D(32, (3,3), activation=&#39;relu&#39;, input_shape=(200, 200, 3)),<br>    layers.MaxPooling2D(2,2),<br>    layers.Flatten(),<br>    layers.Dense(64, activation=&#39;relu&#39;),<br>    layers.Dense(10, activation=&#39;softmax&#39;)<br>])<br><br>model.compile(<br>    optimizer=&#39;adam&#39;,<br>    loss=&#39;sparse_categorical_crossentropy&#39;,<br>    metrics=[&#39;accuracy&#39;]<br>)</pre><h3>Lesson 2: TensorFlow, Keras and PyTorch — Making Deep Learning Simpler</h3><p>Before diving into CNNs, you need a tool to build them. That’s where <strong>TensorFlow</strong> and <strong>Keras</strong> come in. And also, PyTorch.</p><h3>🔹 TensorFlow</h3><p>A robust deep learning <em>framework</em>. It gives you low-level flexibility but can be verbose.</p><h3>🔹 Keras</h3><p>A higher-level, user-friendly API built inside TensorFlow. It simplifies model building into easy, readable code.</p><p>For example, loading images becomes incredibly simple:</p><pre>from tensorflow.keras.preprocessing.image import load_img, img_to_array<br><br>img = load_img(&quot;dress.jpg&quot;, target_size=(200, 200))<br>img_array = img_to_array(img)    # shape: (200, 200, 3)</pre><p>Images are stored as RGB pixels, where each value ranges from <strong>0–255</strong>.</p><h3>🔹 PyTorch</h3><p>PyTorch offers a more “Pythonic” and dynamic style for building models.</p><p>Example of defining a CNN in PyTorch:</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class FashionCNN(nn.Module):<br>    def __init__(self):<br>        super(FashionCNN, self).__init__()<br>        self.conv1 = nn.Conv2d(3, 32, kernel_size=3)<br>        self.pool = nn.MaxPool2d(2, 2)<br>        self.fc1 = nn.Linear(32 * 99 * 99, 64)<br>        self.fc2 = nn.Linear(64, 10)<br><br>    def forward(self, x):<br>        x = self.pool(F.relu(self.conv1(x)))<br>        x = x.view(x.size(0), -1)<br>        x = F.relu(self.fc1(x))<br>        return self.fc2(x)</pre><p>PyTorch is especially loved for:</p><ul><li>clean debugging</li><li>dynamic computation graphs</li><li>excellent ecosystem (HuggingFace, Lightning, etc.)</li></ul><p>Both TensorFlow and PyTorch are powerful — your choice depends on personal preference and the project.</p><h3>Lesson 3: Pre-trained Convolutional Neural Networks (Transfer Learning)</h3><p>Here’s where things get exciting.</p><p>Training a large CNN from scratch requires:</p><ul><li><strong>Huge datasets</strong></li><li><strong>Lots of time</strong></li><li><strong>Powerful GPUs</strong></li></ul><p>This is why researchers created <strong>ImageNet</strong>, a massive dataset with:</p><ul><li>1,000 different classes</li><li>Over <strong>1 million images</strong></li></ul><p>Models trained on ImageNet (like ResNet, MobileNet, VGG16) already understand:</p><ul><li>edges</li><li>textures</li><li>shapes</li><li>objects</li></ul><p>Instead of training your own CNN from scratch, you can use these <strong>pre-trained models</strong> and adapt them to your own dataset.</p><p>This technique, called <strong>transfer learning</strong>, often delivers impressive results with very small datasets.</p><pre>from tensorflow.keras.applications import MobileNetV2<br>from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions<br>from tensorflow.keras.preprocessing.image import load_img, img_to_array<br>import numpy as np<br><br># Load pre-trained model + weights trained on ImageNet<br>model = MobileNetV2(weights=&quot;imagenet&quot;)<br><br># Load and preprocess image<br>img = load_img(&quot;shoe.jpg&quot;, target_size=(224, 224))<br>x = img_to_array(img)<br>x = np.expand_dims(x, axis=0)<br>x = preprocess_input(x)<br><br># Predict<br>predictions = model.predict(x)<br>decoded = decode_predictions(predictions, top=3)<br><br>print(decoded)</pre><h3>Key Takeaways</h3><p>Here’s a summary of what truly matters:</p><h4>Classical ML ≠ Image ML</h4><ul><li>Logistic Regression and Random Forest cannot learn spatial patterns in images.</li><li>CNNs are specifically designed for this.</li></ul><h4>TensorFlow/Keras and PyTorch are your main tools</h4><ul><li><strong>TensorFlow/Keras</strong> = beginner-friendly, high-level</li><li><strong>PyTorch is flexible,</strong> intuitive, and loved in research<br> Both can easily load and preprocess images.</li></ul><h4>Transfer learning is a superpower</h4><p>Using ImageNet-trained models saves:</p><ul><li>training time</li><li>compute power</li><li>large datasets</li></ul><p>You get high accuracy <em>even with small datasets</em>.</p><h4>You don’t need a supercomputer</h4><p>Cloud tools like AWS SageMaker or Google Colab give you powerful GPUs on demand.</p><p><em>This publication is the beginning of something exciting for my career and for me personally. Let’s see where this journey takes us.</em></p><p><em>And also thank you so much </em><a href="https://www.linkedin.com/in/agrigorev/"><em>Alexey Grigorev</em></a><em> and the datatalksclub team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b22a19604e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/training-models-raising-kids/deep-learning-part-1-9b22a19604e9">Deep Learning (Part 1)</a> was originally published in <a href="https://medium.com/training-models-raising-kids">Training Models, Raising Kids</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a FastAPI Service for My Readmission Model: From Notebook to a Real API]]></title>
            <link>https://medium.com/training-models-raising-kids/building-a-fastapi-service-for-my-readmission-model-from-notebook-to-a-real-api-e395c4ded509?source=rss-c1cc23102f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/e395c4ded509</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlzoomcamp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Blessing Orazulume]]></dc:creator>
            <pubDate>Wed, 19 Nov 2025 10:52:34 GMT</pubDate>
            <atom:updated>2025-11-19T10:52:34.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yZF3Z9XuW08iL1rkZq0m5g.png" /></figure><p>After training several models for predicting hospital readmission, I reached an exciting milestone:</p><p><strong>Turning my notebook model into a real API that anyone can use.</strong></p><p>This post walks through how I transformed my Jupyter notebook into:</p><ul><li>a <strong>clean train.py script</strong>,</li><li>a <strong>FastAPI prediction service</strong>,</li><li>a <strong>Pydantic validation schema</strong>,</li><li>and even how I tested the endpoint locally.</li></ul><h3>1️⃣ From Notebook to Script: Creating train.py</h3><p>Notebooks are great for experimentation, but models used in production need structure and reproducibility.</p><p>So I exported all the training logic into a file called <strong>train.py</strong>, which:</p><ul><li>loads and cleans the data</li><li>performs feature engineering</li><li>trains the Random Forest model</li><li>bundles everything inside a scikit-learn Pipeline</li><li>saves the final model to disk</li></ul><p>Here’s a simplified version of the script:</p><pre>import pickel<br>import pandas as pd<br>import numpy as np<br>from sklearn.pipeline import make_pipeline<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.feature_extraction import DictVectorizer<br><br>def load_data():<br>    df = pd.read_csv(&quot;data/diabetic_data.csv&quot;)<br>    df = df.replace(&#39;?&#39;, np.nan)<br><br>    df = df.drop(columns=[<br>        &#39;weight&#39;, &#39;max_glu_serum&#39;, &#39;A1Cresult&#39;, &#39;medical_specialty&#39;, &#39;payer_code&#39;<br>    ])<br><br>    # clean categories<br>    cat = df.select_dtypes(include=&#39;object&#39;).columns<br>    num = df.select_dtypes(include=&#39;number&#39;).columns<br><br>    df[cat] = df[cat].fillna(&#39;NA&#39;)<br>    df[num] = df[num].fillna(0.0)<br><br>    # target mapping<br>    df[&#39;readmitted&#39;] = df[&#39;readmitted&#39;].apply(lambda x: 1 if x==&#39;&lt;30&#39; else 0)<br><br>    return df<br><br>def train_model(df):<br>    y = df.readmitted.values<br><br>    numerical = [...]<br>    categorical = [...]<br><br>    pipeline = make_pipeline(<br>        DictVectorizer(),<br>        RandomForestClassifier(<br>            n_estimators=150,<br>            max_depth=15,<br>            min_samples_leaf=3,<br>            class_weight=&#39;balanced&#39;,<br>            random_state=1<br>        )<br>    )<br><br>    train_dict = df[categorical + numerical].to_dict(orient=&#39;records&#39;)<br>    pipeline.fit(train_dict, y)<br><br>    return pipeline<br><br>if __name__ == &quot;__main__&quot;:<br>    df = load_data()<br>    model = train_model(df)<br><br>    with open(&quot;model.bin&quot;, &quot;wb&quot;) as f_out:<br>        pickle.dump(model, f_out)<br><br>    print(&quot;Model saved!&quot;)</pre><h3>2️⃣ Creating the Prediction API (predict.py)</h3><p>I chose <strong>FastAPI</strong> because:</p><ul><li>it’s extremely fast,</li><li>it automatically generates interactive docs (Swagger),</li><li>it uses Pydantic for clean validation,</li><li>and it’s very easy to deploy.</li></ul><p>My predict.py file loads the trained model and exposes an endpoint /predict.</p><pre>import pickle<br>from fastapi import FastAPI<br>from pydantic import BaseModel<br><br># Load model<br>with open(&quot;model/model.bin&quot;, &quot;rb&quot;) as f_in:<br>  model = pickle.load(f_in)<br>  app = FastAPI(title=&quot;Readmission Predictor&quot;, version=&quot;1.0&quot;)<br><br># Pydantic schema<br>class Patient(BaseModel):<br>  time_in_hospital: int<br>  num_lab_procedures: int<br>  num_procedures: int<br>  num_medications: int<br>  number_outpatient: int<br>  number_emergency: int<br>  number_inpatient: int<br>  number_diagnoses: int<br>  race: str | None = None<br>  gender: str | None = None<br>  age: str | None = None<br>  diag_1: str | None = None<br>  diag_2: str | None = None<br>  diag_3: str | None = None<br>  insulin: str | None = None<br>  metformin: str | None = None<br>  change: str | None = None<br>  diabetesMed: str | None = None<br><br>class PredictionResponse(BaseModel):<br>  readmitted_probability: float<br>  readmitted: bool<br><br>def predict_single(patient_dict):<br>  return model.predict_proba([patient_dict])[0, 1]<br><br>@app.post(&quot;/predict&quot;, response_model=PredictionResponse)<br><br>def predict(patient: Patient):<br>  prob = predict_single(patient.dict())<br>  return PredictionResponse(<br>    readmitted_probability=prob,<br>    readmitted=prob &gt;= 0.5<br>  )</pre><p>With just a few lines of code, I had a fully working API.</p><h3>3️⃣ Pydantic Validation: Why It Matters</h3><p>One of my favourite parts of FastAPI is <strong>Pydantic</strong>.</p><p>It ensures every incoming request contains the correct data type and format. For example, if a client accidentally sends:</p><pre>{ &quot;time_in_hospital&quot;: &quot;five&quot; }</pre><p>FastAPI immediately returns a descriptive validation error instead of letting your model crash.</p><p>This is powerful because healthcare data is <strong>messy</strong>, and Pydantic protects your service from malformed input.</p><h3>4️⃣ Testing the API Locally</h3><p>To run the service locally:</p><pre>uvicorn predict:app - reload - port 9696</pre><p>FastAPI automatically generates docs:</p><ul><li>Visit <a href="http://localhost:9696/docs">http://localhost:9696/docs</a></li><li>Try the endpoint interactively</li><li>Send test requests without writing code</li></ul><p>I also tested with raw JSON:</p><pre>import requests<br><br>url = &quot;http://localhost:9696/predict&quot;<br><br>patient = {<br> &quot;time_in_hospital&quot;: 3,<br> &quot;num_lab_procedures&quot;: 50,<br> &quot;num_procedures&quot;: 0,<br> &quot;num_medications&quot;: 12,<br> &quot;number_outpatient&quot;: 1,<br> &quot;number_emergency&quot;: 0,<br> &quot;number_inpatient&quot;: 1,<br> &quot;number_diagnoses&quot;: 6,<br> &quot;race&quot;: &quot;Caucasian&quot;,<br> &quot;gender&quot;: &quot;Female&quot;,<br> &quot;age&quot;: &quot;[60–70)&quot;<br>}<br><br>response = requests.post(url, json=patient)<br>print(response.json())</pre><p>Example output:</p><pre>{<br> &quot;readmitted_probability&quot;: 0.2874,<br> &quot;readmitted&quot;: false<br>}</pre><p>🎉 <strong>Success!</strong> I had a working, local ML prediction API.</p><h3>5️⃣ What I Learned From This Part of the Project</h3><p>Building this FastAPI service taught me:</p><ul><li>How to move from notebook experimentation to production-ready scripts</li><li>Why pipelines and DictVectorizer are essential for deployment</li><li>How to validate complex healthcare data with Pydantic</li><li>How to expose a machine-learning model as an API</li><li>How to send real-world requests to my model</li></ul><p><em>This publication is the beginning of something exciting for my career and for me personally. Let’s see where this journey takes us.</em></p><p><em>And also thank you so much </em><a href="https://www.linkedin.com/in/agrigorev/"><em>Alexey Grigorev</em></a><em> and the datatalksclub team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e395c4ded509" width="1" height="1" alt=""><hr><p><a href="https://medium.com/training-models-raising-kids/building-a-fastapi-service-for-my-readmission-model-from-notebook-to-a-real-api-e395c4ded509">Building a FastAPI Service for My Readmission Model: From Notebook to a Real API</a> was originally published in <a href="https://medium.com/training-models-raising-kids">Training Models, Raising Kids</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Random Forest & XGBoost for Readmission Prediction: Why They Beat Logistic Regression]]></title>
            <link>https://medium.com/training-models-raising-kids/random-forest-xgboost-for-readmission-prediction-why-they-beat-logistic-regression-2de380b42276?source=rss-c1cc23102f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/2de380b42276</guid>
            <category><![CDATA[mlzoomcamp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <dc:creator><![CDATA[Blessing Orazulume]]></dc:creator>
            <pubDate>Wed, 19 Nov 2025 10:52:01 GMT</pubDate>
            <atom:updated>2025-11-19T10:52:01.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yZF3Z9XuW08iL1rkZq0m5g.png" /></figure><p>After building my baseline logistic regression model for predicting 30-day hospital readmission, I quickly noticed its limitations:</p><ul><li>accuracy was misleading,</li><li>recall was extremely low,</li><li>and the AUC hovered around <strong>0.63</strong>.</li></ul><p>So I turned to two of the most powerful machine-learning techniques for structured (tabular) data: <strong>Random Forest and XGBoost.</strong></p><p>Both are tree-based models, which means they can capture complex, nonlinear patterns that linear models simply cannot.</p><p>This post walks through <strong>why tree-based models work better</strong>, how I trained them, the hyperparameters I tested, and what kind of performance I achieved.</p><h3>1️⃣ Why Tree Models Perform Better Than Logistic Regression</h3><p>Logistic Regression assumes:</p><ul><li>The features are independent</li><li>The relationship between features and the target is linear</li><li>Effects are smooth and gradual</li></ul><p>But hospital readmission is <strong>NOT</strong> a linear phenomenon.</p><p>For example:</p><ul><li>A patient with <strong>3+ prior inpatient stays</strong> is exponentially more likely to return</li><li>Specific diagnoses dramatically increase risk</li><li>Medication changes indicate instability</li><li>Age interacts with comorbidities</li><li>Severity jumps at thresholds, not gradually</li></ul><p>Random Forest and XGBoost <strong>don’t assume linearity</strong>.</p><p>They split the data into <strong>regions</strong>, each with different patterns.</p><h3>2️⃣ Training the Random Forest Model</h3><p>I began with this configuration:</p><pre>rf = RandomForestClassifier(<br>  n_estimators=150,<br>  max_depth=15,<br>  min_samples_leaf=3,<br>  class_weight=&#39;balanced&#39;,<br>  max_features=&#39;sqrt&#39;,<br>  n_jobs=-1,<br>  random_state=1<br>)</pre><h4>Hyperparameters I experimented with:</h4><h4>1. n_estimators (number of trees)</h4><p>I tested with <strong>[10, 50, 100, 150, 200]</strong>. More trees generally improve stability, but with diminishing returns.</p><h4>2. max_depth</h4><p>I tested depths with [5, 10, 15]</p><blockquote>Deep trees → overfit</blockquote><blockquote>Shallow trees → underfit</blockquote><p>Depth ≈ 15 gave the best balance.</p><h4>3. class_weight=’balanced’</h4><p>This helps combat the severe class imbalance (only ~11% readmissions).</p><p>After tuning, I stuck with:</p><blockquote><strong>150 trees, max_depth=15</strong></blockquote><h3>3️⃣ Performance Metrics: Random Forest vs Logistic Regression</h3><p>Here’s how the Random Forest performed on my validation set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*BrGZFBU_VuR72ljjbXWiwg.png" /></figure><h3>Interpretation</h3><ul><li><strong>Recall jumped from 0.01 → 0.505: </strong>This is huge. It means Random Forest <em>actually finds</em> readmitted patients.</li><li><strong>Precision dropped(</strong>Classic tradeoff): the model predicts more positives, so some will be false alarms.</li><li><strong>AUC stayed the same: </strong>This is interesting. Random Forest doesn’t increase AUC, but it dramatically reshapes the prediction distribution.</li></ul><p>Overall:</p><p><strong>Random Forest gives a much more clinically useful model</strong> because it identifies high-risk patients.</p><h3><strong>4️⃣</strong> XGBoost: Did It Perform Better?</h3><p>Yes — but only slightly.</p><p>XGBoost is a <strong>boosting algorithm</strong>, meaning:</p><ul><li>Each tree learns from the errors of the previous tree</li><li>It focuses on complex cases</li><li>It is more flexible than Random Forest</li><li>Easier to overfit</li></ul><p>My XGBoost configuration:</p><pre>xgb_params = {<br>    &#39;eta&#39;: 0.1,<br>    &#39;max_depth&#39;: 3,<br>    &#39;min_child_weight&#39;: 1,<br>    &#39;subsample&#39;: 0.8,<br>    &#39;colsample_bytree&#39;: 0.8,<br>    &#39;objective&#39;: &#39;binary:logistic&#39;,<br>    &#39;eval_metric&#39;: &#39;auc&#39;,<br>    &#39;seed&#39;: 1<br>}</pre><h4>XGBoost Performance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*hGTyDaqIjkzgv7mxF8sKVA.png" /></figure><p>It performed slightly better than Random Forest on AUC and F1.<br>But the most significant difference was:</p><ul><li>XGBoost handled rare patterns better</li><li>It was more stable across thresholds</li><li>It generalised slightly better</li></ul><p>Still, both models were far better than logistic regression.</p><h3>Key Takeaways</h3><ul><li>Logistic regression gave a stable baseline, but it was too weak</li><li>Random Forest solved the recall problem: Recall ≈ 0.50 and F1 improved dramatically</li><li>XGBoost performed best overall, achieving a balanced precision/recall and a slightly better AUC.</li><li>Tree models revealed meaningful medical insights</li></ul><h3>But… the problem is still hard</h3><p>Even the best models achieve an AUC of ~0.63–0.64. That indicates the dataset lacks sufficient signals for accurate prediction.</p><h3>Final Thoughts</h3><p>Working with Random Forest and XGBoost showed me a powerful truth:</p><ul><li><strong>Sometimes better algorithms don’t magically fix a weak prediction problem</strong></li><li><strong>But they help us learn more from the data, and make safer decisions</strong></li></ul><p>In healthcare, catching even a small percentage of high-risk patients can make a significant difference.</p><p><em>This publication is the beginning of something exciting for my career and for me personally. Let’s see where this journey takes us.</em></p><p><em>And also thank you so much </em><a href="https://www.linkedin.com/in/agrigorev/"><em>Alexey Grigorev</em></a><em> and the datatalksclub team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2de380b42276" width="1" height="1" alt=""><hr><p><a href="https://medium.com/training-models-raising-kids/random-forest-xgboost-for-readmission-prediction-why-they-beat-logistic-regression-2de380b42276">Random Forest &amp; XGBoost for Readmission Prediction: Why They Beat Logistic Regression</a> was originally published in <a href="https://medium.com/training-models-raising-kids">Training Models, Raising Kids</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression for Hospital Readmission: My Baseline Model & What It Revealed]]></title>
            <link>https://medium.com/training-models-raising-kids/logistic-regression-for-hospital-readmission-my-baseline-model-what-it-revealed-071d0f9f98cd?source=rss-c1cc23102f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/071d0f9f98cd</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[mlzoomcamp]]></category>
            <dc:creator><![CDATA[Blessing Orazulume]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 22:11:20 GMT</pubDate>
            <atom:updated>2025-11-17T22:11:20.946Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yZF3Z9XuW08iL1rkZq0m5g.png" /></figure><p>After exploring the dataset and understanding its imbalance, I built my first baseline model for predicting <strong>30-day hospital readmission</strong> using <strong>Logistic Regression</strong>.</p><p>My goal wasn’t to create a perfect model but to understand the signal in the data and establish a solid baseline before trying more complex algorithms, such as Random Forest or XGBoost.</p><p>Here’s everything I learned.</p><h3><strong>1️⃣ Preparing the Data: One-Hot Encoding with DictVectorizer</strong></h3><p>Before training any model, I needed to convert my dataset into numerical form.</p><p><strong><em>The challenge:</em></strong></p><p>The dataset contains <strong>numerous categorical features</strong>, including medications, diagnosis codes, race, gender, and admission sources.</p><h4>Why DictVectorizer?</h4><ul><li>It handles <strong>large categorical spaces</strong> more efficiently</li><li>Perfect for training + deployment pipelines</li><li>The same object can be reused for real-time prediction</li><li>Automatically performs one-hot encoding</li></ul><p>Here’s how I used it:</p><pre>from sklearn.feature_extraction import DictVectorizer<br><br>dv = DictVectorizer(sparse=False)<br><br>train_dict = df_train[categorical_cols + numerical_cols].to_dict(orient=&#39;records&#39;)<br>X_train = dv.fit_transform(train_dict)<br><br>val_dict = df_val[categorical_cols + numerical_cols].to_dict(orient=&#39;records&#39;)<br>X_val = dv.transform(val_dict)</pre><h3>2️⃣ Training Logistic Regression</h3><p>Logistic regression is the simplest baseline for binary classification.</p><p>It trains fast, it’s explainable, and it gives probability estimates.</p><pre>from sklearn.linear_model import LogisticRegression<br>model = LogisticRegression(solver=&#39;lbfgs&#39;, max_iter=1000)<br>model.fit(X_train, y_train)<br>y_pred = model.predict_proba(X_val)[:, 1]</pre><p>This gives the probability of readmission for each patient.</p><h3>3️⃣ Evaluating the Model: Accuracy, Precision, Recall, F1, AUC</h3><p>Once I had predictions, I computed the essential metrics:</p><pre>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score<br><br>readmitted_decision = (y_pred &gt;= 0.5)<br><br>accuracy = accuracy_score(y_val, readmitted_decision)<br>precision = precision_score(y_val, readmitted_decision)<br>recall = recall_score(y_val, readmitted_decision)<br>f1 = f1_score(y_val, readmitted_decision)<br>auc = roc_auc_score(y_val, y_pred)</pre><p>My results:</p><ul><li><strong>Accuracy:</strong> 0.888</li><li><strong>Precision:</strong> 0.571</li><li><strong>Recall:</strong> 0.010</li><li><strong>AUC:</strong> 0.633</li><li><strong>F1:</strong> 0.021</li></ul><h3>4️⃣ Why Accuracy Is High — But Misleading</h3><p>88.8% accuracy looks like “Wow! Great model!”</p><p>But no.</p><p>Remember:</p><p><strong>Only ~11% of patients are readmitted.</strong></p><p>A model that predicts <strong>“nobody is readmitted”</strong> would get 89% accuracy.</p><p>So accuracy tells us nothing.</p><h3>5️⃣ Why Recall Is So Low</h3><p>Recall = the ability to find actual readmitted patients.</p><p>My model had <strong>recall = 0.01</strong>.</p><p>That means: <em>Out of 100 actual readmissions, the model only caught 1.</em></p><h4>Why?</h4><p>Because the default threshold is <strong>0.5</strong>.</p><p>If the model predicts:</p><ul><li>0.17</li><li>0.23</li><li>0.34</li></ul><p>These aren’t considered “positive” by logistic regression.</p><p>However, in an imbalanced dataset, the signals for the positive class are extremely weak.</p><p>Most predictions will fall below 0.5, causing:</p><ul><li><strong>few positives predicted</strong></li><li><strong>precision goes up</strong></li><li><strong>recall collapses</strong></li></ul><p>This is the tradeoff.</p><h3>In healthcare:</h3><p>Missing a high-risk patient is worse than raising a false alarm. So <strong>recall matters more</strong> than accuracy.</p><h3>6️⃣ AUC Shows the True Picture</h3><p>AUC = 0.633 tells us:</p><ul><li>Better than random guessing (0.5)</li><li>There <em>is</em> some signal in the features</li><li>But logistic regression can’t capture nonlinear relationships</li></ul><p>This matches what we saw earlier in feature importance that the dataset is challenging.</p><h3><strong>Key Takeaways From the Baseline Model</strong></h3><ul><li>One-hot encoding with DictVectorizer makes the pipeline clean</li><li>Logistic Regression sets a realistic baseline: AUC ~ 0.63</li><li>Accuracy is misleading for imbalanced problems</li><li>Recall is extremely low at the default threshold</li><li>The model is conservative: it prefers predicting “no readmission”</li></ul><p><em>This publication is the beginning of something exciting for my career and for me personally. Let’s see where this journey takes us.</em></p><p><em>And also thank you so much </em><a href="https://www.linkedin.com/in/agrigorev/"><em>Alexey Grigorev</em></a><em> and the datatalksclub team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=071d0f9f98cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/training-models-raising-kids/logistic-regression-for-hospital-readmission-my-baseline-model-what-it-revealed-071d0f9f98cd">Logistic Regression for Hospital Readmission: My Baseline Model &amp; What It Revealed</a> was originally published in <a href="https://medium.com/training-models-raising-kids">Training Models, Raising Kids</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Readmission Hard to Predict? A Deep Dive Into Imbalance & Feature Importance]]></title>
            <link>https://medium.com/training-models-raising-kids/is-readmission-hard-to-predict-a-deep-dive-into-imbalance-feature-importance-fd552a91481f?source=rss-c1cc23102f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd552a91481f</guid>
            <category><![CDATA[mlzoomcamp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Blessing Orazulume]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 21:35:05 GMT</pubDate>
            <atom:updated>2025-11-17T21:35:05.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yZF3Z9XuW08iL1rkZq0m5g.png" /></figure><p>Predicting hospital readmissions sounds simple in theory.</p><blockquote>You have a patient’s data.<br>You train a model.<br>You predict whether they’ll return within 30 days.</blockquote><p>But the deeper I went into this dataset for my midterm project, the more I realized:</p><blockquote><strong>Readmission is one of the most challenging aspects to predict in healthcare.</strong></blockquote><p>And the reason is simple:</p><ul><li>The target variable is highly imbalanced</li><li>The signal in the features is weak</li><li>Many important medical factors aren’t captured in the data</li></ul><p>In this post, I’ll break down what I learned while analyzing <strong>class imbalance, correlations, mutual information, and pre-model feature importance</strong>.</p><h3>1️⃣ The Surprising Truth: Only 11% of Patients Were Readmitted</h3><p>When I computed the readmission rate, the result showed that Only ~11% of patients were readmitted within 30 days:</p><pre>df.readmitted.mean()</pre><p>That means:</p><ul><li>89% = class 0 (NO readmission)</li><li>11% = class 1 (0 readmission)</li></ul><p>This is a <strong>severely imbalanced dataset</strong>, and it explains why early models performed strangely.</p><h3>Why Imbalance Makes Prediction Hard</h3><p>If a lazy model predicts <strong>“nobody is readmitted”</strong> for all patients:</p><ul><li>Accuracy = 89%</li><li>But the model is completely useless</li></ul><p>This is why metrics like accuracy collapse in imbalanced problems.</p><p>We need <strong>AUC, precision, recall, and F1</strong> instead.</p><h3>2️⃣ Correlation: Weak Signals Everywhere</h3><p>Next, I examined the correlation between numerical features and readmission.</p><pre>df[num_cols].corr()[&#39;readmitted&#39;].sort_values(ascending=False)</pre><p>The result:</p><ul><li>The strongest correlations were around <strong>0.17</strong></li><li>Many were close to <strong>0.00</strong></li></ul><h3>What this means:</h3><p>Correlation shows linear relationships.</p><p>But readmission is influenced by complex medical factors — not simple linear trends.</p><p>So correlation alone won’t tell the full story.</p><p>Still, a few interesting signals appeared:</p><ul><li><strong>number_inpatient</strong> → more past inpatient visits → higher readmission</li><li><strong>number_emergency</strong> → more ER visits → higher readmission</li><li><strong>number_diagnoses</strong> → slightly higher readmission</li><li><strong>time_in_hospital</strong> → the amount of time in the hospital gives higher readmission as well.</li></ul><p>These became essential features later.</p><h3>3️⃣ Mutual Information: What Do Inputs Actually Tell Us About the Target?</h3><p>Mutual information (MI) measures <strong>how much a feature reduces uncertainty</strong> about the target.</p><pre>from sklearn.metrics import mutual_info_score<br><br>def mutual_info_readmitted_score(series):<br>    return mutual_info_score(series, df_full_train.readmitted)<br><br>mi = df_full_train[categorical].apply(mutual_info_readmitted_score)<br>mi.sort_values(ascending=False)</pre><h3>These features had strong MI:</h3><ul><li><strong>change</strong> (whether medications changed)</li><li><strong>insulin</strong> (up/steady/down/no)</li><li><strong>diabetesMed</strong> (whether the patient is on diabetes medication)</li></ul><p>This makes sense — readmission is a <em>clinical decision</em> problem, not a statistical one.</p><h3>5️⃣ Why Readmission Is Hard to Predict (Before Modeling)</h3><p>After doing all this feature analysis, a clear pattern emerged:</p><p>Many critical medical factors are NOT in the dataset. For example: patient adherence, home environment, nursing support, diet or lifestyle, hospital quality differences, e.t.c</p><p>A machine-learning model cannot guess what isn’t recorded.</p><ul><li><strong><em>Low signal-to-noise ratio:</em></strong> Most features had weak correlation and small MI values.</li><li><strong><em>Extreme class imbalance:</em></strong> Only 11% of positives → model defaults to predicting negative.</li><li><strong><em>Diagnosis codes are complex:</em></strong> ICD-9 codes, such as “250.83”, “403”, and “V58”, require specialised domain knowledge.</li></ul><h3>6️⃣ So… Which Features Actually Matter?</h3><p>From risk ratio + MI + correlation + intuition, these stood out:</p><h4>Strongest Predictors:</h4><ul><li><strong>number_inpatient:</strong> repeated hospital use = instability</li><li><strong>number_emergency:</strong> chronic instability or poor control</li><li><strong>number_diagnoses:</strong> complexity of illness</li><li><strong>change:</strong> medication adjustment may signal a worsening condition</li><li><strong>age:</strong> elderly patients often have complications</li></ul><h4>Moderate Predictors:</h4><ul><li>num_medications</li><li>time_in_hospital</li><li>num_lab_procedures</li></ul><h4>Weak Predictors:</h4><ul><li>gender</li><li>race</li><li>diag_1, diag_2, diag_3 (because ICD codes are too granular)</li></ul><h3>Takeaway</h3><p>Feature importance shows why the prediction problem is complicated. Before training the first model, I already knew:</p><ul><li>The dataset is imbalanced</li><li>The medical signal is weak</li><li>Some features are noisy or irrelevant</li><li>AUC won’t be very high (confirmed later)</li></ul><p>This understanding helped manage expectations.</p><p>It also taught me an important lesson:</p><p><strong>Not every problem is highly predictable — and that’s okay.</strong></p><p>For healthcare, even an AUC ≈ of approximately 0.63 can still provide clinical value if used carefully (e.g., for flagging high-risk patients).</p><p><em>This publication is the beginning of something exciting for my career and for me personally. Let’s see where this journey takes us.</em></p><p><em>And also thank you so much </em><a href="https://www.linkedin.com/in/agrigorev/"><em>Alexey Grigorev</em></a><em> and the datatalksclub team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd552a91481f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/training-models-raising-kids/is-readmission-hard-to-predict-a-deep-dive-into-imbalance-feature-importance-fd552a91481f">Is Readmission Hard to Predict? A Deep Dive Into Imbalance &amp; Feature Importance</a> was originally published in <a href="https://medium.com/training-models-raising-kids">Training Models, Raising Kids</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>