<?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 Pooja on Medium]]></title>
        <description><![CDATA[Stories by Pooja on Medium]]></description>
        <link>https://medium.com/@poojashreechoudhury7?source=rss-6b879c2525c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qcA4anexhPn_3kIUMwz_zQ.png</url>
            <title>Stories by Pooja on Medium</title>
            <link>https://medium.com/@poojashreechoudhury7?source=rss-6b879c2525c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:36:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@poojashreechoudhury7/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building My First AI Agent with LangChain + Groq (From Errors to Working System)]]></title>
            <link>https://medium.com/@poojashreechoudhury7/building-my-first-ai-agent-with-langchain-groq-from-errors-to-working-system-c9813e8e08b6?source=rss-6b879c2525c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9813e8e08b6</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Pooja]]></dc:creator>
            <pubDate>Mon, 04 May 2026 11:17:27 GMT</pubDate>
            <atom:updated>2026-05-04T11:17:27.271Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started learning Generative AI, I kept seeing terms like <em>agents</em>, <em>tools</em>, and <em>LLMs</em>. I understood the theory — but I didn’t really “get it” until I built one myself.</p><p>This post is about how I built a <strong>simple AI agent using LangChain and Groq</strong>, the problems I faced, and what I learned along the way.</p><h4>What is an AI Agent (in simple terms)?</h4><p>Most beginners think AI is just:</p><pre>Input → LLM → Output</pre><p>But an <strong>agent is different</strong>:</p><pre>User → Agent → Think → Use Tool → Observe → Respond</pre><p>An agent can:</p><ul><li>Decide <em>what to do</em></li><li>Use tools (like calculator, search, etc.)</li><li>Iterate until it finds an answer</li></ul><h4>What I Built</h4><p>I created a <strong>Smart AI Assistant</strong> that can:</p><ul><li>Answer general questions</li><li>Perform mathematical calculations using a custom tool</li><li>Decide when to use tools vs LLM reasoning</li></ul><h4>Tech Stack</h4><ul><li>Python</li><li>LangChain</li><li>Groq (LLaMA 3 models)</li><li>dotenv</li></ul><h4>How It Works</h4><h4>1. LLM (Brain)</h4><p>I used Groq’s model:</p><pre>llm = ChatGroq(<br>    model=&quot;llama-3.1-8b-instant&quot;,<br>    temperature=0,<br>    groq_api_key=os.getenv(&quot;GROQ_API_KEY&quot;)<br>)</pre><h4>2. Tool (Calculator)</h4><pre>@tool<br>def calculator(expression: str) -&gt; str:<br>    cleaned = re.sub(r&quot;[^0-9+\-*/().]&quot;, &quot;&quot;, expression)<br>    return str(eval(cleaned))</pre><p>This allows the agent to solve math problems.</p><h4>3. Agent (Decision Maker)</h4><pre>agent = initialize_agent(<br>    tools=[calculator],<br>    llm=llm,<br>    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,<br>    verbose=True,<br>    max_iterations=3,<br>    early_stopping_method=&quot;generate&quot;<br>)</pre><h3>What’s Interesting: Agent Reasoning Loop</h3><p>When I run:</p><pre>What is 30 * 41?</pre><p>The agent internally does:</p><pre>Thought → I need to calculate<br>Action → calculator<br>Observation → 1230<br>Final Answer → 1230</pre><p>This is called the <strong>ReAct pattern (Reason + Act)</strong>.</p><h4>Challenges I Faced (Real Learning)</h4><h4>1. Environment Issues</h4><ul><li>Python version mismatch (3.14 caused failures)</li><li>Package conflicts in LangChain</li></ul><p>Fix: Use Python 3.11 + clean virtual environment</p><h4>2. API Integration Confusion</h4><ul><li>Mixed OpenAI and Groq incorrectly</li></ul><p>Fix: Use ChatGroq and correct API key</p><h4>3. Tool Errors</h4><ul><li>eval() failed due to dirty inputs</li></ul><p>Fix: Clean inputs using regex before evaluation</p><h4>4. Infinite Agent Loop</h4><p>The agent kept repeating actions.</p><p>Fix:</p><pre>max_iterations=3<br>early_stopping_method=&quot;generate&quot;</pre><h4>Key Learnings</h4><ul><li>Agents don’t just “answer” — they <strong>reason step by step</strong></li><li>LLM outputs are messy → always sanitize inputs</li><li>Environment setup is as important as code</li><li>Small configuration mistakes can break everything</li></ul><h4>What I Improved</h4><p>Initially:</p><ul><li>Just a basic agent</li></ul><p>Now:</p><ul><li>Stable agent</li><li>Tool integration working</li><li>Controlled reasoning loop</li><li>Clean GitHub project</li></ul><h4>Next Steps</h4><p>I plan to extend this into:</p><ul><li>Memory-based agent (conversation awareness)</li><li>Multi-tool agent (search, wiki)</li><li>RAG-based system (document Q&amp;A)</li></ul><p>#GenerativeAI #AIProjects #LangChain #LLM #AIEngineering <br>#MachineLearning #Python #ArtificialIntelligence #LearningInPublic #Groq</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9813e8e08b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Indian Food Calorie Prediction API with Machine Learning, FastAPI  & Docker]]></title>
            <link>https://medium.com/@poojashreechoudhury7/building-an-indian-food-calorie-prediction-api-with-machine-learning-fastapi-docker-088d1f67ab6c?source=rss-6b879c2525c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/088d1f67ab6c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Pooja]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 12:43:21 GMT</pubDate>
            <atom:updated>2025-12-14T12:43:21.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Indian Food Calorie Prediction API with Machine Learning, FastAPI &amp; Docker</h3><p>When it comes to Indian food, one universal truth exists — <strong>we love our food rich, diverse, and full of flavor</strong>.</p><p>But ask the average person how many calories are in a plate of <em>Masala Dosa, Biryani, Rajma Chawal,</em> or <em>Paneer Butter Masala</em> — the answer is usually a guess.</p><p>Most calorie-tracking apps today are built around Western food databases and fail to capture the complexity of <strong>Indian homemade meals</strong>. This creates challenges for:</p><ul><li>Diet planning</li><li>Diabetes management</li><li>Weight loss journeys</li><li>Athlete nutrition</li><li>Personalized diet coaching</li></ul><h3>Indian Food Calorie Prediction — ML + FastAPI + Docker</h3><p>An end-to-end machine learning system that predicts <strong>calorie values of Indian dishes</strong> using a regression model and exposes the prediction service through a <strong>FastAPI REST API</strong>.</p><p>This project answers one simple question:</p><p><strong>“Given the nutrient values, how many calories does this food contain?”</strong></p><h3>What the Project Does</h3><p>This system accepts macro and micro-nutrient values of a dish as input:</p><p>Nutrient Examples Macros Fat, Carbs, Protein Fats Composition Saturated, Mono, Poly Fat Minerals Iron, Zinc, Copper, Magnesium Vitamins A, B Complex, C, D, E, K</p><p>It returns the estimated <strong>nutrition density</strong>— giving actionable insights into nutrition density, portion planning, and diet optimization.</p><h3>Machine Learning Pipeline</h3><p>This project is designed to be clean, scalable, and production-oriented.</p><h3>Steps Taken</h3><ul><li>Dataset cleanup and preprocessing</li><li>Handling missing micro-nutrient values</li><li>Exploratory data analysis and correlations</li><li>Feature selection using importance scores</li><li>Model benchmarking across regression algorithms</li><li>Final deployment using <strong>XGBoost Regressor</strong></li></ul><p>Why XGBoost?<br>It handled non-linear relationships extremely well and offered lower error in prediction compared to baseline models.</p><p>The model was exported using <strong>Pickle</strong> to be consumed by the API for real-time inference.</p><h3>FastAPI — Serving ML Model as a REST API</h3><p>The backend is built using <strong>FastAPI</strong>, one of the fastest Python frameworks designed for production ML apps.</p><h3>Available Endpoints</h3><p>Method Route Purpose GET / Health check POST /predict Predict calories</p><p>FastAPI automatically generates beautiful interactive documentation:<br> ➡ /docs – Swagger UI<br> ➡ /redoc – ReDoc UI</p><p>Example prediction request:</p><pre>{<br>  &quot;fat&quot;: 10.5,<br>  &quot;saturated_fats&quot;: 3.2,<br>  &quot;carbohydrates&quot;: 25,<br>  &quot;protein&quot;: 6,<br>  &quot;vitamin_c&quot;: 10,<br>  &quot;iron&quot;: 1.2,<br>  &quot;calcium&quot;: 60<br>}</pre><p>Response:</p><pre>{<br>  &quot;prediction&quot;: 245.73<br>}</pre><h3>Dockerizing the API for Deployment</h3><p>To make this ML API <strong>portable, scalable and deployment-ready</strong>, the service is containerized using Docker.</p><h3>Run using Docker</h3><pre>docker build -t food-calorie-api .<br>docker run -p 8000:8000 food-calorie-api</pre><p>Now the service is accessible at:</p><p>➡ http://localhost:8000<br>➡ <a href="http://localhost:8000/docs">http://localhost:8000/docs</a></p><h3>Running Locally (Without Docker)</h3><pre>pipenv install<br>pipenv shell<br>uvicorn predict:app --reload --port 8000</pre><h3>Why This Project Is Useful</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*bpd-cuDLU2nj7MQsTz-qXQ.png" /></figure><p>As health-tracking grows in India, <strong>region-specific food datasets</strong> are going to play a huge part in personalized healthcare AI.</p><h3>Technology Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*Da5lRnYfvV8wIUtO64rJZA.png" /></figure><h3>Final Thoughts</h3><p>This project blends <strong>data science + API engineering + deployment</strong>, making it a practical end-to-end portfolio project.</p><p>It’s not just about predictions — it’s about creating AI capability that works for culturally relevant challenges like <strong>Indian food nutrition</strong>.</p><p>If you are exploring ML deployment, nutrition AI, or building health-tech apps, this is a great foundation.</p><p>#MachineLearning #FastAPI #DataScience #HealthTech #Python #XGBoost #MLOps</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=088d1f67ab6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Made Simple-From Images to Predictions (Step-by-Step Guide) | Part 2]]></title>
            <link>https://medium.com/@poojashreechoudhury7/deep-learning-made-simple-from-images-to-predictions-step-by-step-guide-part-2-53edc1a66823?source=rss-6b879c2525c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/53edc1a66823</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[dropout-regularization]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[data-augmentation]]></category>
            <dc:creator><![CDATA[Pooja]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 10:32:06 GMT</pubDate>
            <atom:updated>2025-11-26T10:32:06.116Z</atom:updated>
            <content:encoded><![CDATA[<p>In <strong>Part 1</strong>, we built a clothing image classifier using:</p><ul><li>A pre-trained <strong>Xception</strong> model</li><li>Transfer learning</li><li>Images resized to <strong>150×150</strong></li><li>Custom dense layers on top</li></ul><p>We reached around <strong>80–85% accuracy</strong> without huge compute.</p><p>In <strong>Part 2</strong>, we’ll go deeper and cover:</p><ol><li><strong>Data Augmentation</strong> — increasing dataset variety</li><li><strong>Regularization &amp; Dropout</strong> — preventing overfitting</li><li><strong>Training a Larger Model with 299×299 Images</strong></li><li><strong>Using the Model</strong> — evaluating on test data and making predictions</li></ol><h3>1. Data Augmentation — Teaching Your Model to “See” More</h3><p>In Part 1, we noticed something common in deep learning:</p><blockquote><em>Training accuracy increases fast, but validation accuracy lags behind.</em></blockquote><p>This means the model is <strong>overfitting</strong> — memorizing examples instead of learning concepts.</p><p><strong>Data augmentation</strong> helps fix this by artificially expanding your dataset.</p><h4>What is Data Augmentation?</h4><p>It means taking one training image and creating multiple <strong>modified versions</strong>:</p><ul><li>Rotated</li><li>Shifted</li><li>Zoomed</li><li>Flipped</li><li>Brightness-adjusted</li><li>Slightly distorted</li></ul><p>These aren’t completely new images — just realistic variations of the existing ones.</p><p>The model learns <strong>general patterns</strong>, not exact pixel locations.</p><p>Common Types of Augmentation</p><ul><li>Rotation</li><li>Width/height shift</li><li>Zoom</li><li>Shear (slanting the image)</li><li>Brightness/contrast adjustments</li><li>Vertical/horizontal flips</li></ul><p>This makes the model robust to real-world variation.</p><h4>Keras Implementation</h4><pre>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br>from tensorflow.keras.applications.xception import preprocess_input<br><br>train_gen = ImageDataGenerator(<br>    preprocessing_function=preprocess_input,<br>    rotation_range=30,<br>    width_shift_range=10,<br>    height_shift_range=10,<br>    shear_range=10,<br>    zoom_range=0.1,<br>    vertical_flip=True<br>)</pre><p>Validation data <strong>should not</strong> be augmented.</p><h3>2. Regularization &amp; Dropout — Preventing the Model From Overfitting</h3><p>Data augmentation helps the input side, but overfitting can also happen inside the network.</p><p>That’s where <strong>regularization</strong> comes in.</p><h4><strong>What Is Regularization?</strong></h4><p>Regularization refers to techniques that teach the model to:</p><ul><li>Avoid memorizing the training data</li><li>Learn simpler, more general patterns</li><li>Perform better on unseen images</li></ul><p>Common regularization techniques include:</p><ul><li>Dropout</li><li>Early stopping</li><li>Data augmentation</li></ul><p>The most common and powerful one in neural networks is <strong>Dropout</strong>.</p><h4>Dropout — The Most Effective Regularization Technique</h4><p>Dropout randomly turns OFF some neurons during training.</p><p>If dropout = 0.2:</p><ul><li>20% of neurons in that layer are disabled</li><li>Each batch uses a different random set</li><li>At inference time, all neurons are active</li></ul><p>This prevents the network from relying too heavily on particular neurons, forcing it to learn more distributed, robust features.</p><h4><strong>Why Dropout Works</strong></h4><p>It stops the model from memorizing:</p><ul><li>Backgrounds</li><li>Shadow patterns</li><li>Exact pixel combinations</li></ul><p>Instead, the model must learn <strong>general features</strong> like shape and structure.</p><h4><strong>Example of Dropout in Our Model</strong></h4><pre>inner = keras.layers.Dense(size_inner, activation=&#39;relu&#39;)(vectors)<br>drop = keras.layers.Dropout(droprate)(inner)<br>outputs = keras.layers.Dense(10)(drop)</pre><p>Typical values:</p><ul><li>0.1–0.3 → light regularization</li><li>0.3–0.5 → moderate</li><li>0.5–0.7 → strong</li></ul><p>For this dataset:</p><pre>droprate = 0.2</pre><h4>Summary: Why Regularization Matters</h4><p>Regularization helps your model:</p><ul><li>Generalize better</li><li>Avoid memorizing noise</li><li>Perform consistently on new data</li><li>Reduce validation overfitting</li><li>Achieve higher test accuracy</li></ul><p>Together with augmentation, it makes your model much more reliable.</p><h3>3. Training a Larger Model with 299×299 Images</h3><p>In Part 1 we trained with <strong>150×150 images</strong> for speed.</p><p>Now we upgrade to <strong>299×299</strong>, which matches the native input size of Xception.</p><p>Larger images → more detail → better accuracy.</p><h4>Model Function Supporting Different Image Sizes</h4><pre>from tensorflow import keras<br>from tensorflow.keras.applications.xception import Xception<br><br><br>def make_model(input_size=150, learning_rate=0.01, size_inner=100, droprate=0.5):<br>    base_model = Xception(<br>        weights=&#39;imagenet&#39;,<br>        include_top=False,<br>        input_shape=(input_size, input_size, 3)<br>    )<br>    base_model.trainable = False<br>    inputs = keras.Input(shape=(input_size, input_size, 3))<br>    base = base_model(inputs, training=False)<br>    vectors = keras.layers.GlobalAveragePooling2D()(base)<br>    inner = keras.layers.Dense(size_inner, activation=&#39;relu&#39;)(vectors)<br>    drop = keras.layers.Dropout(droprate)(inner)<br>    outputs = keras.layers.Dense(10)(drop)<br>    model = keras.Model(inputs, outputs)<br>    optimizer = keras.optimizers.Adam(learning_rate=learning_rate)<br>    loss = keras.losses.CategoricalCrossentropy(from_logits=True)<br>    model.compile(optimizer=optimizer, loss=loss, metrics=[&#39;accuracy&#39;])<br>    return model</pre><h4>Training with 299×299 + Augmentation</h4><pre>input_size = 299<br><br>train_gen = ImageDataGenerator(<br>    preprocessing_function=preprocess_input,<br>    shear_range=10,<br>    zoom_range=0.1,<br>    horizontal_flip=True<br>)</pre><p>Validation data remains clean.</p><h4>Saving the Best Model</h4><pre>checkpoint = keras.callbacks.ModelCheckpoint(<br>    &#39;xception_v4_1_{epoch:02d}_{val_accuracy:.3f}.h5&#39;,<br>    save_best_only=True,<br>    monitor=&#39;val_accuracy&#39;,<br>    mode=&#39;max&#39;<br>)</pre><h4>Training</h4><pre>learning_rate = 0.0005<br>size = 100<br>droprate = 0.2<br><br>model = make_model(<br>    input_size=input_size,<br>    learning_rate=learning_rate,<br>    size_inner=size,<br>    droprate=droprate<br>)<br>history = model.fit(<br>    train_ds,<br>    epochs=50,<br>    validation_data=val_ds,<br>    callbacks=[checkpoint]<br>)</pre><p>Results:</p><ul><li>Training accuracy → very high</li><li>Validation accuracy → ~88%</li><li>Better than the earlier 84%</li></ul><p>Larger images + regularization = stronger model.</p><h3>4. Using the Model: Evaluation &amp; Predictions</h3><p><strong>Loading the Model &amp; Test Data</strong></p><pre>test_ds = test_gen.flow_from_directory(<br>    &#39;./clothing-dataset-small/test&#39;,<br>    target_size=(299, 299),<br>    batch_size=32,<br>    shuffle=False<br>)<br><br>model = keras.models.load_model(&#39;xception_v1_09_0.839.h5&#39;)</pre><p><strong>Evaluating on Test Set</strong></p><pre>model.evaluate(test_ds)</pre><p>Example output:</p><pre>loss: 0.71 - accuracy: 0.80</pre><p>This is a good sign — the model generalizes well.</p><h4>Making Predictions on a Single Image</h4><pre>img = load_img(path, target_size=(299, 299))<br>x = np.array(img)<br>X = np.array([x])<br>X = preprocess_input(X)<br><br>pred = model.predict(X)</pre><p>Map logits to class names:</p><pre>classes = [...]<br>result = dict(zip(classes, pred[0]))</pre><p>Convert to probabilities (optional):</p><pre>probs = tf.nn.softmax(pred[0]).numpy()</pre><p>Output example:</p><pre>pants: 0.91<br>t-shirt: 0.02<br>skirt: 0.03</pre><p>Prediction → <strong>pants</strong>.</p><h3>Final Summary</h3><p>In this part, we Learned:</p><blockquote><strong>data augmentation</strong> and how it helps the model generalize<br>Added <strong>regularization and dropout</strong> to fight overfitting<br>Trained a <strong>larger 299×299 Xception model</strong> for better accuracy<br>Loaded and evaluated the model on test data<br>Made predictions for individual images</blockquote><p><strong>#DeepLearning #MachineLearning #ComputerVision #TensorFlow #Keras #NeuralNetworks #TransferLearning #DataAugmentation #Regularization #Dropout #ImageClassification #AI #DataScience</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53edc1a66823" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Made Simple from Images to Predictions (Step-by-Step Guide)- Part 1]]></title>
            <link>https://medium.com/@poojashreechoudhury7/deep-learning-made-simple-from-images-to-predictions-step-by-step-guide-part-1-86cf59a88e09?source=rss-6b879c2525c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/86cf59a88e09</guid>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Pooja]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 08:01:03 GMT</pubDate>
            <atom:updated>2025-11-23T08:01:03.851Z</atom:updated>
            <content:encoded><![CDATA[<p>Deep Learning has transformed the world of computer vision. From identifying objects in photos to powering recommendation systems, it’s everywhere — and easier to learn than ever.</p><p>In this beginner-friendly guide, we’ll walk through:</p><ul><li>How Deep Learning works</li><li>Why Convolutional Neural Networks (CNNs) are so powerful</li><li>What Transfer Learning is</li><li>How to build an image classifier using the <strong>Xception</strong> model</li><li>A practical step-by-step workflow you can apply to any image dataset</li></ul><p>We’ll use a real example:</p><blockquote><em>Predicting clothing categories (t-shirt, skirt, dress, hat, pants, etc.) from images.</em></blockquote><p>Let’s break it down in the simplest possible way.</p><h3>What is Deep Learning?</h3><p>Deep Learning is a branch of Machine Learning that uses <strong>neural networks with many layers</strong>. These networks automatically learn patterns from raw data — no manual feature engineering required.</p><p>Instead of telling the model:<br> “Look at the shape, the color, the texture…”</p><p>We simply give it the images, and the model learns:</p><ul><li>edges</li><li>curves</li><li>shades</li><li>textures</li><li>complex shapes</li><li>whole objects</li></ul><blockquote><strong>Example Goal</strong></blockquote><blockquote><strong>Input:</strong> An image of clothing<br><strong>Output:</strong> Category → t-shirt, pants, shoes, skirt, etc.</blockquote><p>This is known as <strong>image classification</strong>.</p><h3>Why Use Deep Learning for Images?</h3><p>Every image is made of <strong>pixels</strong>. Each pixel has 3 color values:</p><pre>(R, G, B)</pre><p>So an image of size <strong>299 × 299</strong> becomes a 3D tensor:</p><pre>(299, 299, 3)</pre><p>Deep learning models — especially <strong>CNNs</strong> — understand, extract, and combine these pixel patterns far better than traditional algorithms.</p><p>To load and process images, we commonly use:</p><ul><li><strong>Pillow (PIL)</strong> — for image loading</li><li><strong>NumPy</strong> — for pixel data</li><li><strong>TensorFlow + Keras</strong> — for model training</li></ul><h3>Using Pre-Trained Models: Transfer Learning (Xception Model)</h3><p>Training a model from scratch on millions of images is expensive. Instead, we reuse a model that is already trained on a huge dataset like <strong>ImageNet</strong>.</p><p>This technique is called <strong>Transfer Learning</strong>.</p><p>The model we use here is <strong>Xception</strong>, a popular CNN architecture trained on 1,000 ImageNet classes.</p><h3>Why transfer learning works</h3><p>It means: <strong>Reuse a pre-trained model → Replace last few layers → Train it for your dataset.</strong></p><ul><li>All early CNN layers learn <strong>generic patterns</strong>: edges, shapes, colors.</li><li>Later layers learn <strong>task-specific patterns</strong>.</li><li>So we keep the convolution layers (generic) and replace the top dense layers (task-specific).</li></ul><h3><strong>Step 1: Load and Resize Images</strong></h3><p>We load images using:</p><pre>from tensorflow.keras.preprocessing.image import load_img<br><br>img = load_img(&quot;tshirt.jpg&quot;, target_size=(150, 150))</pre><p>Resizing is important because CNNs expect fixed dimensions like <strong>150×150</strong> or <strong>299×299</strong>.</p><p>Converted images become numeric arrays with values between 0 and 255.</p><h3><strong>Step 2: Build a Convolutional Neural Network (CNN)</strong></h3><p>A CNN has two major parts:</p><p><strong><em>Convolutional Layers</em></strong></p><p>These layers use <strong>filters</strong> (small 3×3 or 5×5 windows) that slide across the image and detect patterns like:</p><ul><li>edges</li><li>curves</li><li>textures</li></ul><p>Applying each filter generates a <strong>feature map</strong> — a representation of how strongly the image matches that filter.</p><p><strong><em>Dense Layers</em></strong></p><p>After convolution layers compress the image into a vector, dense layers will produce the final prediction.</p><p>For example, a 2048-length vector becomes a <strong>10-class softmax output</strong> (for our 10 clothing categories).</p><h3>Step 3: Using ImageDataGenerator to Load Datasets</h3><p>Keras’s <strong>ImageDataGenerator</strong> makes it easy to:</p><ul><li>load images from folders</li><li>apply preprocessing</li><li>manage batches</li></ul><p>Example:</p><pre>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br><br>train_gen = ImageDataGenerator(preprocessing_function=preprocess_input)<br><br>train_ds = train_gen.flow_from_directory(<br>    &#39;./clothing-dataset-small/train&#39;,<br>    target_size=(150, 150),<br>    batch_size=32<br>)This loads 10 classes like t-shirt, hat, skirt, pants, etc.</pre><h3>Step 4: Freezing the Pre-Trained Base Model</h3><p>We keep Xception’s convolution layers unchanged:</p><pre>base_model.trainable = False</pre><p>This prevents overwriting the valuable ImageNet-learned filters.</p><h3>Step 5: Add Your Own Dense Layers</h3><p>To adapt Xception for our clothing dataset:</p><pre>import tensorflow as tf<br>from tensorflow import keras<br><br>vectors = keras.layers.GlobalAveragePooling2D()(base)<br>outputs = keras.layers.Dense(10)(vectors)  # 10 clothing categories<br><br>model = keras.Model(inputs, outputs)</pre><p>The final layer outputs <strong>10 raw scores (logits)</strong>, one for each class.</p><p>We then compile the model using:</p><pre>loss = keras.losses.CategoricalCrossentropy(from_logits=True)</pre><h3>Step 6: Training the Model</h3><p>Training is done via:</p><pre>model.fit(train_ds, epochs=10, validation_data=val_ds)</pre><p>You will see training accuracy improve rapidly, but validation accuracy grows slowly and may plateau — indicating overfitting after a few epochs.</p><h3>Understanding Learning Rate</h3><p>Learning rate controls <strong>how fast the model learns</strong>.</p><ul><li>Too high → unstable</li><li>Too low → slow and gets stuck</li><li>Medium → best</li></ul><p>Experiments show <strong>0.001</strong> works best for this dataset.</p><h3>Step 7: Using Callbacks (Checkpointing)</h3><p>We save the best model automatically using ModelCheckpoint:</p><pre>checkpoint = keras.callbacks.ModelCheckpoint(<br>    &#39;xception_v1_{epoch:02d}_{val_accuracy:.3f}.h5&#39;,<br>    save_best_only=True,<br>    monitor=&#39;val_accuracy&#39;,<br>    mode=&#39;max&#39;<br>)</pre><p>This prevents losing the best version when accuracy varies across epochs.</p><h3>Step 8: Adding More Layers (Optional Improvement)</h3><p>Adding extra dense layers between the vector representation and the final output can improve performance:</p><pre>inner = keras.layers.Dense(100, activation=&#39;relu&#39;)(vectors)<br>outputs = keras.layers.Dense(10)(inner)</pre><p>Experiments show <strong>one inner layer with 100 units</strong> works best.</p><h3>Final Summary</h3><p>Here’s the complete journey from image → prediction:</p><ol><li>Load and resize images</li><li>Use a pre-trained CNN (Xception)</li><li>Freeze convolution layers</li><li>Add custom dense layers</li><li>Load data using ImageDataGenerator</li><li>Train with categorical crossentropy</li><li>Tune learning rate</li><li>Use callbacks to save best model</li><li>Optionally add more dense layers</li></ol><p>This approach gives <strong>80–85% accuracy</strong> with minimal training and without huge GPU resources.</p><p>#DeepLearning #MachineLearning #ComputerVision #TensorFlow #Keras #TransferLearning #NeuralNetworks #ImageClassification #ArtificialIntelligence #DataScience #Python #CNN #Xception #ModelTraining #MLBeginners</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86cf59a88e09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Medical Insurance Costs with Machine Learning — From Data to FastAPI Deployment]]></title>
            <link>https://medium.com/@poojashreechoudhury7/predicting-medical-insurance-costs-with-machine-learning-from-data-to-fastapi-deployment-98ea95671fd4?source=rss-6b879c2525c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/98ea95671fd4</guid>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[capstone-project]]></category>
            <dc:creator><![CDATA[Pooja]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 08:40:24 GMT</pubDate>
            <atom:updated>2025-11-09T08:40:24.461Z</atom:updated>
            <content:encoded><![CDATA[<h3>Predicting Medical Insurance Costs with Machine Learning — From Data to FastAPI Deployment</h3><h3>Introduction</h3><p>Why do some people pay more for medical insurance than others?<br>It’s no mystery — insurance companies rely on factors like <strong>age</strong>, <strong>BMI</strong>, <strong>smoking habits</strong>, and <strong>number of children</strong> to estimate risk and set premium amounts.</p><p>But instead of relying on traditional actuarial methods, can we <em>predict</em> these costs using <strong>machine learning</strong>?</p><p>That’s what this project does — an <strong>end-to-end Medical Insurance Cost Prediction system</strong> built using Python and machine learning, deployed as a <strong>FastAPI service</strong>, and containerized using <strong>Docker</strong> for portability and scalability.</p><h3>Project Overview</h3><p><strong>Goal:</strong><br>Predict an individual’s <strong>annual medical insurance charges</strong> using demographic and health-related factors:</p><ul><li>Age</li><li>Gender</li><li>BMI (Body Mass Index)</li><li>Number of children</li><li>Smoking status</li><li>Residential region</li></ul><p><strong>Tech Stack:</strong></p><ul><li>Python, Pandas, NumPy, Scikit-Learn, XGBoost</li><li>FastAPI (for deployment)</li><li>Docker (for containerization)</li></ul><h3>Step 1: Exploratory Data Analysis (EDA)</h3><p>I began with the <strong>Insurance dataset</strong>, which contains demographic and health details of individuals along with their insurance costs.</p><h3>EDA Steps</h3><ul><li>Checked for <strong>missing values</strong> and <strong>data types</strong></li><li>Analyzed the <strong>distribution</strong> of charges</li><li>Explored <strong>correlations</strong> between features</li><li>Visualized how <strong>smoking</strong> and <strong>BMI</strong> influence cost</li></ul><h3>Insights</h3><ul><li><strong>Smokers</strong> pay the highest premiums — on average <strong>3× more</strong> than non-smokers</li><li><strong>BMI &gt; 30</strong> (obese range) increases cost significantly</li><li><strong>Age</strong> shows a linear increase with charges</li><li><strong>Gender</strong> and <strong>Region</strong> show very little impact</li></ul><blockquote>Lifestyle choices like smoking and maintaining a healthy BMI are the strongest cost drivers.</blockquote><h3>Step 2: Model Training</h3><p>Once the data was clean and analyzed, I trained multiple regression models to identify the best performer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*cICL2DlwRZsF6T8S5PspmA.png" /></figure><p>The <strong>XGBoost Regressor</strong> performed best with the lowest prediction error and highest accuracy.</p><p>To make it reusable, I exported both:</p><ul><li>model.pkl → trained model</li><li>dv.pkl → DictVectorizer used for feature transformation</li></ul><p>Both files were saved using Python’s built-in pickle module.</p><h3>Step 3: Training Script (train.py)</h3><p>Here’s a simplified version of my model training code:</p><pre>import pandas as pd<br>import pickle<br>from sklearn.feature_extraction import DictVectorizer<br>from xgboost import XGBRegressor<br><br># Load dataset<br>df = pd.read_csv(&quot;insurance.csv&quot;)<br># Split data<br>X = df.drop(&quot;charges&quot;, axis=1)<br>y = df[&quot;charges&quot;]<br># Convert categorical data<br>dv = DictVectorizer(sparse=False)<br>X_encoded = dv.fit_transform(X.to_dict(orient=&quot;records&quot;))<br># Train model<br>model = XGBRegressor(n_estimators=200, max_depth=5, learning_rate=0.1, random_state=42)<br>model.fit(X_encoded, y)<br># Save model and DictVectorizer<br>with open(&quot;model.pkl&quot;, &quot;wb&quot;) as f_out:<br>    pickle.dump(model, f_out)<br>with open(&quot;dv.pkl&quot;, &quot;wb&quot;) as f_out:<br>    pickle.dump(dv, f_out)<br>print(&quot;Model training complete! Artifacts saved successfully.&quot;)</pre><p>This script makes it easy for anyone to retrain the model by simply running:</p><pre>python train.py</pre><h3>Step 4: Building the FastAPI Prediction Service</h3><p>Once the model was trained and saved, I created a <strong>FastAPI</strong> web service (predict.py) to make real-time predictions.</p><pre>from fastapi import FastAPI<br>import pickle<br><br># Load model and DictVectorizer<br>with open(&quot;model.pkl&quot;, &quot;rb&quot;) as f_in:<br>    model = pickle.load(f_in)<br>with open(&quot;dv.pkl&quot;, &quot;rb&quot;) as f_in:<br>    dv = pickle.load(f_in)<br>app = FastAPI()<br>@app.post(&quot;/predict&quot;)<br>def predict(data: dict):<br>    X = dv.transform([data])<br>    prediction = model.predict(X)[0]<br>    return {&quot;Predicted Insurance Cost&quot;: round(float(prediction), 2)}</pre><h3>Example Input</h3><pre>{<br>  &quot;age&quot;: 32,<br>  &quot;sex&quot;: &quot;male&quot;,<br>  &quot;bmi&quot;: 27.8,<br>  &quot;children&quot;: 1,<br>  &quot;smoker&quot;: &quot;no&quot;,<br>  &quot;region&quot;: &quot;southwest&quot;<br>}</pre><h3>Example Output</h3><pre>{&quot;Predicted Insurance Cost&quot;: 4567.32}</pre><p>This allows users to send JSON requests and get predictions instantly.<br>FastAPI automatically generates an interactive Swagger UI at /docs, making it easy to test.</p><h3>Step 5: Containerization with Docker</h3><p>To make the API portable and deployable anywhere, I containerized the entire application using <strong>Docker</strong>.</p><p>Here’s the Dockerfile:</p><pre>FROM python:3.10<br>WORKDIR /app<br>COPY . /app<br>RUN pip install --no-cache-dir -r requirements.txt<br>EXPOSE 8000<br>CMD [&quot;uvicorn&quot;, &quot;predict:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><h3>Build and Run the Container</h3><pre>docker build -t insurance-predictor .<br>docker run -p 8000:8000 insurance-predictor</pre><p>Once running, open http://localhost:8000/docs to test your API inside Docker.</p><h3>Project Structure</h3><pre>Medical-Insurance-Cost-Prediction<br>├── insurance.csv<br>├── Medical Insurance Cost Prediction.ipynb<br>├── train.py<br>├── predict.py<br>├── model.pkl<br>├── dv.pkl<br>├── requirements.txt<br>├── Dockerfile<br>└── README.md</pre><p>Each component plays a critical role:</p><ul><li><strong>EDA Notebook</strong> → Exploratory analysis &amp; model comparison</li><li><strong>train.py</strong> → Model training and artifact export</li><li><strong>predict.py</strong> → FastAPI service</li><li><strong>Dockerfile</strong> → Containerization</li><li><strong>README.md</strong> → Documentation</li></ul><h3>Key Learnings</h3><ul><li><strong>EDA provides the foundation</strong> — understanding feature relationships before modeling is crucial.</li><li><strong>Multiple model comparison matters</strong> — XGBoost outperformed simpler models.</li><li><strong>Deployment turns a notebook into a product</strong> — FastAPI makes this easy.</li><li><strong>Containerization ensures consistency</strong> — “works everywhere” means no setup headaches.</li><li><strong>Documentation matters</strong> — a clean, reproducible repo makes your work professional.</li></ul><h3>Conclusion</h3><p>This project showcases a <strong>complete machine learning lifecycle</strong> — from data to deployment:<br> ✔ Data Cleaning and EDA<br> ✔ Model Training with XGBoost<br> ✔ FastAPI Prediction Service<br> ✔ Docker Containerization</p><p>It’s not just a model — it’s a production-ready pipeline that demonstrates practical ML engineering skills.</p><p>#MachineLearning #DataScience #Python #FastAPI #Docker #MLDeployment #XGBoost #EndToEndML #Regression #PortfolioProject</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98ea95671fd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Decision Trees to Power Ensembles — Random Forest & XGBoost Explained (Step-by-Step Guide)]]></title>
            <link>https://medium.com/@poojashreechoudhury7/from-decision-trees-to-power-ensembles-random-forest-xgboost-explained-step-by-step-guide-e1613522b66b?source=rss-6b879c2525c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1613522b66b</guid>
            <category><![CDATA[model-finetuning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Pooja]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 07:21:56 GMT</pubDate>
            <atom:updated>2025-11-05T07:21:56.888Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Decision Trees to Power Ensembles — Random Forest &amp; XGBoost Explained (Step-by-Step Guide)</h3><p>In our previous post, we built a <strong>Credit Risk Scoring Model</strong> using a simple <strong>Decision Tree</strong>.<br>It worked — but not perfectly. Our model had an <strong>AUC around 0.74</strong> and was prone to <strong>overfitting</strong> (too good on training, weak on test data).</p><p>So now it’s time to level up — and explore two of the most powerful ensemble methods in modern machine learning:</p><ul><li><strong>Random Forest</strong> — many trees working together</li></ul><p>A <strong>Random Forest</strong> is like a group of decision trees working as a team.<br>Each tree looks at the data from a slightly different angle — trained on random samples and random features.</p><ul><li><strong>XGBoost</strong> — smarter trees learning from each other</li></ul><p>Instead of growing all trees independently, it builds them <strong>sequentially</strong> — one after another. Each new tree focuses on the <strong>errors</strong> made by the previous trees, learning from mistakes and correcting them step by step.<br>Over time, this process creates a highly optimized model that gets smarter with every iteration.</p><p>By the end of this post, you’ll know exactly:</p><ul><li>How these algorithms work</li><li>How to implement them in Python</li><li>How they differ in performance and purpose</li></ul><h3>Random Forest — The Power of Many Trees</h3><p>A <strong>Decision Tree</strong> makes predictions by asking a series of if-else questions. But what if that one tree is biased or too specific to training data?</p><p>That’s where <strong>Random Forest</strong> shines — it’s an <strong>ensemble of many Decision Trees</strong>, each trained slightly differently.</p><p>Instead of trusting one tree, it <strong>takes a vote</strong> among many trees and averages their predictions.<br> This reduces variance and gives much more stable results.</p><p>Think of it like this:</p><blockquote><em>“One tree can make a mistake. A forest of trees can’t all be wrong.”</em></blockquote><h4>The Goal</h4><p>We’ll continue the same <strong>Credit Risk Scoring</strong> task:</p><blockquote><em>Predict whether a customer will repay the loan (</em><em>OK = 0) or default (</em><em>DEFAULT = 1).</em></blockquote><h4>Step 1: Import Libraries</h4><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import roc_auc_score</pre><p>We’ll use the same cleaned and preprocessed data we used for the Decision Tree model.</p><h4>Step 2: Train a Random Forest Model</h4><pre>rf = RandomForestClassifier(<br>    n_estimators=10,      # number of trees<br>    max_depth=10,         # maximum depth per tree<br>    random_state=11<br>)<br>rf.fit(X_train, y_train)</pre><p>Here:</p><ul><li>n_estimators → Number of trees in the forest<br>This controls <strong>how many decision trees</strong> the Random Forest will build.</li><li>max_depth → Maximum depth of each tree<br>Determines <strong>how deep each tree can grow</strong> (how many splits it can make).</li><li>random_state<strong> → </strong>Reproducibility control<br> Sets the <strong>seed</strong> for random number generation.</li></ul><h4>Step 3: Evaluate Model Performance</h4><pre>y_pred = rf.predict_proba(X_val)[:, 1]<br>roc_auc_score(y_val, y_pred)</pre><p><strong>Validation AUC ≈ 0.78–0.80</strong><br>That’s a clear improvement over our single Decision Tree (~0.74 AUC).</p><h4>Step 4: Why Random Forest Works</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*tFUt12FCO61s57_OgaCPGA.png" /></figure><p>This randomness gives <strong>diversity</strong> among trees → leading to <strong>lower overfitting</strong> and <strong>better generalization</strong>.</p><h4>Step 5: Tuning Random Forest</h4><p>Try different parameters for better performance:</p><pre>for n in [10, 50, 100, 200]:<br>    rf = RandomForestClassifier(n_estimators=n, random_state=11)<br>    rf.fit(X_train, y_train)<br>    y_pred = rf.predict_proba(X_val)[:, 1]<br>    print(n, roc_auc_score(y_val, y_pred))</pre><p>You’ll usually see the AUC stabilizing after ~100 trees.</p><h4>Step 6: Feature Importance</h4><p>One great advantage of tree-based models: they tell you <strong>which features matter most</strong>.</p><pre>import pandas as pd<br><br>features = dv.get_feature_names_out()<br>importances = rf.feature_importances_<br>pd.Series(importances, index=features).sort_values(ascending=False).head(10)</pre><p>Typical top predictors:</p><ul><li>Credit records (records=yes)</li><li>Assets</li><li>Income</li><li>Loan amount</li></ul><h4>Random Forest Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*o4RQ7_D5TkoCdG_01VXeYw.png" /></figure><p><em>More accurate and robust than Decision Tree<br>Slightly less interpretable due to multiple trees</em></p><h3>XGBoost — Smarter Trees That Learn from Mistakes</h3><p>Now that we understand Random Forest, let’s look at its advanced cousin — <strong>XGBoost</strong>.</p><h4>What Is XGBoost?</h4><p><strong>XGBoost</strong> stands for <em>Extreme Gradient Boosting</em>.<br>It’s not just a forest — it’s a sequence of trees built one after another.</p><p>Each new tree tries to <strong>fix the errors</strong> made by the previous trees.</p><p>Think of it as:</p><blockquote><em>“Each new tree learns what the last tree got wrong.”</em></blockquote><h4>How It’s Different from Random Forest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*6BdnJKPUnCT912Z_nNK9gQ.png" /></figure><h4>Step 1: Import XGBoost</h4><pre>import xgboost as xgb<br>from sklearn.metrics import roc_auc_score<br><br>dtrain = xgb.DMatrix(X_train, label=y_train)<br>dval = xgb.DMatrix(X_val, label=y_val)</pre><h4>Step 2: Set Hyperparameters</h4><pre>xgb_params = {<br>    &#39;eta&#39;: 0.3,              # learning rate<br>    &#39;max_depth&#39;: 6,          # tree depth<br>    &#39;min_child_weight&#39;: 1,   # min samples per leaf<br>    &#39;objective&#39;: &#39;binary:logistic&#39;,<br>    &#39;eval_metric&#39;: &#39;auc&#39;,<br>    &#39;nthread&#39;: 4,<br>    &#39;seed&#39;: 11<br>}</pre><h4>Step 3: Train the Model</h4><pre>model = xgb.train(<br>    xgb_params,<br>    dtrain,<br>    num_boost_round=200,<br>    evals=[(dval, &#39;validation&#39;)],<br>    verbose_eval=50<br>)</pre><p>Each new tree improves the overall model step-by-step.</p><h4>Step 4: Evaluate Performance</h4><pre>y_pred = model.predict(dval)<br>roc_auc_score(y_val, y_pred)</pre><p><strong>Validation AUC ≈ 0.85–0.87</strong> — the best yet!<br>XGBoost not only improves accuracy but also handles overfitting elegantly with regularization.</p><h4>Step 5: Key Parameters Explained</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*5fTX4jjJnxQDsky_YZ4RhQ.png" /></figure><p>Lower eta → slower learning but more accurate models.</p><h4>Step 6: Feature Importance Visualization</h4><pre>xgb.plot_importance(model, max_num_features=10)<br>plt.show()</pre><p>You’ll usually see:</p><ul><li>Credit record (records=yes)</li><li>Assets</li><li>Income<br> as key predictors again — confirming consistency.</li></ul><h4>Final Comparison</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*dluJsZIlDjvpTT8hg0gUZQ.png" /></figure><h4>Key Takeaways</h4><ul><li><strong>Random Forest</strong>: Reduces overfitting by averaging multiple trees.</li><li><strong>XGBoost</strong>: Improves accuracy by sequentially correcting mistakes.</li><li>Both handle non-linear data and categorical variables well.</li><li>Always tune hyperparameters — they make or break your results.</li></ul><h4>Conclusion</h4><p>From <strong>Decision Trees → Random Forest → XGBoost</strong>, we just built a complete journey from simple interpretable models to cutting-edge ensemble learners.</p><p>Decision Tree — interpretable but prone to overfitting<br>Random Forest — stable and robust<br>XGBoost — fast, accurate, and production-ready</p><p>#MachineLearning #Python #DataScience #CreditRiskScoring #DecisionTrees #RandomForest #XGBoost #EnsembleLearning #ModelTuning #MLProject #ScikitLearn</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1613522b66b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Credit Risk Scoring Model with Decision Trees (Step-by-Step)]]></title>
            <link>https://medium.com/@poojashreechoudhury7/building-a-credit-risk-scoring-model-with-decision-trees-step-by-step-ecc8094f4524?source=rss-6b879c2525c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecc8094f4524</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[credit-risk]]></category>
            <dc:creator><![CDATA[Pooja]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 16:22:02 GMT</pubDate>
            <atom:updated>2025-11-03T16:22:02.048Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Imagine you’re applying for a mobile phone loan at a bank. The bank needs to decide if you can repay the loan or not. Traditionally, they look at your income, job, and other details. But what if we could train a <strong>machine learning model</strong> to automatically predict this — to give each customer a <strong>credit risk score</strong>?</p><p>That’s what we’ll build today — a <strong>Credit Risk Scoring Model</strong> using a <strong>Decision Tree</strong> in Python.</p><h4>The Goal</h4><p>We’ll train a model that predicts whether a customer will:</p><ul><li><strong>OK (0)</strong> → Repay the loan</li><li><strong>DEFAULT (1)</strong> → Fail to repay</li></ul><p>This is a <strong>binary classification problem</strong>.</p><h3>Step 1: Import the Essential Libraries</h3><p>We’ll use Python’s most popular libraries for data and ML tasks.</p><pre>import pandas as pd<br>import numpy as np<br>import seaborn as sns<br>from matplotlib import pyplot as plt<br>%matplotlib inline</pre><ul><li><strong>Pandas &amp; NumPy</strong> → handle and process data.</li><li><strong>Seaborn &amp; Matplotlib</strong> → visualize trends and patterns.</li><li><strong>Scikit-learn</strong> → build our ML model.</li></ul><h3>Step 2: Load and Preview the Dataset</h3><p>We use the dataset from GitHub.</p><pre>data = &#39;https://github.com/gastonstat/CreditScoring/blob/master/CreditScoring.csv&#39;<br>!wget $data<br>df = pd.read_csv(&#39;CreditScoring.csv&#39;)<br>df.head()</pre><p>Each record represents one loan application.<br>Important columns include:</p><ul><li><strong>income</strong>, <strong>assets</strong>, <strong>debt</strong></li><li><strong>home</strong>, <strong>marital</strong>, <strong>records</strong></li><li><strong>status</strong> → Target variable (ok or default)</li></ul><h3>Step 3: Clean Column Names</h3><p>To make the dataset easier to work with:</p><pre>df.columns = df.columns.str.lower()</pre><p>Now all columns follow a uniform lowercase format.</p><h3>Step 4: Decode the Categorical Variables</h3><p>Some columns use numbers instead of words. Let’s map them to readable labels:</p><pre>status_values = {1: &#39;ok&#39;, 2: &#39;default&#39;, 0: &#39;unk&#39;}<br>df.status = df.status.map(status_values)</pre><p>Do the same for:</p><ul><li><strong>home</strong> → rent, owner, parents, etc.</li><li><strong>marital</strong> → single, married, divorced, etc.</li><li><strong>records</strong> → yes/no</li><li><strong>job</strong> → fixed, part-time, freelance, etc.</li></ul><p>After mapping, your data is much clearer and interpretable.</p><h3>Step 5: Handle Missing Values</h3><p>Some numeric columns (like income, assets, debt) contain unrealistic values such as 99999999. These represent missing data.</p><p>Replacing 99999999 with NaN is crucial because leaving unrealistic values would confuse the model — it might treat those as valid high incomes instead of missing data.</p><p>We replace them with NaN:</p><pre>for c in [&#39;income&#39;, &#39;assets&#39;, &#39;debt&#39;]:<br>    df[c] = df[c].replace(99999999, np.nan)</pre><h3>Step 6: Remove Unknown Status</h3><p>We only keep rows where status = ok or default.</p><pre>df = df[df.status != &#39;unk&#39;].reset_index(drop=True)</pre><h3>Step 7: Split the Dataset</h3><p>We now divide the dataset into:</p><ul><li><strong>Training set</strong> → 60%</li><li><strong>Validation set</strong> → 20%</li><li><strong>Test set</strong> → 20%</li></ul><pre>from sklearn.model_selection import train_test_split<br><br>df_full_train, df_test = train_test_split(df, test_size=0.2, random_state=11)<br>df_train, df_val = train_test_split(df_full_train, test_size=0.25, random_state=11)</pre><p>We also encode our target variable:</p><pre>y_train = (df_train.status == &#39;default&#39;).astype(int).values<br>y_val = (df_val.status == &#39;default&#39;).astype(int).values<br>y_test = (df_test.status == &#39;default&#39;).astype(int).values<br><br>del df_train[&#39;status&#39;], df_val[&#39;status&#39;], df_test[&#39;status&#39;]</pre><p>At this stage, our dataset is clean, encoded, and ready for modeling.</p><h4>What Is a Decision Tree?</h4><p>A <strong>Decision Tree</strong> is like a flowchart — each question splits the data until we reach a final decision.</p><p>Example:</p><pre>If records == &quot;yes&quot;:<br>    If job == &quot;part-time&quot;: Default<br>    Else: OK<br>Else:<br>    If assets &gt; 6000: OK<br>    Else: Default</pre><p>This simple tree can predict outcomes logically and visually.</p><h3>Step 8: Create the First Model</h3><pre>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.feature_extraction import DictVectorizer<br>from sklearn.metrics import roc_auc_score<br><br>train_dicts = df_train.fillna(0).to_dict(orient=&#39;records&#39;)<br>dv = DictVectorizer(sparse=False)<br>X_train = dv.fit_transform(train_dicts)</pre><p>Train the model:</p><pre>dt = DecisionTreeClassifier()<br>dt.fit(X_train, y_train)</pre><p>Check performance:</p><pre>val_dicts = df_val.fillna(0).to_dict(orient=&#39;records&#39;)<br>X_val = dv.transform(val_dicts)<br>y_pred = dt.predict_proba(X_val)[:, 1]<br><br>roc_auc_score(y_val, y_pred)</pre><p>Result: ~0.65 AUC — not great!</p><h3>Step 9: Understanding Overfitting</h3><p>When we check the AUC on the <strong>training data</strong>, we get <strong>1.0</strong> — perfect accuracy!</p><p>That’s a over fitting — the model memorized training data but can’t generalize to new cases.</p><h3>Step 10: Fix Overfitting with Depth Control</h3><p>Let’s restrict the tree depth.</p><pre>dt = DecisionTreeClassifier(max_depth=3)<br>dt.fit(X_train, y_train)<br><br>#Train AUC = 0.77<br>#Validation AUC = 0.74</pre><p>Now: Much better! The model generalizes well now.</p><h3>Step 11: Decision Stump (Tiny Tree)</h3><p>A <strong>Decision Stump</strong> is a tree with only one condition (max_depth =1).</p><pre>dt = DecisionTreeClassifier(max_depth=1)<br>dt.fit(X_train, y_train)</pre><p>Even this simple stump gives 0.60 AUC — not bad for a single rule!</p><h3>Step 12: Visualizing the Tree</h3><pre>from sklearn.tree import export_text<br>print(export_text(dt, feature_names=dv.get_feature_names_out().tolist()))</pre><p>Interpretation:</p><ul><li>If <strong>records=no</strong> → likely <strong>DEFAULT</strong></li><li>If <strong>records=yes</strong> → likely <strong>OK</strong></li></ul><h3>Step 13: Tuning Parameters</h3><p>Decision Trees have key tuning parameters:</p><ul><li>max_depth → limits how deep the tree grows</li><li>min_samples_leaf → minimum samples needed in each leaf</li><li>criterion → how impurity is measured (gini or entropy)</li></ul><p>We tune these parameters to balance <strong>simplicity vs accuracy</strong>.</p><h3>Step 14: Understanding the Algorithm</h3><p>Here’s how a decision tree learns:</p><ol><li>Try all possible splits on every feature</li><li>For each split, calculate <strong>impurity</strong> (how mixed the classes are)</li><li>Pick the split that reduces impurity the most</li><li>Repeat recursively for both left and right branches</li><li>Stop when tree depth or purity limits are reached</li></ol><p>This recursive splitting continues until we reach pure or small groups.</p><h3>Final Thoughts</h3><p>Decision Trees are easy to understand and powerful for classification problems.<br>In the <strong>Credit Risk Scoring project</strong>, we used them to:</p><ul><li>Predict customer default risk</li><li>Control overfitting with parameters</li><li>Interpret rules for decision transparency</li></ul><p>In the next stage, we could extend this with <strong>Ensemble Methods</strong> like Random Forest or Gradient Boosting to improve performance even further.</p><p>#MachineLearning #Python #DecisionTrees #CreditRiskScoring #DataScience #Classification #MLProject #ScikitLearn #DataPreparation #ModelTuning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecc8094f4524" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Machine Learning Models — From Notebook to Cloud (Step-by-Step Guide)]]></title>
            <link>https://medium.com/@poojashreechoudhury7/deploying-machine-learning-models-from-notebook-to-cloud-step-by-step-guide-fddedc1a0a7c?source=rss-6b879c2525c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fddedc1a0a7c</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[gunicorn]]></category>
            <category><![CDATA[pipenv]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Pooja]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 08:58:23 GMT</pubDate>
            <atom:updated>2025-11-01T08:58:23.139Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying Machine Learning Models — From Notebook to Cloud (Step-by-Step Guide)</h3><p>Machine Learning is not just about training models — it’s about turning those models into <strong>real-world applications</strong> that deliver value.<br>In this post, we’ll walk through how to <strong>deploy a trained ML model</strong> — starting from a jupyter notebook, turning it into a web service, containerizing it with Docker, and finally deploying it to the <strong>cloud using AWS Elastic Beanstalk</strong>.</p><p>By the end, you’ll understand how to take your local model and make it available as a production-ready API.</p><h3>Overview</h3><p>Imagine we’ve built a <strong>customer churn prediction model</strong> — it predicts whether a customer is likely to leave a subscription-based service.</p><p>We’ll build a simple architecture where:</p><ul><li>The <strong>Marketing Service</strong> collects customer data.</li><li>The <strong>Churn Service</strong> (our model) predicts the churn probability.</li><li>The Marketing Service then decides whether to send a discount or promotional email.</li></ul><p>We’ll use:</p><ul><li><strong>Flask</strong> → to serve our model as a web API</li><li><strong>Pipenv</strong> → to isolate Python dependencies</li><li><strong>Docker</strong> → to containerize the service</li><li><strong>AWS Elastic Beanstalk</strong> → to deploy it in the cloud</li></ul><h3>Step 1: Train and Save the Model</h3><p>We start by training a <strong>Logistic Regression</strong> model using the customer dataset (data-week-3.csv).</p><h3>Data Preparation</h3><pre>import pandas as pd<br>import numpy as np<br>from sklearn.model_selection import train_test_split, KFold<br>from sklearn.feature_extraction import DictVectorizer<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import roc_auc_score<br><br>df = pd.read_csv(&#39;data-week-3.csv&#39;)<br>df.columns = df.columns.str.lower().str.replace(&#39; &#39;, &#39;_&#39;)<br><br># We clean categorical columns, convert numeric values, and split the dataset:<br>df[&#39;churn&#39;] = (df[&#39;churn&#39;] == &#39;yes&#39;).astype(int)<br>df_full_train, df_test = train_test_split(df, test_size=0.2, random_state=1)<br><br># Training Function<br>def train(df_train, y_train, C=1.0):<br>    dicts = df_train.to_dict(orient=&#39;records&#39;)<br>    dv = DictVectorizer(sparse=False)<br>    X_train = dv.fit_transform(dicts)<br>    model = LogisticRegression(C=C, max_iter=1000)<br>    model.fit(X_train, y_train)<br>    return dv, model</pre><p>We use <strong>K-Fold Cross Validation</strong> to validate model performance and get an <strong>AUC of ~0.84</strong>.</p><p>Finally, we train the model on the full data and save it using <strong>Pickle</strong>:</p><pre>import pickle<br><br>dv, model = train(df_full_train, df_full_train.churn.values)<br>with open(&#39;model_C=1.0.bin&#39;, &#39;wb&#39;) as f_out:<br>    pickle.dump((dv, model), f_out)</pre><p>Once the model is trained, we serialize both the <strong>model</strong> and the <strong>DictVectorizer</strong> with pickle so they can be reloaded later.</p><p>Now we have a serialized model file — model_C=1.0.bin.</p><h3>Step 2: Serve the Model with Flask</h3><p>We’ll now wrap our model in a <strong>Flask web service</strong> so that other applications can call it via an API.</p><h3>Simple Flask App Example</h3><p>To start small, here’s a “ping-pong” test:</p><pre>from flask import Flask<br>app = Flask(&#39;ping&#39;)<br><br>@app.route(&#39;/ping&#39;, methods=[&#39;GET&#39;])<br>def ping():<br>    return &quot;PONG&quot;<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(debug=True, host=&#39;0.0.0.0&#39;, port=9696)</pre><p><em>Open a browser and go to </em><em>http://localhost:9696/ping<br>You’ll get back “PONG”.</em></p><h3>Step 3: Build the Prediction API</h3><p>Now let’s build the actual <strong>churn prediction API</strong>.</p><h4>predict.py</h4><pre>import pickle<br>from flask import Flask, request, jsonify<br><br>model_file = &#39;model_C=1.0.bin&#39;<br>with open(model_file, &#39;rb&#39;) as f_in:<br>    dv, model = pickle.load(f_in)<br>app = Flask(&#39;churn&#39;)<br>@app.route(&#39;/predict&#39;, methods=[&#39;POST&#39;])<br>def predict():<br>    customer = request.get_json()<br>    X = dv.transform([customer])<br>    y_pred = model.predict_proba(X)[0, 1]<br>    churn = y_pred &gt;= 0.5<br>    result = {<br>        &#39;churn_probability&#39;: float(y_pred),<br>        &#39;churn&#39;: bool(churn)<br>    }<br>    return jsonify(result)<br>if __name__ == &quot;__main__&quot;:<br>    app.run(debug=True, host=&#39;0.0.0.0&#39;, port=9696)</pre><p>This app takes customer data (in JSON), predicts churn probability, and returns the result.</p><h3>Step 4: Teste Locally</h3><p>We’ll test the API using Python’s requests library:</p><pre>import requests<br><br>url = &#39;http://localhost:9696/predict&#39;<br>customer = {<br>    &quot;gender&quot;: &quot;female&quot;,<br>    &quot;seniorcitizen&quot;: 0,<br>    &quot;partner&quot;: &quot;yes&quot;,<br>    &quot;dependents&quot;: &quot;no&quot;,<br>    &quot;phoneservice&quot;: &quot;no&quot;,<br>    &quot;internetservice&quot;: &quot;dsl&quot;,<br>    &quot;contract&quot;: &quot;month-to-month&quot;,<br>    &quot;paperlessbilling&quot;: &quot;yes&quot;,<br>    &quot;paymentmethod&quot;: &quot;electronic_check&quot;,<br>    &quot;tenure&quot;: 1,<br>    &quot;monthlycharges&quot;: 29.85,<br>    &quot;totalcharges&quot;: 29.85<br>}<br>response = requests.post(url, json=customer).json()<br>print(response)<br><br><br># Output<br># {&#39;churn_probability&#39;: 0.63, &#39;churn&#39;: True}</pre><p>Our model is now responding via an API!</p><h3>Step 5: Prepare for Production</h3><p>Flask is perfect for development, but for <strong>production</strong>, we use a <strong>WSGI server</strong> like <strong>Gunicorn</strong> or <strong>Waitress</strong>.</p><p>Windows:</p><pre>pip install gunicorn<br>gunicorn --bind 0.0.0.0:9696 predict:app<br><br>pip install waitress<br>waitress-serve --listen=0.0.0.0:9696 predict:app</pre><h3>Step 6: Manage Dependencies with Pipenv</h3><p>Each project might use different library versions, so we use <strong>Pipenv</strong> to isolate environments.</p><pre>pip install pipenv<br>pipenv install numpy scikit-learn flask gunicorn<br>pipenv shell</pre><p>You’ll get two files: Pipfile and Pipfile.lock.</p><p>To start the app inside the environment:</p><pre>pipenv run gunicorn --bind 0.0.0.0:9696 predict:app</pre><h3>Step 7: Containerize with Docker</h3><p>Docker helps package the entire application (code + dependencies + environment) into a single portable container.</p><h4>Example Dockerfile</h4><pre>FROM python:3.8.12-slim<br><br>RUN pip install pipenv<br>WORKDIR /app<br>COPY [&quot;Pipfile&quot;, &quot;Pipfile.lock&quot;, &quot;./&quot;]<br>RUN pipenv install --system --deploy<br>COPY [&quot;predict.py&quot;, &quot;model_C=1.0.bin&quot;, &quot;./&quot;]<br>EXPOSE 9696<br>ENTRYPOINT [&quot;gunicorn&quot;, &quot;--bind=0.0.0.0:9696&quot;, &quot;predict:app&quot;]</pre><h4>Build and Run</h4><pre>docker build -t churn-service .<br>docker run -it --rm -p 9696:9696 churn-service</pre><p>Your churn API is now running inside a Docker container!</p><h3>Step 8: Deploy to the Cloud (AWS Elastic Beanstalk)</h3><p>AWS Elastic Beanstalk (EB) makes deployment simple — it manages the infrastructure, scaling, and load balancing for you.</p><h4>Setup</h4><p>Install the Elastic Beanstalk CLI:</p><pre>pipenv install awsebcli --dev<br>pipenv shell</pre><p>Initialize your app:</p><pre>eb init -p docker -r eu-west-1 churn-serving</pre><p>Run Locally</p><pre>eb local run --port 9696</pre><p>Deploy to AWS</p><pre>eb create churn-serving-env</pre><p>Once deployed, you’ll get a URL like:</p><pre>http://churn-serving-env.elasticbeanstalk.com/predict</pre><p>Now you can test it remotely using your predict-test.py script by replacing the host URL.</p><h3>Step 9: Clean Up</h3><p>When you’re done testing, terminate the environment to avoid unnecessary AWS costs:</p><pre>eb terminate churn-serving-env</pre><h3>Summary</h3><p>Here’s what we’ve built:</p><ol><li>Trained a <strong>churn prediction model</strong> in Python</li><li>Saved and loaded it using <strong>Pickle</strong></li><li>Served it via a <strong>Flask API</strong></li><li>Managed dependencies using <strong>Pipenv</strong></li><li>Containerized it using <strong>Docker</strong></li><li>Deployed it to <strong>AWS Elastic Beanstalk</strong></li></ol><p>This end-to-end process transforms your jupyter notebook into a <strong>production-ready ML microservice</strong> — deployable, scalable, and cloud-native.</p><h3>Final Thoughts</h3><p>Deployment is the bridge between experimentation and impact.<br>Once you master this pipeline, you can deploy any ML model — not just for churn prediction, but for recommendation systems, fraud detection, or NLP tasks.</p><blockquote><em>The real power of Machine Learning lies not in building models — but in </em><strong><em>deploying them where they can make decisions</em></strong><em>.</em></blockquote><p>#MachineLearning #MLOps #Python #Docker #AWS</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fddedc1a0a7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating Logistic Regression Models — From Accuracy to AUC (Step-by-Step Guide)]]></title>
            <link>https://medium.com/@poojashreechoudhury7/evaluating-logistic-regression-models-from-accuracy-to-auc-step-by-step-guide-b500ad78700a?source=rss-6b879c2525c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b500ad78700a</guid>
            <category><![CDATA[model-evaluation]]></category>
            <category><![CDATA[confusion-matrix]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[precision]]></category>
            <dc:creator><![CDATA[Pooja]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 08:35:01 GMT</pubDate>
            <atom:updated>2025-10-19T08:35:01.614Z</atom:updated>
            <content:encoded><![CDATA[<h3>Evaluating Logistic Regression Models — From Accuracy to AUC (Step-by-Step Guide)</h3><p>When we train a machine-learning model, it’s tempting to focus on <strong>accuracy</strong> — “My model is 80% accurate!”<br>But does that mean it’s <em>good</em>?<br>Not always.</p><p>In this post, we’ll explore the <strong>complete evaluation pipeline</strong> for a logistic regression model:</p><ul><li>Why accuracy can be misleading</li><li>What <strong>TP, TN, FP, FN</strong> mean</li><li>What <strong>precision</strong> and <strong>recall</strong> really measure</li><li>How to interpret the <strong>ROC curve</strong> and <strong>AUC score</strong></li><li>What <strong>K-Fold cross-validation</strong> does and why it’s powerful</li></ul><p>All illustrated with a <strong>customer churn prediction</strong> example.</p><h3>1. Problem Setup — Predicting Customer Churn</h3><p>We have a telecom dataset with customer information and whether they left the company (churn=1) or stayed (churn=0).<br>Our goal is to predict <strong>who will churn</strong>.</p><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.feature_extraction import DictVectorizer<br>from sklearn.linear_model import LogisticRegression<br><br># Load and clean data<br>df = pd.read_csv(&#39;data-week-3.csv&#39;)<br>df.columns = df.columns.str.lower().str.replace(&#39; &#39;, &#39;_&#39;)<br># Fix numerical column and missing values<br>df.totalcharges = pd.to_numeric(df.totalcharges, errors=&#39;coerce&#39;).fillna(0)<br># Convert target to numeric<br>df.churn = (df.churn == &#39;yes&#39;).astype(int)<br># Split data (60% train, 20% val, 20% test)<br>df_full_train, df_test = train_test_split(df, test_size=0.2, random_state=1)<br>df_train, df_val = train_test_split(df_full_train, test_size=0.25, random_state=1)</pre><h3>2. Train the Logistic Regression Model</h3><p>We separate <strong>categorical</strong> and <strong>numerical</strong> features and train the model.</p><pre>numerical = [&#39;tenure&#39;, &#39;monthlycharges&#39;, &#39;totalcharges&#39;]<br>categorical = [&#39;gender&#39;,&#39;partner&#39;,&#39;dependents&#39;,&#39;internetservice&#39;,&#39;contract&#39;,&#39;paymentmethod&#39;]<br><br>dv = DictVectorizer(sparse=False)<br>train_dict = df_train[categorical + numerical].to_dict(orient=&#39;records&#39;)<br>X_train = dv.fit_transform(train_dict)<br>y_train = df_train.churn.values<br>model = LogisticRegression(max_iter=1000)<br>model.fit(X_train, y_train)</pre><p>Predict on validation data:</p><pre>val_dict = df_val[categorical + numerical].to_dict(orient=&#39;records&#39;)<br>X_val = dv.transform(val_dict)<br>y_pred = model.predict_proba(X_val)[:, 1]</pre><h3>3. Accuracy — The First Step (and Its Limits)</h3><pre>churn_decision = (y_pred &gt;= 0.5)<br>(y_val == churn_decision).mean()<br># Output: 0.8034 (≈80%)</pre><p>That’s 80% accuracy — sounds great, right?</p><p>But let’s look deeper.</p><p>If 73% of customers never churn, a model that always predicts “no churn” will still be right 73% of the time — without actually learning anything. So when our real model shows 80% accuracy, it’s only slightly better than guessing the majority class. That’s why accuracy alone can be misleading in imbalanced datasets — we need other metrics like precision and recall to truly measure how well the model detects churners.</p><h3>4. Understanding TP, TN, FP, FN</h3><p>Before we calculate other metrics, let’s understand the <strong>four core outcomes</strong> in binary classification:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*FqnBISPK7rzrNBAx083RPg.png" /></figure><ul><li><strong>TP (True Positive)</strong> → Model correctly predicts <em>churn</em>.</li><li><strong>TN (True Negative)</strong> → Model correctly predicts <em>no churn</em>.</li><li><strong>FP (False Positive)</strong> → Model predicts <em>churn</em> but the customer didn’t.</li><li><strong>FN (False Negative)</strong> → Model predicts <em>no churn</em> but the customer actually left.</li></ul><p>Let’s compute these from the validation results:</p><pre>t = 0.5<br>predict_positive = (y_pred &gt;= t)<br>predict_negative = (y_pred &lt; t)<br>actual_positive = (y_val == 1)<br>actual_negative = (y_val == 0)<br><br>tp = (predict_positive &amp; actual_positive).sum()<br>tn = (predict_negative &amp; actual_negative).sum()<br>fp = (predict_positive &amp; actual_negative).sum()<br>fn = (predict_negative &amp; actual_positive).sum()<br>tp, tn, fp, fn<br># Output: (210, 922, 101, 176)</pre><h3>5. Precision, Recall, and F1 — The Real Quality Metrics</h3><p>Now we can calculate the important metrics that depend on TP, TN, FP, and FN.</p><p><strong>Precision : </strong><em>Of all customers predicted to churn, how many actually churned?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*bqKoV84QChvrlfouZHRZ3A.png" /></figure><pre>precision = tp / (tp + fp)  # 0.675</pre><p><strong>Interpretation:</strong><br>When the model predicts a customer will churn, it’s right <strong>67.5%</strong> of the time.</p><p><strong>Recall (Sensitivity) : </strong><em>Of all actual churners, how many did we successfully catch?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*Q_gRbJV3gYHj8zHVMVFWcw.png" /></figure><pre>recall = tp / (tp + fn)  # 0.544</pre><p><strong>Interpretation:</strong><br>We caught <strong>54%</strong> of the customers who actually churned — but missed almost half.</p><p><strong>F1 Score : </strong><em>A balance between Precision and Recall.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*rbLGhGiYmZej2kIRjsDAQg.png" /></figure><p>The F1 score helps when you want a single metric that balances both errors.​</p><pre>f1 = 2 * (precision * recall) / (precision + recall)  # ≈ 0.602</pre><h3>6. The Confusion Matrix — Seeing Everything at Once</h3><p>We can visualize this information as a matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*equrpQsJXOOwouwnl4eKFA.png" /></figure><p>But look closer:<br>We have <strong>more false negatives (176)</strong> than false positives (101) — so the models <strong>missing churners</strong>, which is risky for business.</p><h3>7. ROC Curve &amp; AUC — Ranking Power</h3><p>The <strong>ROC curve</strong> shows how recall (True Positive Rate) changes as we vary the threshold.</p><pre>from sklearn.metrics import roc_curve, roc_auc_score<br>import matplotlib.pyplot as plt<br><br>fpr, tpr, thresholds = roc_curve(y_val, y_pred)<br>plt.figure(figsize=(5,5))<br>plt.plot(fpr, tpr, label=&#39;Model&#39;)<br>plt.plot([0,1],[0,1],&#39;--&#39;,label=&#39;Random&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.ylabel(&#39;True Positive Rate (Recall)&#39;)<br>plt.legend()</pre><p>The <strong>area under this curve (AUC)</strong> quantifies model quality:</p><pre>roc_auc_score(y_val, y_pred)<br># Output: 0.84</pre><p><strong>AUC = 0.84</strong> means the model correctly ranks a random churner above a random non-churner <strong>84% of the time</strong>.</p><h3>8. K-Fold Cross-Validation — Testing Model Stability</h3><p>Evaluating on one split can be misleading.<br>K-Fold Cross-Validation gives a more reliable score.</p><p><strong>How It Works</strong></p><ol><li>Split data into <em>K</em> equal folds (e.g., 10).</li><li>Train the model <em>K</em> times — each time, use a different fold for validation.</li><li>Compute AUC for each run and average the results.</li></ol><pre>from sklearn.model_selection import KFold<br>import numpy as np<br><br>kfold = KFold(n_splits=10, shuffle=True, random_state=1)<br>scores = []<br>for train_idx, val_idx in kfold.split(df_full_train):<br>    df_train = df_full_train.iloc[train_idx]<br>    df_val = df_full_train.iloc[val_idx]<br>    y_train = df_train.churn.values<br>    y_val = df_val.churn.values<br>    train_dict = df_train[categorical + numerical].to_dict(orient=&#39;records&#39;)<br>    val_dict = df_val[categorical + numerical].to_dict(orient=&#39;records&#39;)<br>    X_train = dv.fit_transform(train_dict)<br>    X_val = dv.transform(val_dict)<br>    model = LogisticRegression(max_iter=1000)<br>    model.fit(X_train, y_train)<br>    y_pred = model.predict_proba(X_val)[:, 1]<br>    auc = roc_auc_score(y_val, y_pred)<br>    scores.append(auc)<br>print(&#39;%.3f ± %.3f&#39; % (np.mean(scores), np.std(scores)))<br># Output: 0.841 ± 0.012</pre><p>This shows that:</p><ul><li><strong>Average AUC = 0.841</strong></li><li><strong>Std Dev = 0.012</strong> → model is stable and generalizes well.</li></ul><h3>9. Parameter Tuning — The Role of C</h3><p>C in Logistic Regression controls <strong>regularization strength</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*stL-Epz5aTtiVbpfM5-sYg.png" /></figure><p>You can tune it like this:</p><pre>for C in [0.001, 0.01, 0.1, 0.5, 1, 5, 10]:<br>    scores = []<br>    for train_idx, val_idx in kfold.split(df_full_train):<br>        df_train = df_full_train.iloc[train_idx]<br>        df_val = df_full_train.iloc[val_idx]<br>        y_train = df_train.churn.values<br>        y_val = df_val.churn.values<br>        train_dict = df_train[categorical + numerical].to_dict(orient=&#39;records&#39;)<br>        val_dict = df_val[categorical + numerical].to_dict(orient=&#39;records&#39;)<br>        X_train = dv.fit_transform(train_dict)<br>        X_val = dv.transform(val_dict)<br>        model = LogisticRegression(C=C, max_iter=1000)<br>        model.fit(X_train, y_train)<br>        y_pred = model.predict_proba(X_val)[:, 1]<br>        auc = roc_auc_score(y_val, y_pred)<br>        scores.append(auc)<br>    print(f&#39;C={C}  Mean AUC={np.mean(scores):.3f} ± {np.std(scores):.3f}&#39;)</pre><p>Best values: <strong>C = 0.1 to 1.0</strong></p><h3>10. Final Model on Test Data</h3><p>Finally, train on full training data and test once:</p><pre>dv = DictVectorizer(sparse=False)<br>train_dict = df_full_train[categorical + numerical].to_dict(orient=&#39;records&#39;)<br>X_full_train = dv.fit_transform(train_dict)<br><br>y_full_train = df_full_train.churn.values<br>model = LogisticRegression(C=1.0, max_iter=1000)<br>model.fit(X_full_train, y_full_train)<br>test_dict = df_test[categorical + numerical].to_dict(orient=&#39;records&#39;)<br>X_test = dv.transform(test_dict)<br>y_test = df_test.churn.values<br>roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])<br># Output: 0.857</pre><p>Final <strong>Test AUC = 0.857</strong> — consistent with our validation results.</p><h3>11. Summary of All Metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*enA53SCz2VUFT2QJ0g56Zw.png" /></figure><h3>12. Key Takeaways</h3><ul><li>Accuracy can <strong>hide poor performance</strong> on minority classes.</li><li>TP, TN, FP, FN form the foundation for <strong>all evaluation metrics</strong>.</li><li><strong>Precision</strong> measures prediction correctness.</li><li><strong>Recall</strong> measures detection ability.</li><li><strong>AUC</strong> measures ranking quality.</li><li><strong>K-Fold CV</strong> measures model reliability.</li><li><strong>Regularization </strong>balances bias and variance.</li></ul><p><em>If this helped you understand model evaluation clearly, follow for more easy, visual ML guides!</em></p><p>#machinelearning, #datascience, #logisticregression, #evaluationmetrics, #python, #beginnersguide</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b500ad78700a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Transformers: The Magic That Powers LLMs]]></title>
            <link>https://medium.com/@poojashreechoudhury7/inside-transformers-the-magic-that-powers-llms-aa02a84e3cb7?source=rss-6b879c2525c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa02a84e3cb7</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Pooja]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 11:13:28 GMT</pubDate>
            <atom:updated>2025-10-12T11:13:28.104Z</atom:updated>
            <content:encoded><![CDATA[<h3>From LLMs to Transformers: The “Engine Room” of AI</h3><p>My previous LLM post, we learned what Large Language Models (LLMs) are and how they changed the world of AI.</p><p>But have you ever wondered what’s happening under the hood when you ask ChatGPT a question and it replies instantly with something meaningful?<br>Let’s decode the brain behind it all — the <strong>Transformer Architecture</strong>.</p><h3>1. The Transformer: The Engine Behind Modern AI</h3><p>Before Transformers, models like RNNs (Recurrent Neural Networks) and LSTMs were used to process text sequentially — word by word.<br>This caused slow training and difficulty remembering long context (like the start of a paragraph).</p><p>In 2017, Google introduced the paper <strong>“Attention is All You Need”</strong>, and it changed everything.</p><p>Transformers made it possible to process <strong>all words at once</strong>, allowing the model to understand meaning, relationships, and context much better.</p><h3>2. The Transformer Blueprint: Encoder + Decoder</h3><p>The Transformer architecture is not a single block. Instead, it’s built from two major components, much like the two halves of a translator’s brain:</p><ul><li><strong>The Encoder (The Reader):</strong> Takes your input text and understands its meaning and context.</li><li><strong>The Decoder (The Writer/ Generator):</strong> Uses the encoder’s understanding to generate the output, one word at a time.</li></ul><p><strong>Important clarification:</strong></p><ul><li>Models like <strong>T5 or BART</strong> use both <strong>Encoder + Decoder</strong>.</li><li><strong>GPT-style models (ChatGPT)</strong> use <strong>only the Decoder</strong>, which handles both understanding the input and generating output.</li></ul><p>This Encoder–Decoder design is the blueprint where all other pieces — embeddings, attention, and generation — fit together.</p><h3>3. Embeddings: Turning Words into Meaningful Numbers</h3><p>Before the Encoder can understand language, the text must be converted into numbers.</p><ul><li><strong>Tokenization:</strong> Input text is split into tokens (words or sub-words).</li><li><strong>Embeddings:</strong> Each token is converted into a numerical vector that captures meaning and relationships.</li></ul><p>Example: The embedding vectors for &quot;dog&quot; and &quot;puppy&quot; will be very close together, while &quot;pencil&quot; will be far away.</p><p><strong>Data flow:</strong></p><ul><li>Encoder-Decoder models: Token → Encoder → Embeddings→ Decoder (with encoder context)</li><li>Decoder-only models: Token embeddings → Decoder directly</li></ul><p><strong>Connection:</strong> These embeddings are the first input fed into the Encoder (or Decoder, in GPT).</p><h3>4. Self-Attention: How the Model Understands Context</h3><p>Once the Encoder receives the embeddings, <strong>Self-Attention</strong> kicks in.</p><p><strong>Analogy:</strong> Imagine reading a long contract. You don’t read word-by-word; you track which clauses, names, or dates are relevant.</p><p>Self-attention does the same. For each word, it looks at all other words simultaneously and assigns relevance scores.</p><blockquote>Example: &quot;The cat sat on the mat because it was tired&quot; → the model figures out that &quot;it&quot; refers to &quot;cat&quot;.</blockquote><p>This happens across multiple layers, building a <strong>deep, contextual understanding</strong> of every word.</p><p><strong>Connection:</strong> Embeddings feed into Self-Attention layers to create rich representations of the input.</p><h3>5. Auto-Regressive Text Generation</h3><p>Unlike humans who might draft a paragraph and then edit, the Decoder writes <strong>one token at a time</strong>:</p><ol><li>Generate the first word.</li><li>Feed that word back into itself as context.</li><li>Predict the next word using the input + previous outputs.</li><li>Repeat until an <strong>End of Sequence</strong> token.</li></ol><blockquote>Example:</blockquote><blockquote>Input: &quot;The capital of France is&quot;</blockquote><blockquote>Decoder predicts: &quot;Paris&quot;</blockquote><blockquote>New Context: &quot;The capital of France is Paris&quot;</blockquote><blockquote>Decoder predicts: &quot;.&quot;</blockquote><p><strong>Connection:</strong> Auto-regressive generation transforms the internal understanding into sequential, fluent text.</p><h3>6. Self-Supervised Learning: How It All Gets Trained</h3><p>How does the Transformer learn embeddings, attention, and generation?</p><ul><li>Trained using <strong>Self-Supervised Learning</strong>, meaning it <strong>doesn’t need labeled data</strong>.</li><li>GPT- style : predicts the <strong>next token</strong> in billions of sentences.</li><li>BERT- style : predicts <strong>missing words</strong>.</li></ul><blockquote>Example: &quot;The sky is ___.&quot; → the model predicts &quot;blue&quot; (or &quot;gray&quot;, &quot;cloudy&quot;, etc.)</blockquote><p><strong>Connection:</strong> This training teaches embeddings, attention weights, and all layers of the Encoder/Decoder to understand language deeply.</p><h3>7. Generalization: Zero-shot, One-shot, Few-shot</h3><p>Once trained, Transformers can perform tasks they were <strong>never explicitly trained for</strong>:</p><ul><li><strong>Zero-shot:</strong> Solve a task with no examples (e.g., &quot;Translate this German sentence into French&quot;).</li><li><strong>One-shot learning:</strong> Performing a task after being given <strong>one example</strong> (e.g., “Here is one example of summarization. Now, summarize this new article.”).</li><li><strong>Few-shot learning:</strong> Generalizing after being shown a <strong>small handful of examples</strong>.</li></ul><p><strong>Connection:</strong> Massive pretraining allows the Transformer to generalize to new tasks.</p><h3>8. Emergent Behavior: When Scale Creates Intelligence</h3><p>As LLMs grow from millions to billions of parameters, they start displaying <strong>emergent abilities</strong>:</p><ul><li>Complex reasoning</li><li>Advanced mathematical problem-solving</li><li>Writing and debugging code</li><li>Following multi-step logic</li></ul><p>This happens because <strong>attention + scale + self-supervised learning</strong> combine to produce surprisingly human-like intelligence.</p><p><strong>Connection:</strong> Everything from embeddings and attention to training and scale leads to the emergent intelligence of a great LLM.</p><h3>9. The Complete Flow: Everything Connected</h3><p>Every concept is part of the <strong>sequential life cycle</strong> of an LLM responding to a prompt.</p><p><strong>Encoder-Decoder Models:</strong><br>Input text → Tokenization → Embeddings → Encoder → Decoder (with encoder context) → Output text</p><p><strong>Decoder-Only Models (GPT):</strong><br>Input text → Tokenization → Embeddings → Decoder → Auto-regressive output → Output text</p><h3>Final Takeaway</h3><p>The Transformer is more than just a model. It’s a <strong>fully integrated language engine</strong>, where every component — from embeddings to self-attention to decoder generation — works together to create <strong>coherent, intelligent text</strong>.</p><p>Understanding Transformers helps you see <strong>how LLMs like ChatGPT think, learn, and respond</strong> — and why they can perform tasks that seem almost magical.</p><p>#LLMs #Transformers #AI #DeepLearning #GPT #MachineLearning #NLP #ChatGPT #ArtificialIntelligence</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa02a84e3cb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>