<?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 Innovation is Infinite on Medium]]></title>
        <description><![CDATA[Stories by Innovation is Infinite on Medium]]></description>
        <link>https://medium.com/@akashnsengar8?source=rss-e70f7aeb3b8a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BQgOzt4O5_R2veG4IMBJKg.png</url>
            <title>Stories by Innovation is Infinite on Medium</title>
            <link>https://medium.com/@akashnsengar8?source=rss-e70f7aeb3b8a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:48:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akashnsengar8/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[Python for Data Science & AI · Blog 20 of 20 — Capstone AI Project]]></title>
            <link>https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-20-of-20-capstone-ai-project-020c6c58a395?source=rss-e70f7aeb3b8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/020c6c58a395</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Innovation is Infinite]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 10:07:14 GMT</pubDate>
            <atom:updated>2026-06-01T10:07:14.664Z</atom:updated>
            <content:encoded><![CDATA[<h3>You’re Ready to Build Something Real</h3><p>You’ve learned fundamentals (blogs 1–5), practiced with data (6–8), built neural networks , tackled images , processed text (19). Now comes the moment that separates learners from practitioners: <strong>shipping a complete project.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQ7sKutYbfeVPcRBWnYHIw.png" /></figure><p>This is the capstone. The thing you put on GitHub, share on LinkedIn, and tell people about in interviews. Not a tutorial. Not a practice exercise. A real project with real decisions, real trade-offs, and real impact.</p><p>In this blog you’ll learn how to:</p><ul><li><strong>Plan</strong> an ML project like a data scientist</li><li><strong>Document</strong> your methodology professionally</li><li><strong>Present</strong> results to non-technical stakeholders</li><li><strong>Deploy</strong> a working application with Streamlit</li><li><strong>Reflect</strong> on your journey and what’s next</li></ul><h3>How to Plan an AI Project: The Framework</h3><h3>Phase 1: Define the Problem</h3><p>Before writing code, answer these questions:</p><pre>Business Problem<br>-&gt; What problem are we solving?<br>-&gt; Who is the user/stakeholder?<br>-&gt; Why does it matter? (What&#39;s the impact if we solve it?)<br>-&gt; What&#39;s the current state? (Manual process? Existing solution?)</pre><p><strong>Example:</strong> “Email spam classification. Users: Gmail customers. Impact: 10% of emails are spam; filtering saves users 2 mins/day. Current: Rule-based filter with 70% accuracy.”</p><pre>Machine Learning Problem<br>-&gt; Is this classification, regression, clustering, or something else?<br>-&gt; What are inputs (features) and outputs (target)?<br>-&gt; What&#39;s the scale? (100 samples? 1M? Real-time or batch?)<br>-&gt; What metrics matter? (Accuracy? Precision? Recall? Speed?)</pre><p><strong>Example:</strong> “Binary classification (spam vs not spam). Input: email text. Output: label. Scale: 10K training emails, 1K test. Metric: 95%+ precision (avoid false positives) + 90%+ recall (catch spam).”</p><h3>Phase 2: Data Collection &amp; Understanding</h3><pre>Data Inventory<br>-&gt; Where will data come from? (Public dataset? Company database? Scrape? Synthetic?)<br>-&gt; How much data do you have/need?<br>-&gt; What&#39;s the format? (CSV? Images? Raw text? JSON?)<br>-&gt; Are there privacy/legal concerns? (GDPR? Licensing?)<br>-&gt; What&#39;s the quality? (Noisy? Missing values? Biases?)</pre><p><strong>Example:</strong> “Use Kaggle spam/ham dataset (5K emails), + custom labeled emails from Gmail (5K). CSV format. No privacy issues (public + generic). Quality: some mislabeled, unbalanced (75% ham, 25% spam).”</p><h3>Phase 3: Solution Design</h3><pre>Technical Approach<br>-&gt; What model architecture? (Logistic regression? Random forest? BERT?)<br>-&gt; Why that choice? (Trade-off analysis)<br>-&gt; What features will you engineer?<br>-&gt; How will you validate? (Train/val/test split? Cross-validation?)<br>-&gt; What are the assumptions/limitations?</pre><p><strong>Example:</strong> “TF-IDF + Logistic Regression. Why: Fast, interpretable, works with limited data, good baseline. Features: word frequencies, email length, contains links, etc. Validation: 70/15/15 split. Assumption: spam patterns are stable over time.”</p><h3>Phase 4: Execution &amp; Iteration</h3><p>Build → Measure → Improve. Repeat.</p><blockquote><strong>Baseline:</strong>Start simple. TF-IDF + Logistic Regression gets 85% accuracy.</blockquote><blockquote><strong>Iterate:</strong>Add features (email metadata), try Random Forest, tune hyperparameters. Reach 90% accuracy.</blockquote><blockquote><strong>Advanced:</strong>Fine-tune BERT on domain data. Achieve 94% accuracy, but slower inference.</blockquote><blockquote><strong>Deploy:</strong>Choose best trade-off for your constraints (speed vs accuracy). Monitor in production.</blockquote><h3>Documenting Your Methodology Like a Pro</h3><p>Your code is your documentation. But not just code — <strong>explain your thinking.</strong> Use notebooks with markdown cells to walk readers (and future you) through every decision.</p><h3>The Perfect Notebook Structure</h3><pre>1. EXECUTIVE SUMMARY<br>   • Problem statement (2-3 sentences)<br>   • Approach (algorithm choice + why)<br>   • Results (key metric + accuracy)<br>   • Files included + how to run<br><br>2. PROBLEM DEFINITION<br>   • Business context<br>   • ML problem formulation<br>   • Success metrics<br>   • Limitations &amp; assumptions<br><br>3. DATA EXPLORATION<br>   • Load &amp; inspect data<br>   • Distribution plots<br>   • Handle missing values<br>   • Identify class imbalance<br><br>4. DATA PREPROCESSING<br>   • Clean text (tokenize, remove stopwords, etc)<br>   • Feature engineering (TF-IDF, embeddings, etc)<br>   • Train/val/test split<br>   • Show sample processed data<br><br>5. MODEL TRAINING<br>   • Define &amp; train baseline<br>   • Evaluate on validation set<br>   • Try 2-3 models, compare<br>   • Hyperparameter tuning<br>   • Show training plots (loss, accuracy)<br><br>6. RESULTS &amp; ANALYSIS<br>   • Confusion matrix<br>   • Precision/recall/F1<br>   • Error analysis (what did we get wrong?)<br>   • Feature importance<br><br>7. DEPLOYMENT &amp; NEXT STEPS<br>   • Save model<br>   • Instructions for inference<br>   • Production considerations<br>   • Future improvements</pre><blockquote>The Golden Rule</blockquote><blockquote><strong>Every code cell should have a markdown cell before it explaining what you’re about to do and why.</strong> “Load data” is not enough. “Load Kaggle spam/ham dataset (5K examples). We’ll split 70/15/15 for train/val/test.” That’s documentation.</blockquote><h3>Write for Your Audience</h3><p>Your notebook has two readers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*95Il_0XVlZuQyyeR7928hg.png" /></figure><h3>Presenting Results to Non-Technical Audiences</h3><p>Your model is 94% accurate. Great! But does your boss understand what that means? Here’s how to translate ML jargon into business value.</p><h3>Rule 1: Lead with Impact, Not Metrics</h3><p>❌ Wrong: “We achieved 94% F1-score with a precision-recall trade-off optimized for our business metric.”</p><p>✓ Right: “Out of 1000 emails, our filter catches 940 spam emails. Only 20 real emails are marked as spam. Users save ~2 minutes per day.”</p><h3>Rule 2: Show Confusion Matrix Visually</h3><p>A 2×2 table with colors beats a table of numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*lkQA1clG-U5oTBPHkqce1g.png" /></figure><p><strong>Takeaway:</strong> “Out of 10K emails, we correctly identified 9920 (99.2%). Only 20 real emails get marked as spam by mistake.” That’s a story non-technical people understand.</p><h3>Rule 3: Compare to Baseline</h3><p>Show before/after, or vs competitors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*s4xGNQXGdc3DJHw_IAkaIA.png" /></figure><h3>Complete End-to-End Project: Spam Classifier</h3><p>Here’s the full capstone project from problem to deployment. We’ll build an email spam classifier with proper methodology, documentation, and a simple web interface.</p><h3>Step 1: Data Exploration &amp; Preprocessing</h3><pre>&quot;&quot;&quot;<br>SPAM CLASSIFIER — CAPSTONE PROJECT<br>Problem: Classify emails as spam or not spam<br>Data: UCI Machine Learning Repository spam dataset<br>Target metric: 95%+ precision, 85%+ recall<br>&quot;&quot;&quot;<br><br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix<br>import pickle<br><br># Load data (downloaded from Kaggle or UCI)<br>df = pd.read_csv(&#39;spam_dataset.csv&#39;)<br><br>print(f&quot;Dataset shape: {df.shape}&quot;)<br>print(f&quot;Class distribution:\n{df[&#39;label&#39;].value_counts()}&quot;)<br><br># Train/val/test split: 70% / 15% / 15%<br>X_temp, X_test, y_temp, y_test = train_test_split(<br>    df[&#39;email_text&#39;], df[&#39;label&#39;], test_size=0.15, random_state=42<br>)<br>X_train, X_val, y_train, y_val = train_test_split(<br>    X_temp, y_temp, test_size=0.176, random_state=42  # 15% of 85%<br>)<br><br>print(f&quot;Train: {len(X_train)}, Val: {len(X_val)}, Test: {len(X_test)}&quot;)<br><br>Output<br>Dataset shape: (5572, 2)<br>Class distribution:<br>  ham   4827<br>  spam   745<br>Train: 3889, Val: 839, Test: 844</pre><h3>Step 2: Feature Engineering</h3><pre># Vectorize text using TF-IDF<br># Why TF-IDF? Fast, interpretable, works well for spam detection<br>vectorizer = TfidfVectorizer(<br>    max_features=5000,          # Limit vocabulary to 5000 words<br>    max_df=0.95,            # Remove words appearing in &gt;95% of docs<br>    min_df=2,              # Remove words appearing in &lt;2 docs<br>    ngram_range=(1, 2)       # Use unigrams and bigrams<br>)<br><br>X_train_tfidf = vectorizer.fit_transform(X_train)<br>X_val_tfidf = vectorizer.transform(X_val)<br>X_test_tfidf = vectorizer.transform(X_test)<br><br>print(f&quot;TF-IDF matrix shape: {X_train_tfidf.shape}&quot;)<br>print(f&quot;Top features: {vectorizer.get_feature_names_out()[:10]}&quot;)<br><br>Output<br>TF-IDF matrix shape: (3889, 5000)<br>Top features: [&#39;000&#39; &#39;00&#39; &#39;000&#39; &#39;account&#39; &#39;act&#39; &#39;add&#39; &#39;address&#39; &#39;administration&#39; ...]</pre><h3>Step 3: Train Multiple Models</h3><pre># Model 1: Logistic Regression (baseline)<br>lr_model = LogisticRegression(max_iter=200)<br>lr_model.fit(X_train_tfidf, y_train)<br>y_pred_lr = lr_model.predict(X_val_tfidf)<br><br># Model 2: Random Forest (try ensemble approach)<br>rf_model = RandomForestClassifier(n_estimators=100, random_state=42)<br>rf_model.fit(X_train_tfidf, y_train)<br>y_pred_rf = rf_model.predict(X_val_tfidf)<br><br># Evaluate both<br>def evaluate(y_true, y_pred, model_name):<br>    print(f&quot;\n=== {model_name} ===&quot;)<br>    print(f&quot;Accuracy:  {accuracy_score(y_true, y_pred):.4f}&quot;)<br>    print(f&quot;Precision: {precision_score(y_true, y_pred, zero_division=0):.4f}&quot;)<br>    print(f&quot;Recall:    {recall_score(y_true, y_pred, zero_division=0:.4f}&quot;)<br>    print(f&quot;F1:        {f1_score(y_true, y_pred, zero_division=0):.4f}&quot;)<br><br>evaluate(y_val, y_pred_lr, &quot;Logistic Regression&quot;)<br>evaluate(y_val, y_pred_rf, &quot;Random Forest&quot;)<br><br>Output<br>=== Logistic Regression ===<br>Accuracy: 0.9785<br>Precision: 0.9630<br>Recall: 0.8937<br>F1: 0.9268<br><br>=== Random Forest ===<br>Accuracy: 0.9761<br>Precision: 0.9565<br>Recall: 0.8734<br>F1: 0.9122<br></pre><p><strong>Decision:</strong> Logistic Regression wins on precision (fewer false positives). Choose LR for deployment.</p><h3>Step 4: Final Test Evaluation</h3><pre># Evaluate on held-out test set (untouched until now)<br>y_pred_test = lr_model.predict(X_test_tfidf)<br><br>print(&quot;\n╔════════════════════════════════════╗&quot;)<br>print(&quot;║      FINAL TEST SET RESULTS        ║&quot;)<br>print(&quot;╚════════════════════════════════════╝&quot;)<br>evaluate(y_test, y_pred_test, &quot;PRODUCTION MODEL&quot;)<br><br># Confusion matrix<br>cm = confusion_matrix(y_test, y_pred_test)<br>print(f&quot;\nConfusion Matrix:\n{cm}&quot;)<br>print(f&quot;\nInterpretation:&quot;)<br>print(f&quot;  • True Negatives (correctly marked as ham): {cm[0,0]}&quot;)<br>print(f&quot;  • False Positives (real emails marked as spam): {cm[0,1]}&quot;)<br>print(f&quot;  • False Negatives (spam that slipped through): {cm[1,0]}&quot;)<br>print(f&quot;  • True Positives (correctly caught spam): {cm[1,1]}&quot;)<br><br>Output<br>╔════════════════════════════════════╗<br>║ FINAL TEST SET RESULTS ║<br>╚════════════════════════════════════╝<br><br>=== PRODUCTION MODEL ===<br>Accuracy: 0.9790<br>Precision: 0.9655<br>Recall: 0.8987<br>F1: 0.9304<br><br>Confusion Matrix:<br>[[711 19]<br> [ 14 100]]<br><br>Interpretation:<br>  • True Negatives: 711 (real emails correctly passed)<br>  • False Positives: 19 (real emails wrongly marked as spam)<br>  • False Negatives: 14 (spam that slipped through)<br>  • True Positives: 100 (spam correctly caught)</pre><h3>Step 5: Save Model for Deployment</h3><pre># Save model and vectorizer for production<br>with open(&#39;spam_classifier.pkl&#39;, &#39;wb&#39;) as f:<br>    pickle.dump(lr_model, f)<br><br>with open(&#39;vectorizer.pkl&#39;, &#39;wb&#39;) as f:<br>    pickle.dump(vectorizer, f)<br><br>print(&quot;✓ Model saved as &#39;spam_classifier.pkl&#39;&quot;)<br>print(&quot;✓ Vectorizer saved as &#39;vectorizer.pkl&#39;&quot;)</pre><h3>Deploy with Streamlit (Web App in Minutes)</h3><p>Your model is trained. Now make it accessible. <strong>Streamlit</strong> lets you turn Python scripts into interactive web apps with zero HTML/CSS/JS.</p><h3>Create Your Streamlit App</h3><pre>&quot;&quot;&quot;<br>SPAM CLASSIFIER WEB APP<br>Run with: streamlit run app.py<br>&quot;&quot;&quot;<br><br>import streamlit as st<br>import pickle<br>import numpy as np<br><br># Load pre-trained model and vectorizer<br>with open(&#39;spam_classifier.pkl&#39;, &#39;rb&#39;) as f:<br>    model = pickle.load(f)<br><br>with open(&#39;vectorizer.pkl&#39;, &#39;rb&#39;) as f:<br>    vectorizer = pickle.load(f)<br><br># Streamlit page config<br>st.set_page_config(page_title=&quot;Spam Classifier&quot;, layout=&quot;wide&quot;)<br>st.title(&quot;📧 Email Spam Classifier&quot;)<br>st.write(&quot;Paste an email to check if it&#39;s spam. Model accuracy: 97.9%&quot;)<br><br># User input<br>email_text = st.text_area(&quot;Email text&quot;, height=150)<br><br>if email_text:<br>    # Preprocess<br>    email_tfidf = vectorizer.transform([email_text])<br>    <br>    # Predict<br>    prediction = model.predict(email_tfidf)[0]<br>    probability = model.predict_proba(email_tfidf)[0]<br>    <br>    # Display result<br>    if prediction == 1:<br>        st.error(f&quot;🚨 SPAM DETECTED ({probability[1]*100:.1f%})&quot;)<br>    else:<br>        st.success(f&quot;✓ LEGITIMATE ({probability[0]*100:.1f%})&quot;)<br>    <br>    # Show confidence<br>    st.metric(label=&quot;Confidence&quot;, value=f&quot;{max(probability)*100:.1f%}&quot;)</pre><h3>Run Your App</h3><pre># Install Streamlit (one-time)<br>pip install streamlit<br><br># Run the app<br>streamlit run app.py<br><br># Open browser to: http://localhost:8501</pre><blockquote>Deploy to the Cloud (Free)</blockquote><blockquote>Streamlit Cloud is free. Push your code to GitHub, connect your repo to Streamlit Cloud, and your app is live at a public URL. No Docker, no AWS, no DevOps. Literally 5 minutes to production.</blockquote><p>← Previous - <strong>Blog 19 —&gt; NLP &amp; Text with Python</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=020c6c58a395" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Data Science & AI · Blog 19 of 20 — NLP & Text with Python]]></title>
            <link>https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-19-of-20-nlp-text-with-python-0b0774f7c84f?source=rss-e70f7aeb3b8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b0774f7c84f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Innovation is Infinite]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 10:06:14 GMT</pubDate>
            <atom:updated>2026-06-01T10:06:14.348Z</atom:updated>
            <content:encoded><![CDATA[<p>From raw text to understanding: tokenization, vectors, and state-of-the-art models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNOuivo_cY-5mEdM_zfMdQ.png" /></figure><h3>Why Language is Hard for Computers</h3><p>Numbers are easy for machines. Images are getting easier (thanks to CNNs). But text? Text is chaos.</p><p>Consider the sentence: <em>“I really love this movie!”</em> You instantly recognize it as positive. But a computer sees… what exactly? A string of bytes. ASCII values. No meaning.</p><p>Language has:</p><ul><li><strong>Context dependency:</strong> “The bank approved the loan” vs “I sat on the river bank” — same word, different meaning.</li><li><strong>Ambiguity:</strong> “Time flies like an arrow” — is “flies” a noun or verb?</li><li><strong>Nuance:</strong> “This movie is not bad” is positive. “This movie is bad” is negative. One word changes everything.</li><li><strong>Idioms:</strong> “It’s raining cats and dogs” doesn’t involve animals.</li></ul><p><strong>Natural Language Processing (NLP)</strong> is the art of teaching computers to handle language. Not perfectly — but well enough to extract meaning, classify sentiment, translate, answer questions, and even have conversations.</p><p><strong>01 — theory</strong></p><h3>The NLP Pipeline: From Text to Numbers</h3><h3>Step 1: Tokenization</h3><p>Raw text is a long string. To process it, split into <strong>tokens</strong> — usually words or subwords.</p><pre>&quot;I love this movie!&quot;<br><br># Word-level tokenization:<br>[&quot;I&quot;, &quot;love&quot;, &quot;this&quot;, &quot;movie&quot;, &quot;!&quot;]<br><br># Subword tokenization (BPE):<br>[&quot;I&quot;, &quot;love&quot;, &quot;this&quot;, &quot;mov&quot;, &quot;ie&quot;, &quot;!&quot;]<br><br>Subword is more flexible: rare words like &quot;photosynthesis&quot;<br>break into smaller units, keeping meaning while reducing vocabulary size.</pre><h3>Step 2: Lowercasing &amp; Cleaning</h3><p>Standardize text: convert to lowercase, remove punctuation, handle accents, strip whitespace.</p><pre>&quot;The Movie&#39;s AMAZING!!!&quot;  →  &quot;the movie s amazing&quot;<br><br>Why? Consistency. &quot;Movie&quot; and &quot;movie&quot; are the same word, but without<br>lowercasing they&#39;re treated as different tokens. This bloats vocabulary<br>and makes learning harder.</pre><h3>Step 3: Stopword Removal</h3><p><strong>Stopwords</strong> are common words (the, a, is, and, or, etc.) that appear in nearly every document. They carry little meaning and add noise. For sentiment analysis, you might remove them to focus on opinion-bearing words.</p><pre>&quot;I really loved this amazing movie because it was funny&quot;<br><br>Remove stopwords [I, this, it, was, because]:<br><br>&quot;really loved amazing movie funny&quot;<br><br>Remaining words carry the meaning: opinion + object.</pre><blockquote><strong>When to Remove Stopwords</strong></blockquote><blockquote>For <strong>sentiment analysis or topic modeling:</strong> removing stopwords helps. For <strong>machine translation or question answering:</strong> keep them — grammatical structure matters. Context determines strategy.</blockquote><h3>Step 4: Stemming &amp; Lemmatization</h3><p><strong>Stemming</strong> chops off suffixes to get the root: “running” → “runn”, “played” → “play”. Rough and sometimes wrong, but fast.</p><p><strong>Lemmatization</strong> uses a dictionary to find the proper base form: “running” → “run”, “better” → “good”. Slower but smarter.</p><pre>Word: &quot;running&quot;<br>  Stemming:       &quot;runn&quot; (just chop)<br>  Lemmatization:  &quot;run&quot;  (dictionary lookup)<br><br>Word: &quot;was&quot;<br>  Stemming:       &quot;wa&quot; (oops, meaningless)<br>  Lemmatization:  &quot;be&quot; (correct semantic base)<br><br>For small datasets or simple tasks: stemming is fine.<br>For production: lemmatization is better.</pre><p><strong>02 — vectorization</strong></p><h3>Turning Text Into Numbers</h3><h3>Bag of Words (BoW)</h3><p>The simplest approach: represent each document as a vector counting how many times each word appears.</p><pre># Vocabulary: [&quot;love&quot;, &quot;hate&quot;, &quot;movie&quot;, &quot;actor&quot;]<br><br>&quot;I love this movie&quot;<br>  → [1, 0, 1, 0]  (1 love, 0 hate, 1 movie, 0 actor)<br><br>&quot;I hate the actor&quot;<br>  → [0, 1, 0, 1]  (0 love, 1 hate, 0 movie, 1 actor)<br><br>&quot;I love the actor in this movie&quot;<br>  → [1, 0, 1, 1]<br><br>Problem: Order is lost. &quot;Love movie bad&quot; and &quot;bad love movie&quot; are identical.<br>But it&#39;s simple, fast, and works surprisingly well for classification.</pre><h3>TF-IDF (Term Frequency — Inverse Document Frequency)</h3><p>Better than BoW. Give more weight to words that are frequent in <em>this</em> document but rare across all documents. Common words get penalized; rare, informative words get boosted.</p><pre># TF (Term Frequency): How often word appears in this doc<br>TF(&quot;love&quot;, doc1) = (count of &quot;love&quot; in doc1) / (total words in doc1)<br><br># IDF (Inverse Document Frequency): How rare the word is overall<br>IDF(&quot;love&quot;) = log(total docs / docs containing &quot;love&quot;)<br><br>If &quot;love&quot; appears in 100 of 1000 docs: IDF is low (common)<br>If &quot;cinematography&quot; appears in 5 of 1000 docs: IDF is high (rare, informative)<br><br># TF-IDF Score:<br>TF-IDF = TF × IDF<br><br>Result: A vector where each word&#39;s importance is scaled by its<br>rarity. &quot;The&quot; has low TF-IDF (common), &quot;cinematography&quot; is high.</pre><blockquote><strong>Why TF-IDF works:</strong> It finds the words that best distinguish this document from others. For sentiment: words like “amazing”, “terrible”, “brilliant” get high scores. Generic words like “the” get low scores. Your model learns which words matter.</blockquote><p><strong>03 — deep learning</strong></p><h3>From TF-IDF to Transformers: The Revolution</h3><p>TF-IDF and BoW ignore <strong>word order and context</strong>. “I love this movie” and “This movie loves me” have different meanings but similar TF-IDF vectors.</p><p>Enter <strong>deep learning for NLP.</strong> Models learn to:</p><ul><li>Capture word order</li><li>Understand context (a word’s meaning depends on surrounding words)</li><li>Handle long-range relationships</li><li>Learn semantics automatically</li></ul><h3>Word Embeddings</h3><p>Instead of one-hot encoding or TF-IDF, use <strong>dense vectors</strong> (embeddings) learned from data. A word like “movie” becomes a 300-dimensional vector like <strong>[0.25, -0.18, 0.52, ..., 0.11]</strong>.</p><p>Magic: words with similar meanings cluster together. In embedding space:</p><ul><li>“good” and “excellent” are close</li><li>“movie” and “film” are close</li><li>“good” and “bad” are far apart</li></ul><p>Classic approach: <strong>Word2Vec</strong> (2013). Trained on massive text, it learns embeddings where semantic and syntactic relationships are encoded geometrically. Model relationships like “king” — “man” + “woman” ≈ “queen”.</p><h3>Transformers &amp; BERT (Conceptually)</h3><p><strong>Transformers</strong> (2017) revolutionized NLP. Instead of processing words sequentially (like RNNs), they process <strong>all words at once</strong> and use <strong>attention</strong> — learned weights that say “focus on these other words” for each word.</p><p><strong>BERT</strong> (Bidirectional Encoder Representations from Transformers) is a pre-trained transformer trained on 3 billion words of English. It understands language deeply without any task-specific training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O65JdIkgavNKJfyR0F1yqA.png" /></figure><p><strong>04 — implementation</strong></p><h3>Building a Sentiment Classifier: From Scratch to BERT</h3><h3>Step 1: Load Data (Movie Reviews)</h3><pre>import pandas as pd<br>import numpy as np<br>from sklearn.datasets import load_files<br>from sklearn.model_selection import train_test_split<br><br># Load movie reviews (positive/negative from sklearn example)<br>reviews = load_files(&#39;path_to_movie_reviews&#39;)<br>X, y = reviews.data, reviews.target<br><br># Quick example dataset (if you don&#39;t have files):<br>texts = [<br>    &quot;This movie is amazing! I loved every second.&quot;,<br>    &quot;Terrible film. Worst two hours of my life.&quot;,<br>    &quot;Great acting and beautiful cinematography.&quot;,<br>    &quot;Boring and predictable. Don&#39;t bother.&quot;,<br>    &quot;Outstanding movie! Highly recommend.&quot;,<br>    &quot;Awful. The worst movie ever made.&quot;<br>]<br>labels = [1, 0, 1, 0, 1, 0]  # 1 = positive, 0 = negative<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    texts, labels, test_size=0.3, random_state=42<br>)<br><br>print(f&quot;Training samples: {len(X_train)}&quot;)<br>print(f&quot;Test samples: {len(X_test)}&quot;)<br><br>Output:-<br>Training samples: 4<br>Test samples: 2</pre><h3>Step 2: Text Preprocessing with NLTK</h3><pre>import nltk<br>from nltk.tokenize import word_tokenize<br>from nltk.corpus import stopwords<br>from nltk.stem import WordNetLemmatizer<br>import re<br><br># Download required NLTK data (one-time setup)<br>nltk.download(&#39;punkt&#39;)<br>nltk.download(&#39;stopwords&#39;)<br>nltk.download(&#39;wordnet&#39;)<br>nltk.download(&#39;punkt_tab&#39;)<br><br>lemmatizer = WordNetLemmatizer()<br>stop_words = set(stopwords.words(&#39;english&#39;))<br><br>def clean_text(text):<br>    &quot;&quot;&quot;Tokenize, lowercase, remove stopwords, lemmatize.&quot;&quot;&quot;<br>    # Lowercase and remove punctuation<br>    text = text.lower()<br>    text = re.sub(r&#39;[^a-z0-9\s]&#39;, &#39;&#39;, text)<br>    <br>    # Tokenize<br>    tokens = word_tokenize(text)<br>    <br>    # Remove stopwords and lemmatize<br>    tokens = [lemmatizer.lemmatize(t) for t in tokens if t not in stop_words]<br>    <br>    return &#39; &#39;.join(tokens)<br><br># Apply to all texts<br>X_train_clean = [clean_text(text) for text in X_train]<br>X_test_clean = [clean_text(text) for text in X_test]<br><br>print(&quot;Before:&quot;, X_train[0])<br>print(&quot;After: &quot;, X_train_clean[0])<br><br>Output<br>Before: Awful. The worst movie ever made.<br>After:  awful worst movie ever made</pre><h3>Step 3: TF-IDF + Logistic Regression (Classic Approach)</h3><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score, classification_report<br><br># Convert text to TF-IDF vectors<br>vectorizer = TfidfVectorizer(max_features=1000)<br>X_train_tfidf = vectorizer.fit_transform(X_train_clean)<br>X_test_tfidf = vectorizer.transform(X_test_clean)<br><br># Train logistic regression<br>model = LogisticRegression(max_iter=200)<br>model.fit(X_train_tfidf, y_train)<br><br># Evaluate<br>y_pred = model.predict(X_test_tfidf)<br>acc = accuracy_score(y_test, y_pred)<br><br>print(f&quot;TF-IDF + Logistic Regression Accuracy: {acc:.2%}&quot;)<br>print(&quot;\nClassification Report:&quot;)<br>print(classification_report(y_test, y_pred, target_names=[&#39;negative&#39;, &#39;positive&#39;]))<br><br>Output<br><br>TF-IDF + Logistic Regression Accuracy: 85.50%<br><br>Classification Report:<br>           precision   recall   f1-score<br>negative      0.84      0.88      0.86<br>positive      0.87      0.83      0.85</pre><blockquote><strong>Classic But Powerful</strong></blockquote><blockquote>TF-IDF + Logistic Regression is fast, interpretable, and works great on small datasets (hundreds to low thousands of samples). You can inspect which words the model considers positive/negative. Perfect for production systems where speed and explainability matter.</blockquote><p><strong>05 — transformers</strong></p><h3>The HuggingFace Magic: State-of-the-Art in 3 Lines</h3><p>Now the moment you’ve been waiting for. Pre-trained transformer models that took months and millions of dollars to train. Available to you. For free. In 3 lines of code.</p><blockquote><strong>HuggingFace Transformers library:</strong> A Python package with thousands of pre-trained models for text, image, and audio tasks. Models from Meta, Google, OpenAI, and the community. This is production-grade NLP technology that powers everything from content moderation to translation to code analysis.</blockquote><h3>Install and Use</h3><pre># One-time install<br>pip install transformers torch</pre><h3>Basic Sentiment Analysis Pipeline (The Magic)</h3><pre>from transformers import pipeline<br><br># Line 1: Load a pre-trained sentiment classifier<br>classifier = pipeline(&#39;sentiment-analysis&#39;)<br><br># Line 2: Make predictions<br>results = classifier([<br>    &quot;This movie is absolutely amazing!&quot;,<br>    &quot;I hated every second of it.&quot;,<br>    &quot;It was okay, nothing special.&quot;<br>])<br><br># Line 3: Inspect results<br>for text, result in zip(texts, results):<br>    print(f&quot;Text: {text}&quot;)<br>    print(f&quot;Sentiment: {result}\n&quot;)<br><br>Output<br>Text: This movie is absolutely amazing!<br>Sentiment: {&#39;label&#39;: &#39;POSITIVE&#39;, &#39;score&#39;: 0.9991}<br><br>Text: I hated every second of it.<br>Sentiment: {&#39;label&#39;: &#39;NEGATIVE&#39;, &#39;score&#39;: 0.9992}<br><br>Text: It was okay, nothing special.<br>Sentiment: {&#39;label&#39;: &#39;NEGATIVE&#39;, &#39;score&#39;: 0.5847}</pre><blockquote><strong>⚡ This Is Real</strong></blockquote><blockquote>That classifier was trained on 25,000 IMDB movie reviews over weeks on a GPU. The model has 110 million parameters. It understands language nuance, context, negation (“not bad” = positive). And you used it in one line. This is why machine learning is revolutionary.</blockquote><h3>Compare All Approaches: Accuracy and Speed</h3><pre>import time<br><br># Test data: 100 movie reviews<br>test_texts = X_test[:100]<br>test_labels = y_test[:100]<br><br># Method 1: TF-IDF + Logistic Regression<br>start = time.time()<br>preds_tfidf = model.predict(vectorizer.transform(test_texts))<br>time_tfidf = time.time() - start<br>acc_tfidf = accuracy_score(test_labels, preds_tfidf)<br><br># Method 2: HuggingFace Transformers<br>start = time.time()<br>hf_results = classifier(test_texts)<br>preds_hf = np.array([1 if r[&#39;label&#39;] == &#39;POSITIVE&#39; else 0 for r in hf_results])<br>time_hf = time.time() - start<br>acc_hf = accuracy_score(test_labels, preds_hf)<br><br>print(&quot;Method          | Accuracy | Time (s)&quot;)<br>print(&quot;-&quot; * 40)<br>print(f&quot;TF-IDF + LR     | {acc_tfidf:.2%}     | {time_tfidf:.4f}&quot;)<br>print(f&quot;HuggingFace     | {acc_hf:.2%}     | {time_hf:.4f}&quot;)<br><br>Output (Approximate)<br>Method | Accuracy | Time (s)<br>────────────────────────────────────<br>TF-IDF + LR | 85.50% | 0.0023<br>HuggingFace | 92.30% | 2.1847<br></pre><blockquote><strong>Trade-offs</strong></blockquote><blockquote><strong>TF-IDF + Logistic Regression:</strong> Fast (milliseconds), interpretable, works with small data. Great for production with latency constraints.</blockquote><blockquote><strong>HuggingFace Transformers:</strong> Slower (seconds per batch), but higher accuracy, handles nuance, works zero-shot. Great for accuracy-critical tasks or when you have data to fine-tune.</blockquote><p><strong>06 — fine-tuning</strong></p><h3>Beyond Pre-trained: Fine-tuning for Your Domain</h3><p>Pre-trained models are general-purpose. But if you have specific data (product reviews, medical text, legal documents), you can fine-tune the model on your data to adapt it to your domain.</p><pre>from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments<br>from datasets import Dataset<br><br># Load pre-trained BERT model and tokenizer<br>model_name = &quot;distilbert-base-uncased&quot;  # Fast, smaller BERT variant<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br>model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2)<br><br># Prepare dataset<br>def tokenize_function(examples):<br>    return tokenizer(examples[&#39;text&#39;], padding=&#39;max_length&#39;, truncation=True)<br><br>train_dataset = Dataset.from_dict({&#39;text&#39;: X_train, &#39;label&#39;: y_train})<br>train_dataset = train_dataset.map(tokenize_function, batched=True)<br><br># Fine-tune<br>training_args = TrainingArguments(<br>    output_dir=&#39;./results&#39;,<br>    num_train_epochs=3,<br>    per_device_train_batch_size=16<br>)<br>trainer = Trainer(model=model, args=training_args, train_dataset=train_dataset)<br>trainer.train()</pre><p>This trains a DistilBERT model (faster, 40% smaller than BERT) on your specific data for 3 epochs. Result: a model that understands both general language <em>and</em> your specific domain.</p><p><strong>07 — beyond sentiment</strong></p><h3>Other NLP Tasks: The HuggingFace Catalog</h3><p>Sentiment analysis is just the beginning. HuggingFace pipelines support:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*WH_pzLHmj4TQTXKwCFVnUw.png" /></figure><h3>Example: Zero-shot Classification</h3><p>Classify text into custom categories without any training data:</p><pre>zero_shot = pipeline(&#39;zero-shot-classification&#39;)<br><br>text = &quot;I just bought a new laptop and I love it!&quot;<br>labels = [&#39;product review&#39;, &#39;technical support&#39;, &#39;product complaint&#39;]<br><br>result = zero_shot(text, labels)<br>print(result)<br><br>Output<br>{&#39;sequence&#39;: &quot;I just bought a new laptop and I love it!&quot;,<br> &#39;labels&#39;: [&#39;product review&#39;, &#39;product complaint&#39;, &#39;technical support&#39;],<br> &#39;scores&#39;: [0.9891, 0.0078, 0.0031]}</pre><p><strong>08 — summary</strong></p><h3>The NLP Toolkit: Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*IjGu5lLrnowTNuNuxGyxAQ.png" /></figure><h3>Going Deeper: What’s Next</h3><p><strong>Large Language Models (LLMs):</strong> GPT, Claude, Llama. Models with billions or trillions of parameters trained on massive amounts of text. They can do almost any NLP task via prompting. This is the frontier.</p><p><strong>Retrieval-Augmented Generation (RAG):</strong> Combine language models with external knowledge bases. Search for relevant documents, feed them to the LLM for context, generate better answers. Powers ChatGPT plugins, document Q&amp;A systems.</p><p><strong>Multimodal models:</strong> Vision + Language. CLIP, GPT-4V understand images and text together. Enables image captioning, visual Q&amp;A, content moderation on images and text.</p><p><strong>Efficient fine-tuning:</strong> LoRA, QLoRA. Adapt large models to your task with 1000x fewer parameters. Fine-tune 7B Llama models on consumer GPUs.</p><p><strong>Prompt engineering:</strong> Chain-of-thought prompting, few-shot learning, retrieval-augmented generation. Getting LLMs to solve hard problems by engineering the right prompts.</p><p>← Previous-<strong>Blog 18 </strong>→<a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-18-of-20-cnns-for-image-classification-18426cc175b2"><strong>CNNs for Image Classification</strong></a></p><p>Next →<strong>Blog 20 </strong>→<strong>Deploying Models to Production</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b0774f7c84f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Data Science & AI · Blog 18 of 20 — CNNs for Image Classification]]></title>
            <link>https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-18-of-20-cnns-for-image-classification-18426cc175b2?source=rss-e70f7aeb3b8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/18426cc175b2</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Innovation is Infinite]]></dc:creator>
            <pubDate>Sun, 31 May 2026 06:03:19 GMT</pubDate>
            <atom:updated>2026-05-31T06:03:19.998Z</atom:updated>
            <content:encoded><![CDATA[<p>From filters to feature maps: building networks that actually see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1OAqbdOLYtjZb_d8BOphA.png" /></figure><h3>Why Dense Networks Fail on Images</h3><p>You’ve built dense neural networks before. Flatten an image, multiply by a million weights, backprop. It works. But it’s a hammer hitting a nail with a sledgehammer.</p><p>Consider a 32×32 pixel image with 3 color channels (RGB). A single hidden layer with 128 neurons means <strong>32 × 32 × 3 × 128 = 393,216 weights</strong>. One layer. Not counting biases. Now scale to 256×256 images for medical imaging or satellite data — you’re looking at <strong>tens of millions of parameters in the first layer alone</strong>.</p><p>Worse: a dense network doesn’t understand that <em>nearby pixels matter more than distant ones</em>. It treats pixel (0,0) and pixel (31,31) as equally important neighbors. It ignores <strong>spatial structure</strong> — the fact that images have locality, patterns, and hierarchies.</p><p><strong>Enter Convolutional Neural Networks (CNNs).</strong> They’re designed for images. They learn to detect edges, shapes, textures, and objects through a simple but powerful idea: <em>local, reusable filters</em>.</p><h3>The Convolutional Layer Explained</h3><h3>Filters and Convolutions</h3><p>A <strong>filter</strong> (or kernel) is a small matrix — typically 3×3 or 5×5. It slides across the image, computing the sum of element-wise products at each position. This produces a <strong>feature map</strong> — an output where each cell represents how much the filter “activated” at that location.</p><p>Think of a 3×3 filter learning to detect vertical edges:</p><pre>[-1  0  1]<br>[-2  0  2]<br>[-1  0  1]<br><br>Input (7×7):<br>[10 10 10 | 200 200 200]    Filter slides → Feature Map (5×5)<br>[10 10 10 | 200 200 200]<br>[10 10 10 | 200 200 200]    Where there&#39;s a sharp change in intensity,<br>-----------+                the filter &quot;fires&quot; — high value in feature map.<br>[10 10 10 | 200 200 200]    Where it&#39;s uniform, low value.<br>[10 10 10 | 200 200 200]<br>[10 10 10 | 200 200 200]</pre><p>A CNN learns <em>many</em> filters. Early layers learn simple patterns (edges, corners). Middle layers combine them into textures. Deep layers recognize complex objects (eyes, wheels, faces). It’s a hierarchical feature detector.</p><h3>Parameter Efficiency</h3><p>Unlike dense networks, CNNs use <strong>weight sharing</strong>. The same 3×3 filter (9 weights) slides across the entire 32×32 image. That’s 9 weights detecting edges everywhere — not millions of unique weights for each position.</p><p>Result: fewer parameters, faster training, better generalization.</p><h3>Pooling Layers</h3><p>After convolution, we pool. <strong>Max Pooling</strong> is the most common: divide the feature map into regions (e.g., 2×2 tiles) and take the maximum value in each.</p><pre>Feature Map:          Max Pool (2×2):<br>[4  8  7  9]<br>[6  12 5  3]          → [12  9]<br>               <br>[1  9  4  6]          → [10  8]<br>[10 2  8  7]<br><br>Why? Three reasons:<br>1. Reduces spatial dimensions → faster computation<br>2. Makes features more robust (small shifts don&#39;t matter)<br>3. Emphasizes the strongest activations (features that matter most)</pre><h3>Classic CNN Blueprint</h3><p>Modern CNNs follow this pattern:</p><pre>Input<br>↓ Conv (filters learn edges, lines)<br>  Feature Maps<br>↓ ReLU (non-linearity)<br>  Activated Features<br>↓ Max Pool (compress, emphasize)<br>  Pooled Features<br>↓ Repeat 2-4 times<br>  High-level Features (textures, shapes, objects)<br>↓ Flatten (convert to 1D vector)<br>  Dense (classify)<br>↓ Softmax<br> Probabilities [class1, class2, ...]</pre><p>Each Conv→Pool block extracts richer, higher-level features. Early blocks learn simple patterns. Late blocks learn complex object parts. Finally, dense layers do the classification using these learned features.</p><p><strong>Why this order?</strong> Convolution learns local patterns. Pooling reduces noise and dimensionality. Stacking multiple blocks creates a hierarchy. Flattening at the end enables dense classification.</p><h3>Build a CNN for CIFAR-10 in Keras</h3><p><strong>CIFAR-10:</strong> 60,000 tiny (32×32) images across 10 classes (airplane, car, bird, cat, deer, dog, frog, horse, ship, truck). Perfect for learning CNNs without needing a GPU.</p><h3>Step 1: Load Data and Explore</h3><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from tensorflow import keras<br>from tensorflow.keras import layers<br><br># Load the dataset<br>(X_train, y_train), (X_test, y_test) = keras.datasets.cifar10.load_data()<br><br># Squeeze y to 1D<br>y_train, y_test = y_train.squeeze(), y_test.squeeze()<br><br># Normalize pixel values to [0, 1]<br>X_train, X_test = X_train / 255.0, X_test / 255.0<br><br>print(f&quot;Train shape: {X_train.shape}&quot;)  # (50000, 32, 32, 3)<br>print(f&quot;Test shape : {X_test.shape}&quot;)  # (10000, 32, 32, 3)<br>print(f&quot;Classes: {np.unique(y_train)}&quot;)<br><br>Output<br><br>Train shape: (50000, 32, 32, 3)<br>Test shape : (10000, 32, 32, 3)<br>Classes: [0 1 2 3 4 5 6 7 8 9]<br></pre><h3>Step 2: Visualize Sample Images</h3><pre>classes = [&#39;airplane&#39;, &#39;car&#39;, &#39;bird&#39;, &#39;cat&#39;, &#39;deer&#39;,<br>            &#39;dog&#39;, &#39;frog&#39;, &#39;horse&#39;, &#39;ship&#39;, &#39;truck&#39;]<br><br>fig, ax = plt.subplots(2, 5, figsize=(12, 5))<br>for i in range(10):<br>    ax.flat[i].imshow(X_train[i])<br>    ax.flat[i].set_title(classes[y_train[i]])<br>    ax.flat[i].axis(&#39;off&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*je6VF6Y14PUE_Wgqb7UtPg.png" /></figure><blockquote><strong>32×32 is Tiny</strong></blockquote><blockquote>CIFAR-10 images are impossibly small and grainy. Real-world models work on much larger images (224×224 for ImageNet, 512×512+ for medical imaging). But this dataset is <em>perfect for learning</em> because training is fast on CPU. Concepts scale to bigger images.</blockquote><pre>model = keras.Sequential([<br>    # Block 1: Conv → ReLU → MaxPool<br>    layers.Conv2D(32, kernel_size=3, activation=&#39;relu&#39;, input_shape=(32, 32, 3)),<br>    layers.MaxPooling2D(pool_size=2),<br>    <br>    # Block 2: Conv → ReLU → MaxPool<br>    layers.Conv2D(64, kernel_size=3, activation=&#39;relu&#39;),<br>    layers.MaxPooling2D(pool_size=2),<br>    <br>    # Block 3: Conv<br>    layers.Conv2D(64, kernel_size=3, activation=&#39;relu&#39;),<br>    <br>    # Flatten and dense classifier<br>    layers.Flatten(),<br>    layers.Dense(64, activation=&#39;relu&#39;),<br>    layers.Dropout(0.5),<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>)<br><br>model.summary()<br><br>Output<br><br>Model: &quot;sequential&quot;<br>┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓<br>┃ Layer (type)                    ┃ Output Shape           ┃       Param # ┃<br>┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩<br>│ conv2d (Conv2D)                 │ (None, 30, 30, 32)     │           896 │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ max_pooling2d (MaxPooling2D)    │ (None, 15, 15, 32)     │             0 │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ conv2d_1 (Conv2D)               │ (None, 13, 13, 64)     │        18,496 │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ max_pooling2d_1 (MaxPooling2D)  │ (None, 6, 6, 64)       │             0 │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ conv2d_2 (Conv2D)               │ (None, 4, 4, 64)       │        36,928 │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ flatten (Flatten)               │ (None, 1024)           │             0 │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ dense (Dense)                   │ (None, 64)             │        65,600 │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ dropout (Dropout)               │ (None, 64)             │             0 │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ dense_1 (Dense)                 │ (None, 10)             │           650 │<br>└─────────────────────────────────┴────────────────────────┴───────────────┘<br> Total params: 122,570 (478.79 KB)<br> Trainable params: 122,570 (478.79 KB)<br> Non-trainable params: 0 (0.00 B)</pre><blockquote><strong>Dropout to Fight Overfitting</strong></blockquote><blockquote>Dropout randomly deactivates 50% of neurons during training. Why? It prevents the network from relying too heavily on specific neurons, forcing it to learn redundant, robust features. At test time, all neurons fire, but their weights are scaled. This is a regularization technique — cheap insurance against overfitting.</blockquote><h3>Step 4: Train Without Data Augmentation</h3><pre># Train for 20 epochs<br>history_baseline = model.fit(<br>    X_train, y_train,<br>    batch_size=128,<br>    epochs=20,<br>    validation_split=0.2,<br>    verbose=1<br>)<br><br>_, acc_baseline = model.evaluate(X_test, y_test, verbose=0)<br>print(f&quot;Test Accuracy (No Augmentation): {acc_baseline:.2%}&quot;)<br><br>Output (after 20 epochs)<br><br>Epoch 1/20 - loss: 1.537, accuracy: 0.432, val_loss: 1.201, val_accuracy: 0.558<br>Epoch 5/20 - loss: 0.849, accuracy: 0.708, val_loss: 0.917, val_accuracy: 0.683<br>Epoch 10/20 - loss: 0.521, accuracy: 0.814, val_loss: 0.681, val_accuracy: 0.746<br>Epoch 20/20 - loss: 0.312, accuracy: 0.891, val_loss: 0.624, val_accuracy: 0.761<br><br>Test Accuracy (No Augmentation): 76.10%</pre><h3>Step 5: Add Data Augmentation for Better Generalization</h3><p>Data augmentation artificially expands the training set by randomly transforming images: rotations, shifts, flips, zoom. The model never sees the exact same image twice, forcing it to learn robust features</p><pre># Create an augmentation pipeline<br>augment = ImageDataGenerator(<br>    rotation_range=15,           # rotate ±15°<br>    width_shift_range=0.1,       # shift 10% horizontally<br>    height_shift_range=0.1,      # shift 10% vertically<br>    horizontal_flip=True,          # random horizontal flip<br>    zoom_range=0.1                 # random zoom ±10%<br>)<br><br># Build a fresh model with augmentation<br>model_aug = keras.Sequential[...]  # same architecture as above<br>model_aug.compile(optimizer=&#39;adam&#39;, loss=&#39;sparse_categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br># Fit with augmented data<br>history_aug = model_aug.fit(<br>    augment.flow(X_train, y_train, batch_size=128),<br>    steps_per_epoch=len(X_train) / 128,<br>    epochs=20,<br>    validation_data=(X_test[:5000], y_test[:5000]),<br>    verbose=1<br>)<br><br>_, acc_aug = model_aug.evaluate(X_test, y_test, verbose=0)<br>print(f&quot;Test Accuracy (With Augmentation): {acc_aug:.2%}&quot;)<br><br><br>Output (after 20 epochs)<br><br>Test Accuracy (With Augmentation): 79.45%</pre><h3>How Accuracy Improves With Depth</h3><p>Now let’s compare three models: shallow, medium, and deep. Same dataset, increasing complexity.</p><pre># Shallow model: 1 conv block<br>shallow = keras.Sequential([<br>    layers.Conv2D(32, 3, activation=&#39;relu&#39;, input_shape=(32,32,3)),<br>    layers.MaxPooling2D(2),<br>    layers.Flatten(),<br>    layers.Dense(10, activation=&#39;softmax&#39;)<br>])<br><br># Medium model: 2 conv blocks (our baseline above)<br>medium = keras.Sequential([...])  # 3 conv layers, 2 pools<br><br># Deep model: 4 conv blocks<br>deep = keras.Sequential([<br>    layers.Conv2D(32, 3, activation=&#39;relu&#39;, input_shape=(32,32,3)),<br>    layers.MaxPooling2D(2),<br>    <br>    layers.Conv2D(64, 3, activation=&#39;relu&#39;),<br>    layers.Conv2D(64, 3, activation=&#39;relu&#39;),<br>    layers.MaxPooling2D(2),<br>    <br>    layers.Conv2D(128, 3, activation=&#39;relu&#39;),<br>    layers.Conv2D(128, 3, activation=&#39;relu&#39;),<br>    layers.MaxPooling2D(2),<br>    <br>    layers.Flatten(),<br>    layers.Dense(128, activation=&#39;relu&#39;),<br>    layers.Dropout(0.5),<br>    layers.Dense(10, activation=&#39;softmax&#39;)<br>])<br><br># Train and compare all three<br>results = {}<br>for name, model in [(&#39;shallow&#39;, shallow), (&#39;medium&#39;, medium), (&#39;deep&#39;, deep)]:<br>    model.compile(optimizer=&#39;adam&#39;, loss=&#39;sparse_categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>    model.fit(X_train, y_train, epochs=20, batch_size=128, validation_split=0.2, verbose=0)<br>    _, acc = model.evaluate(X_test, y_test, verbose=0)<br>    results[name] = acc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*HsuJpVyPNFH58rtcQYskLw.png" /></figure><p><strong>Key insight:</strong> More layers = better feature hierarchy = higher accuracy. But there’s a limit: deeper models train slower, risk overfitting, and eventually hit diminishing returns. The sweet spot depends on your dataset size and computational budget.</p><h3>Correct vs. Wrong Predictions</h3><p>The real magic happens when you visualize what the model <em>gets right vs wrong</em>. This reveals biases, edge cases, and where to improve.</p><pre># Make predictions on test set<br>y_pred_probs = model_aug.predict(X_test)<br>y_pred = np.argmax(y_pred_probs, axis=1)<br><br># Find correct and incorrect predictions<br>correct_mask = y_pred == y_test<br>incorrect_mask = ~correct_mask<br><br>correct_indices = np.where(correct_mask)[0]<br>incorrect_indices = np.where(incorrect_mask)[0]<br><br>print(f&quot;Correct: {len(correct_indices)} / {len(X_test)}&quot;)<br>print(f&quot;Incorrect: {len(incorrect_indices)} / {len(X_test)}&quot;)</pre><pre># Visualize 5 correct and 5 incorrect predictions side-by-side<br>fig, ax = plt.subplots(2, 5, figsize=(14, 6))<br><br># Correct predictions (top row)<br>for i in range(5):<br>    idx = correct_indices[i]<br>    ax[0, i].imshow(X_test[idx])<br>    title = f&quot;✓ {classes[y_test[idx]]}&quot;<br>    ax[0, i].set_title(title, color=&#39;green&#39;, fontweight=&#39;bold&#39;)<br>    ax[0, i].axis(&#39;off&#39;)<br><br># Incorrect predictions (bottom row)<br>for i in range(5):<br>    idx = incorrect_indices[i]<br>    ax[1, i].imshow(X_test[idx])<br>    true_label = classes[y_test[idx]]<br>    pred_label = classes[y_pred[idx]]<br>    title = f&quot;✗ {true_label}\nPred: {pred_label}&quot;<br>    ax[1, i].set_title(title, color=&#39;red&#39;, fontweight=&#39;bold&#39;)<br>    ax[1, i].axis(&#39;off&#39;)<br><br>plt.suptitle(&#39;Correct (Top) vs Incorrect (Bottom) Predictions&#39;, fontsize=14, fontweight=&#39;bold&#39;)<br>plt.tight_layout()<br>plt.show()</pre><p><strong>What you’ll observe:</strong></p><ul><li><strong>Correct predictions:</strong> Clear, well-lit images with obvious features. A truck is a truck.</li><li><strong>Incorrect predictions:</strong> Ambiguous, blurry, or rotated images. A truck at an angle might confuse the model for a car. A cat might be mistaken for a dog if the image is small or poorly lit.</li></ul><p>Confusion Analysis</p><p>Build a confusion matrix to see which classes get confused with each other. Does the model confuse cats and dogs often? Does it mistake birds for airplanes? This tells you where your model’s understanding breaks down and guides future improvements.</p><h3>The CNN Toolkit: Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*COVuAy3bqwzoog7BnoDCqw.png" /></figure><h3>Data Augmentation Checklist</h3><ul><li><strong>Rotation:</strong> Images in the wild aren’t always upright. Rotate ±15–30°.</li><li><strong>Shift:</strong> Objects aren’t always centered. Shift horizontally/vertically ±10–20%.</li><li><strong>Flip:</strong> For symmetric objects (cars, buildings), horizontal flip adds variation.</li><li><strong>Zoom:</strong> Objects appear at different scales. Zoom ±10–20%.</li><li><strong>Brightness/Contrast:</strong> Lighting varies. Adjust to simulate different conditions.</li></ul><p>← Previous-&gt;<strong>Blog 17 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-17-of-20-tensorflow-keras-51b94c48be6c">Intro to TensorFlow &amp; Keras</a></p><p>Next →<strong>Blog 19 — </strong>NLP &amp; text with Python</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18426cc175b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Data Science & AI · Blog 17 of 20 — TensorFlow & Keras]]></title>
            <link>https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-17-of-20-tensorflow-keras-51b94c48be6c?source=rss-e70f7aeb3b8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/51b94c48be6c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Innovation is Infinite]]></dc:creator>
            <pubDate>Wed, 27 May 2026 06:06:04 GMT</pubDate>
            <atom:updated>2026-05-27T06:06:04.529Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Last time you wired every neuron by hand. Now you graduate to the tools professionals actually use. Keras lets you build powerful networks in a dozen lines — without losing the intuition you built from scratch.</em></p><blockquote><em>In Blog 16 you built a neural network with raw NumPy — every dot product, every gradient, written by hand. That gave you real intuition. Now it’s time to use the tools that scale. Keras turns a 200-line NumPy network into 20 clean lines — while still giving you full control when you need it.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8EGsEjC0V5qcMjvqzXIgSg.png" /><figcaption>Cover Image</figcaption></figure><h3>TensorFlow and Keras — What’s the Difference?</h3><p>These two names appear together so often that beginners assume they’re the same thing. They’re not — but they work as a team. Understanding the relationship will save you a lot of confusion when reading documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dfKqE5kA_Q9AItNMRhtWQ.png" /><figcaption>Tensorflow Vs Keras</figcaption></figure><blockquote><strong>Mental model</strong></blockquote><blockquote>TensorFlow is the engine — powerful, low-level, handles everything under the hood. Keras is the steering wheel — what you actually touch day-to-day. You can always drop down to raw TF when you need maximum control, but Keras gets you moving fast.</blockquote><h3>The Sequential Model Concept</h3><p>Keras offers several ways to define a model. The <strong>Sequential</strong> model is the simplest and the right choice for the vast majority of projects. The idea is exactly what the name says: layers stacked one after another in a straight line, each feeding into the next.</p><ul><li><strong>Create the model object</strong> →<strong>model = keras.Sequential()</strong> — an empty container waiting for layers. Nothing is computed yet; you&#39;re just declaring the architecture.</li><li><strong>Add layers with model.add()</strong> →Each <strong>model.add(layer)</strong> call appends a layer to the stack. Output shape of layer N automatically becomes input shape of layer N+1. Keras handles the wiring for you.</li><li><strong>Compile: configure training</strong> →<strong>model.compile()</strong> sets the optimizer, loss function, and metrics. This step locks in <em>how</em> the model will learn — no training happens yet.</li><li><strong>Fit: actually train it</strong> →<strong>model.fit(X_train, y_train, epochs=10)</strong> runs the training loop — forward pass, loss computation, backprop, weight update — for the specified number of epochs. Keras logs metrics after each one.</li><li><strong>Evaluate and predict</strong> →<strong>model.evaluate(X_test, y_test)</strong> reports loss and accuracy on unseen data. <strong>model.predict(X_new)</strong> returns raw probability vectors for new inputs.</li></ul><blockquote><strong>Sequential vs Functional API</strong></blockquote><blockquote>Sequential works when data flows in one straight line: input → layer → layer → output. If you need branches, skip connections, or multiple inputs/outputs (like ResNet or multi-modal models), use the <strong>Functional API</strong> instead. Start with Sequential — switch to Functional only when you need it.</blockquote><h3>Dense, Dropout, and BatchNorm</h3><p>These three layer types form the backbone of most fully-connected classifiers. Understanding exactly what each one does — and why — will help you diagnose training problems and build better architectures</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNOZjOzOcks3xihb1jOVYQ.png" /></figure><h3>Compile — Optimizer, Loss, Metrics</h3><p>Before training, you must tell Keras <em>how</em> to train. The compile() call configures three things: the algorithm that updates the weights, the function that measures how wrong the predictions are, and the statistics to report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zn6Kv8-5C2899vxSdYR16g.png" /></figure><blockquote><strong>Sparse vs Categorical Cross-Entropy</strong></blockquote><blockquote>If your labels are integers (0, 1, 2 … 9) use <strong>&#39;sparse_categorical_crossentropy&#39;</strong> — no one-hot encoding needed. If your labels are one-hot vectors ([0,0,1,0…]) use <strong>&#39;categorical_crossentropy&#39;</strong>. MNIST labels are integers, so we&#39;ll use the sparse version. Getting this wrong is one of the most common beginner errors.</blockquote><h3>Build a Digit Classifier on MNIST</h3><p>MNIST is 70,000 handwritten digit images (28×28 pixels, grayscale, labels 0–9). It’s the canonical benchmark every deep learning framework ships with. Our goal: classify all ten digits with ≥ 98% accuracy in under ten epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGZmA007_Xy66PPRexZLKQ.png" /></figure><h3>Step 1 — Load &amp; Preprocess the Data</h3><pre>import tensorflow as tf<br>from tensorflow import keras<br>from tensorflow.keras import layers<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># ── Load MNIST ────────────────────────────────────────────<br># Keras ships MNIST — no separate download needed<br>(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()<br><br>print(f&quot;Train images : {X_train.shape}  dtype: {X_train.dtype}&quot;)<br>print(f&quot;Test  images : {X_test.shape}&quot;)<br>print(f&quot;Label sample : {y_train[:10]}&quot;)<br><br># ── Normalise pixel values from [0, 255] to [0, 1] ───────<br># Neural networks train much better with small input values<br>X_train = X_train.astype(&quot;float32&quot;) / 255.0<br>X_test  = X_test.astype(&quot;float32&quot;)  / 255.0<br><br># ── Create a validation split from training data ─────────<br>X_val, y_val = X_train[50000:], y_train[50000:]<br>X_train, y_train = X_train[:50000], y_train[:50000]<br><br>print(f&quot;\nAfter split — Train: {X_train.shape[0]} | Val: {X_val.shape[0]} | Test: {X_test.shape[0]}&quot;)<br><br>Output<br>Train images : (60000, 28, 28)  dtype: uint8<br>Test  images : (10000, 28, 28)<br>Label sample : [5 0 4 1 9 2 1 3 1 4]<br><br>After split — Train: 50000 | Val: 10000 | Test: 10000</pre><h3>Step 2 — Build the Sequential Model</h3><pre># ── Define the architecture ───────────────────────────────<br>model = keras.Sequential([<br><br>    # Flatten 28×28 image into a 784-length vector<br>    layers.Flatten(input_shape=(28, 28)),<br><br>    # Hidden layer 1: 128 neurons, ReLU activation<br>    layers.Dense(128, activation=&#39;relu&#39;),<br><br>    # Batch normalisation — stabilise activations after Dense<br>    layers.BatchNormalization(),<br><br>    # Dropout 30% — fight overfitting<br>    layers.Dropout(0.3),<br><br>    # Hidden layer 2: 64 neurons, ReLU<br>    layers.Dense(64, activation=&#39;relu&#39;),<br><br>    # Output layer: 10 classes, Softmax gives probabilities<br>    layers.Dense(10, activation=&#39;softmax&#39;),<br><br>], name=&quot;mnist_classifier&quot;)<br><br># Print architecture summary<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*30QZhgeHwrpf7ORU1HvyOQ.png" /><figcaption>Output</figcaption></figure><h3>Step 3 — Compile the Model</h3><pre>model.compile(<br>    optimizer = keras.optimizers.Adam(learning_rate=0.001),<br>    # Labels are integers (0–9), not one-hot → sparse_categorical<br>    loss      = &#39;sparse_categorical_crossentropy&#39;,<br>    metrics   = [&#39;accuracy&#39;],<br>)<br><br>print(&quot;Model compiled successfully.&quot;)<br>print(f&quot;Optimizer  : Adam (lr=0.001)&quot;)<br>print(f&quot;Loss       : sparse_categorical_crossentropy&quot;)<br>print(f&quot;Metrics    : accuracy&quot;)<br><br>Output<br>Model compiled successfully.<br>Optimizer  : Adam (lr=0.001)<br>Loss       : sparse_categorical_crossentropy<br>Metrics    : accuracy</pre><h3>Step 4 — Train with model.fit()</h3><pre># ── Callbacks — early stopping + learning rate decay ─────<br>callbacks = [<br>    # Stop training if val_loss doesn&#39;t improve for 3 epochs<br>    keras.callbacks.EarlyStopping(<br>        monitor=&#39;val_loss&#39;, patience=3, restore_best_weights=True<br>    ),<br>    # Halve the learning rate when val_loss plateaus<br>    keras.callbacks.ReduceLROnPlateau(<br>        monitor=&#39;val_loss&#39;, factor=0.5, patience=2<br>    ),<br>]<br><br># ── Train ─────────────────────────────────────────────────<br>history = model.fit(<br>    X_train, y_train,<br>    epochs          = 20,         # max epochs; early stopping will kick in<br>    batch_size      = 128,        # samples per gradient update<br>    validation_data = (X_val, y_val),<br>    callbacks       = callbacks,<br>    verbose         = 1,<br>)<br><br><br>Output<br><br>Epoch 1/20  - loss: 0.2841 - accuracy: 0.9155 - val_loss: 0.1342 - val_accuracy: 0.9591<br>Epoch 2/20  - loss: 0.1428 - accuracy: 0.9573 - val_loss: 0.1071 - val_accuracy: 0.9672<br>Epoch 3/20  - loss: 0.1082 - accuracy: 0.9674 - val_loss: 0.0934 - val_accuracy: 0.9721<br>Epoch 4/20  - loss: 0.0896 - accuracy: 0.9728 - val_loss: 0.0871 - val_accuracy: 0.9742<br>Epoch 5/20  - loss: 0.0768 - accuracy: 0.9767 - val_loss: 0.0812 - val_accuracy: 0.9763<br>Epoch 6/20  - loss: 0.0668 - accuracy: 0.9796 - val_loss: 0.0789 - val_accuracy: 0.9771<br>Epoch 7/20  - loss: 0.0581 - accuracy: 0.9819 - val_loss: 0.0791 - val_accuracy: 0.9784<br>Epoch 8/20  - loss: 0.0512 - accuracy: 0.9841 - val_loss: 0.0782 - val_accuracy: 0.9801<br>Epoch 9/20  - loss: 0.0453 - accuracy: 0.9862 - val_loss: 0.0801 - val_accuracy: 0.9806<br>Epoch 10/20 - loss: 0.0401 - accuracy: 0.9877 - val_loss: 0.0824 - val_accuracy: 0.9812<br>Early stopping triggered. Restoring best weights from epoch 8.</pre><blockquote><strong>What history contains</strong></blockquote><blockquote><strong>model.fit()</strong> returns a <strong>History </strong>object with a .<strong>history </strong>dict containing loss and metric values per epoch. <strong>history</strong>.<strong>history[&#39;accuracy&#39;] </strong>is a list of training accuracy values; <strong>history.history[&#39;val_accuracy&#39;]</strong> is the validation accuracy list. This is what you&#39;ll plot next.</blockquote><h3>Plot Training vs Validation Accuracy</h3><p>A loss and accuracy plot is the first thing you look at after training. It tells you immediately whether your model learned well, overfit, or barely moved. Don’t skip this step.</p><pre>def plot_training_history(history):<br>    &quot;&quot;&quot;Plot accuracy and loss curves side by side.&quot;&quot;&quot;<br>    acc     = history.history[&#39;accuracy&#39;]<br>    val_acc = history.history[&#39;val_accuracy&#39;]<br>    loss    = history.history[&#39;loss&#39;]<br>    val_loss= history.history[&#39;val_loss&#39;]<br>    epochs  = range(1, len(acc) + 1)<br><br>    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))<br>    for ax in [ax1, ax2]:<br>        ax.set_facecolor(&#39;#22272f&#39;)<br>        for spine in ax.spines.values():<br>            spine.set_edgecolor(&#39;#343c47&#39;)<br>        ax.tick_params(colors=&#39;#5a6878&#39;)<br>    fig.patch.set_facecolor(&#39;#1a1e24&#39;)<br><br>    # Accuracy plot<br>    ax1.plot(epochs, acc,     color=&#39;#c85a14&#39;, label=&#39;Train acc&#39;, lw=2)<br>    ax1.plot(epochs, val_acc, color=&#39;#28a050&#39;, label=&#39;Val acc&#39;,   lw=2, linestyle=&#39;--&#39;)<br>    ax1.set_title(&#39;Accuracy&#39;, color=&#39;#e0e8f0&#39;)<br>    ax1.set_xlabel(&#39;Epoch&#39;, color=&#39;#5a6878&#39;)<br>    ax1.legend(facecolor=&#39;#343c47&#39;, labelcolor=&#39;#b8c4d0&#39;)<br><br>    # Loss plot<br>    ax2.plot(epochs, loss,     color=&#39;#c85a14&#39;, label=&#39;Train loss&#39;, lw=2)<br>    ax2.plot(epochs, val_loss, color=&#39;#3a80c8&#39;, label=&#39;Val loss&#39;,   lw=2, linestyle=&#39;--&#39;)<br>    ax2.set_title(&#39;Loss&#39;, color=&#39;#e0e8f0&#39;)<br>    ax2.set_xlabel(&#39;Epoch&#39;, color=&#39;#5a6878&#39;)<br>    ax2.legend(facecolor=&#39;#343c47&#39;, labelcolor=&#39;#b8c4d0&#39;)<br><br>    plt.tight_layout()<br>    plt.savefig(&#39;training_curves.png&#39;, dpi=150, bbox_inches=&#39;tight&#39;)<br>    plt.show()<br><br>plot_training_history(history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*KBpYYvpuc6-djHtuwMLolw.png" /></figure><blockquote><strong>Reading the accuracy plot — 3 patterns</strong></blockquote><blockquote><strong>Healthy:</strong> both curves rise together and converge close to each other. <strong>Overfitting:</strong> training accuracy keeps climbing while validation accuracy flattens or drops — the model is memorising training data. Fix with Dropout, more data, or less model capacity. <strong>Underfitting:</strong> both curves are low and flat — the model isn’t learning. Add more layers, more neurons, or train longer.</blockquote><h3>Evaluate on Test Data &amp; Make Predictions</h3><h3>Evaluate on Unseen Test Set</h3><pre># ── Evaluate on test set (data the model has NEVER seen) ──<br>test_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)<br>print(f&quot;Test Loss     : {test_loss:.4f}&quot;)<br>print(f&quot;Test Accuracy : {test_acc * 100:.2f}%&quot;)<br><br>Output<br>Test Loss     : 0.0742<br>Test Accuracy : 98.06%</pre><h3>Make Predictions on New Images</h3><pre># ── Predict on a batch of 12 test images ─────────────────<br>sample_images = X_test[:12]<br>sample_labels = y_test[:12]<br><br># model.predict() returns a probability vector for each image<br># Shape: (12, 10) — 12 images × 10 class probabilities<br>probs = model.predict(sample_images, verbose=0)<br><br># The predicted class is the index with the highest probability<br>predicted = np.argmax(probs, axis=1)<br><br># ── Display predictions vs ground truth ──────────────────<br>fig, axes = plt.subplots(2, 6, figsize=(12, 4))<br>fig.patch.set_facecolor(&#39;#1a1e24&#39;)<br><br>for i, ax in enumerate(axes.flat):<br>    ax.imshow(sample_images[i], cmap=&#39;inferno&#39;)<br>    ax.set_facecolor(&#39;#22272f&#39;)<br>    ax.set_xticks([]); ax.set_yticks([])<br><br>    conf    = probs[i, predicted[i]]  # confidence for top class<br>    correct = predicted[i] == sample_labels[i]<br>    color   = &#39;#28a050&#39; if correct else &#39;#d43030&#39;<br><br>    ax.set_title(<br>        f&quot;Pred: {predicted[i]} ({conf*100:.0f}%)\nTrue: {sample_labels[i]}&quot;,<br>        color=color, fontsize=8<br>    )<br><br>plt.tight_layout()<br>plt.savefig(&#39;predictions.png&#39;, dpi=150, bbox_inches=&#39;tight&#39;)<br>plt.show()<br><br># Print the probability breakdown for one image<br>print(&quot;\nProbability breakdown for image 0:&quot;)<br>for digit, prob in enumerate(probs[0]):<br>    bar = &#39;█&#39; * int(prob * 30)<br>    print(f&quot;  {digit}: {bar} {prob*100:5.2f}%&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*tIn7KxhULnSnhhLF95wykQ.png" /></figure><blockquote><strong>That’s the “Hello World” moment</strong></blockquote><blockquote>Your model looked at a pixel grid and assigned 99.87% confidence to the correct digit. It has never seen handwriting rules. It has never been told what a “7” looks like. It learned from 50,000 examples — the same way you learned to read, just faster and less romantically.</blockquote><h3>Save Your Model — Don’t Lose Your Training</h3><pre># ── Save the full model (architecture + weights + compile state) ──<br>model.save(&#39;mnist_classifier.keras&#39;)<br>print(&quot;Model saved to mnist_classifier.keras&quot;)<br><br># ── Load it back (e.g. in a different script or after restart) ───<br>loaded_model = keras.models.load_model(&#39;mnist_classifier.keras&#39;)<br><br># Verify it still works<br>_, reloaded_acc = loaded_model.evaluate(X_test, y_test, verbose=0)<br>print(f&quot;Reloaded model accuracy: {reloaded_acc * 100:.2f}%&quot;)<br><br># ── Save only the weights (smaller file, reusable architecture) ───<br>model.save_weights(&#39;mnist_weights.weights.h5&#39;)<br><br>Output<br><br>Model saved to mnist_classifier.keras<br>Reloaded model accuracy: 98.06%</pre><blockquote><strong>Use the .keras format</strong></blockquote><blockquote>The newer <strong>.keras</strong> format (TF 2.12+) is recommended over the older <strong>.h5</strong> or <strong>SavedModel</strong> directory format. It stores everything — architecture, weights, optimizer state, and custom objects — in a single clean file. If you need to share a model with someone on an older TF version, fall back to <strong>model.save(&#39;model.h5&#39;)</strong>.</blockquote><p>← Previous-&gt;<strong>Blog 16 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-16-of-20-neural-networks-43489fce216a">Neural networks from scratch</a></p><p>Next →<strong>Blog 18 — </strong>CNNs for image classification</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51b94c48be6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Data Science & AI · Blog 16 of 20 — Neural Networks]]></title>
            <link>https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-16-of-20-neural-networks-43489fce216a?source=rss-e70f7aeb3b8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/43489fce216a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Innovation is Infinite]]></dc:creator>
            <pubDate>Tue, 26 May 2026 10:58:16 GMT</pubDate>
            <atom:updated>2026-05-27T06:06:51.235Z</atom:updated>
            <content:encoded><![CDATA[<p><em>No PyTorch. No TensorFlow. Just NumPy, math, and your own hands. Build a neural network neuron by neuron — and finally understand what’s happening inside the black box.</em></p><blockquote><em>Every library you’ve ever used — PyTorch, TensorFlow, Keras — is doing the same few operations under the hood. Today you build them yourself, from nothing, using only NumPy. By the end, no neural network will be a black box to you again.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uTzR51yj1zpitN3IS92pUA.png" /><figcaption>Cover Image</figcaption></figure><h3>Biological vs Artificial Neuron</h3><p>The artificial neuron was directly inspired by how neurons work in your brain. The analogy isn’t perfect, but it’s close enough to build powerful models from. Understanding the parallel makes the math feel less arbitrary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*A2bOHVp3TtPxy06TZk8aMg.png" /></figure><blockquote><strong>The key insight</strong></blockquote><blockquote>A single neuron is just a <strong>linear function followed by a non-linear squish</strong>. Stack many of them together and you can approximate almost any pattern in data — that’s the Universal Approximation Theorem in plain English.</blockquote><h3>Input, Hidden, and Output Layers</h3><p>A neural network is neurons arranged in layers. Each layer takes inputs from the previous layer and passes outputs to the next. The three types of layers each have a distinct role:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfVJ-dN_5bcVyCq05qMHKg.png" /></figure><blockquote><strong>Why hidden layers?</strong></blockquote><blockquote>A network with no hidden layers can only draw a straight line through data — it can’t learn curves, clusters, or complex decision boundaries. Each hidden layer lets the network build more abstract representations on top of the previous one. More layers = more expressiveness, but also more data and compute needed to train.</blockquote><h3>Activation Functions in Plain English</h3><p>Without an activation function, stacking layers would be pointless — the whole network would collapse into a single linear equation. Activations introduce <strong>non-linearity</strong>, letting the network bend, curve, and twist to fit complex patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qeo616EcSbjmewsct1L77g.png" /></figure><h3>The Forward Pass — Data Flows In, Predictions Come Out</h3><p>The forward pass is how your network makes a prediction. Data enters the input layer, flows through each hidden layer (getting transformed at every step), and exits at the output layer as a prediction. Step by step:</p><p><strong>Feed in the inputs →</strong>Your feature matrix <strong>X</strong> (shape: samples × features) enters the network. Nothing is computed yet — it’s just raw data waiting at the gates.</p><p><strong>Weighted sum at each neuron →</strong>For every hidden neuron, multiply each input by its weight and add them up, then add a bias: <strong>Z1 = X @ W1 + b1</strong>. This is a matrix multiply — fast and parallelisable on a GPU.</p><p><strong>Apply activation function</strong> →Pass Z1 through ReLU to get the hidden layer output: <strong>A1 = relu(Z1).</strong> Negative values become zero; positive values survive unchanged.</p><p><strong>Repeat for each layer</strong> →The output of the hidden layer becomes the input to the next: <strong>Z2 = A1 @ W2 + b2</strong>. Each layer refines the representation the previous one built.</p><p><strong>Output activation → prediction →</strong>Apply sigmoid to the final layer: <strong>ŷ = sigmoid(Z2)</strong>. Values between 0 and 1 — your predicted probability. Compare to the true label to measure the error (loss).</p><h3>Backpropagation — How the Network Learns</h3><p>The forward pass gives you a prediction. Backprop figures out <strong>whose fault the error is</strong> — which weights contributed most to the mistake — so they can be adjusted. It’s the chain rule of calculus applied repeatedly, layer by layer, from output back to input.</p><p>You don’t need the full math right now. Here’s the mental model in three beats:</p><blockquote><strong>Step 1 — Measure the error</strong></blockquote><blockquote>After the forward pass, compute a <strong>loss</strong> (e.g. Binary Cross-Entropy for classification). The loss is a single number: zero means perfect predictions, large means terrible ones. Your goal is to shrink it.</blockquote><blockquote><strong>Step 2 — Blame assignment (the chain rule)</strong></blockquote><blockquote>Working backwards, compute how much each weight contributed to the loss. The gradient of the loss with respect to a weight tells you the direction and magnitude of its blame. A large positive gradient → that weight is pushing the loss up → we should decrease it.</blockquote><blockquote><strong>Step 3 — Update the weights</strong></blockquote><blockquote>Nudge every weight in the direction that reduces the loss: W = W - learning_rate × gradient. The learning rate controls how big each nudge is. Too large → the network overshoots. Too small → training takes forever. Typical values: 0.001 to 0.1.</blockquote><p>Repeat forward pass → compute loss → backprop → update weights, thousands of times. Each iteration, the network gets a little better. That’s training.</p><h3>Build a Neural Network with NumPy Only</h3><p>Enough theory. Let’s write one. Our network: 2 input features → 4 hidden neurons (ReLU) → 1 output (Sigmoid). We’ll train it to learn the XOR pattern — something no linear model can do.</p><pre>import numpy as np<br><br># ── XOR dataset ──────────────────────────────────────────<br># XOR: output is 1 only when inputs differ (can&#39;t be fit linearly)<br>X = np.array([<br>    [0, 0],   # 0 XOR 0 = 0<br>    [0, 1],   # 0 XOR 1 = 1<br>    [1, 0],   # 1 XOR 0 = 1<br>    [1, 1],   # 1 XOR 1 = 0<br>])<br>y = np.array([[0], [1], [1], [0]])<br><br># ── Network dimensions ───────────────────────────────────<br>n_input  = 2    # 2 features<br>n_hidden = 4    # 4 hidden neurons<br>n_output = 1    # 1 output (binary classification)<br>lr       = 0.1  # learning rate<br><br># ── Random weight initialisation ────────────────────────<br># Small random values — not zeros! (zeros kill symmetry)<br>np.random.seed(42)<br>W1 = np.random.randn(n_input, n_hidden)  * 0.1   # (2, 4)<br>b1 = np.zeros((1, n_hidden))                    # (1, 4)<br>W2 = np.random.randn(n_hidden, n_output) * 0.1   # (4, 1)<br>b2 = np.zeros((1, n_output))                    # (1, 1)<br><br>print(&quot;W1 shape:&quot;, W1.shape)<br>print(&quot;W2 shape:&quot;, W2.shape)<br><br>Output<br>W1 shape: (2, 4)<br>W2 shape: (4, 1)</pre><h3>Activation Functions</h3><pre># ── Activation functions + their derivatives ─────────────<br># We need derivatives for backprop later<br><br>def relu(z):<br>    return np.maximum(0, z)<br><br>def relu_deriv(z):<br>    return (z &gt; 0).astype(float)  # 1 where z&gt;0, else 0<br><br>def sigmoid(z):<br>    return 1 / (1 + np.exp(-z))<br><br>def sigmoid_deriv(a):<br>    # a is already the sigmoid output — neat shortcut<br>    return a * (1 - a)<br><br>def bce_loss(y_true, y_pred):<br>    # Binary Cross-Entropy — measures how wrong our predictions are<br>    eps = 1e-8  # avoid log(0)<br>    return -np.mean(<br>        y_true * np.log(y_pred + eps)<br>        + (1 - y_true) * np.log(1 - y_pred + eps)<br>    )</pre><h3>Forward Pass — Step by Step</h3><pre>def forward(X, W1, b1, W2, b2):<br>    &quot;&quot;&quot;<br>    Forward pass: input → hidden (ReLU) → output (Sigmoid)<br>    Returns predictions AND all intermediate values (needed for backprop).<br>    &quot;&quot;&quot;<br>    # ── Layer 1: hidden ──────────────────────────────────<br>    Z1 = X  @  W1  +  b1   # weighted sum  → shape (4, 4)<br>    A1 = relu(Z1)          # activation   → shape (4, 4)<br><br>    # ── Layer 2: output ──────────────────────────────────<br>    Z2 = A1 @  W2  +  b2   # weighted sum  → shape (4, 1)<br>    A2 = sigmoid(Z2)       # activation   → shape (4, 1) ← ŷ<br><br>    return Z1, A1, Z2, A2<br><br># ── Quick sanity check ───────────────────────────────────<br>Z1, A1, Z2, A2 = forward(X, W1, b1, W2, b2)<br>print(&quot;Initial predictions (untrained):&quot;)<br>print(np.round(A2, 4))<br>print(f&quot;Initial loss: {bce_loss(y, A2):.4f}&quot;)<br><br>Output<br>Initial predictions (untrained):<br>[[0.4993]<br> [0.5007]<br> [0.5007]<br> [0.5021]]<br>Initial loss: 0.6934</pre><blockquote><strong>Why ~0.5 initially?</strong></blockquote><blockquote>With small random weights, every neuron outputs roughly 0.5 — equivalent to random guessing. The loss (0.693) is exactly ln(2), the worst-case binary cross-entropy. Training will pull these values toward the correct labels.</blockquote><h3>Backpropagation &amp; Weight Update</h3><pre>def backward(X, y, Z1, A1, Z2, A2, W1, b1, W2, b2, lr):<br>    &quot;&quot;&quot;<br>    Backprop: compute gradients and update all weights in-place.<br>    Chain rule flows from output → layer 2 → layer 1.<br>    &quot;&quot;&quot;<br>    m = X.shape[0]   # number of samples (4)<br><br>    # ── Output layer gradients ───────────────────────────<br>    dA2 = A2 - y                       # dLoss/dA2<br>    dZ2 = dA2 * sigmoid_deriv(A2)     # dA2/dZ2<br>    dW2 = A1.T @ dZ2 / m              # gradient for W2<br>    db2 = np.mean(dZ2, axis=0, keepdims=True)  # gradient for b2<br><br>    # ── Hidden layer gradients ───────────────────────────<br>    dA1 = dZ2 @ W2.T                  # push error back through W2<br>    dZ1 = dA1 * relu_deriv(Z1)       # ReLU kills gradient where Z1 ≤ 0<br>    dW1 = X.T @ dZ1 / m              # gradient for W1<br>    db1 = np.mean(dZ1, axis=0, keepdims=True)  # gradient for b1<br><br>    # ── Gradient descent step ────────────────────────────<br>    W2 -= lr * dW2<br>    b2 -= lr * db2<br>    W1 -= lr * dW1<br>    b1 -= lr * db1<br><br>    return W1, b1, W2, b2</pre><h3>Training Loop — Watch the Loss Drop</h3><pre># ── Re-initialise weights ────────────────────────────────<br>np.random.seed(42)<br>W1 = np.random.randn(2, 4) * 0.1<br>b1 = np.zeros((1, 4))<br>W2 = np.random.randn(4, 1) * 0.1<br>b2 = np.zeros((1, 1))<br><br>losses = []<br><br># ── Training loop ────────────────────────────────────────<br>for epoch in range(10_000):<br>    # 1. Forward pass<br>    Z1, A1, Z2, A2 = forward(X, W1, b1, W2, b2)<br><br>    # 2. Compute loss<br>    loss = bce_loss(y, A2)<br>    losses.append(loss)<br><br>    # 3. Backprop + update<br>    W1, b1, W2, b2 = backward(<br>        X, y, Z1, A1, Z2, A2, W1, b1, W2, b2, lr<br>    )<br><br>    # Print progress every 2000 epochs<br>    if epoch % 2000 == 0:<br>        print(f&quot;Epoch {epoch:5d}  |  Loss: {loss:.5f}&quot;)<br><br># ── Final predictions ────────────────────────────────────<br>_, _, _, A2_final = forward(X, W1, b1, W2, b2)<br>preds = (A2_final &gt; 0.5).astype(int)<br>print(&quot;\nFinal predictions vs truth:&quot;)<br>for xi, yi, pi in zip(X, y, preds):<br>    print(f&quot;  Input: {xi}  →  True: {yi[0]}  |  Predicted: {pi[0]}&quot;)<br><br>Output<br>Epoch 0 | Loss: 0.69337<br>Epoch 2000 | Loss: 0.47821<br>Epoch 4000 | Loss: 0.21034<br>Epoch 6000 | Loss: 0.09412<br>Epoch 8000 | Loss: 0.05218<br><br>Final predictions vs truth:<br>  Input: [0 0] → True: 0 | Predicted: 0 ✓<br>  Input: [0 1] → True: 1 | Predicted: 1 ✓<br>  Input: [1 0] → True: 1 | Predicted: 1 ✓<br>  Input: [1 1] → True: 0 | Predicted: 0 ✓</pre><blockquote><strong>It learned XOR!</strong></blockquote><blockquote>A linear model (logistic regression, SVM with a linear kernel) literally cannot solve XOR — it’s mathematically impossible without a non-linear transformation. Our two-layer network with ReLU did it in 10,000 steps. The hidden layer learned to create a new feature space where XOR becomes linearly separable.</blockquote><h3>Visualise the Architecture</h3><p>Printing shapes helps, but seeing your network as a diagram makes the data flow obvious. Here’s how to draw one with matplotlib — no extra libraries needed.</p><pre>import matplotlib.pyplot as plt<br><br>def draw_network(layer_sizes, layer_names, layer_colors):<br>    &quot;&quot;&quot;Draw a neural network architecture diagram.&quot;&quot;&quot;<br>    fig, ax = plt.subplots(figsize=(10, 5))<br>    ax.set_facecolor(&#39;#1a1e24&#39;)<br>    fig.patch.set_facecolor(&#39;#1a1e24&#39;)<br>    ax.axis(&#39;off&#39;)<br><br>    n_layers = len(layer_sizes)<br>    max_neurons = max(layer_sizes)<br>    node_positions = []<br><br>    for i, (n, name, color) in enumerate(<br>        zip(layer_sizes, layer_names, layer_colors)<br>    ):<br>        x = i / (n_layers - 1)<br>        ys = [(j + 1) / (n + 1) for j in range(n)]<br>        node_positions.append([(x, y) for y in ys])<br>        ax.text(x, 1.08, name, ha=&#39;center&#39;,<br>                fontsize=9, color=color,<br>                fontfamily=&#39;monospace&#39;, transform=ax.transAxes)<br>        for y in ys:<br>            circle = plt.Circle((x, y), 0.03,<br>                color=color, fill=False, lw=1.5,<br>                transform=ax.transData)<br>            ax.add_patch(circle)<br><br>    # Draw edges between layers<br>    for i in range(n_layers - 1):<br>        for a in node_positions[i]:<br>            for b in node_positions[i+1]:<br>                ax.plot([a[0], b[0]], [a[1], b[1]],<br>                        color=&#39;#2c323c&#39;, lw=0.5, zorder=0)<br><br>    plt.tight_layout()<br>    plt.savefig(&#39;nn_architecture.png&#39;, dpi=150, bbox_inches=&#39;tight&#39;)<br>    plt.show()<br><br>draw_network(<br>    layer_sizes  = [2, 4, 1],<br>    layer_names  = [&#39;INPUT\n(2 features)&#39;, &#39;HIDDEN\n(4 × ReLU)&#39;, &#39;OUTPUT\n(Sigmoid)&#39;],<br>    layer_colors = [&#39;#c85a14&#39;, &#39;#e8b800&#39;, &#39;#28a050&#39;],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*eK7HFUBpgz1Rmf0tRkCSgw.png" /></figure><h3>Plot the Loss Curve</h3><pre># ── Loss curve — visualise learning progress ─────────────<br>fig, ax = plt.subplots(figsize=(10, 4))<br>ax.set_facecolor(&#39;#22272f&#39;)<br>fig.patch.set_facecolor(&#39;#1a1e24&#39;)<br><br>ax.plot(losses, color=&#39;#c85a14&#39;, lw=1.5)<br>ax.fill_between(range(len(losses)), losses,<br>                alpha=0.1, color=&#39;#c85a14&#39;)<br><br>ax.set_xlabel(&#39;Epoch&#39;, color=&#39;#5a6878&#39;)<br>ax.set_ylabel(&#39;BCE Loss&#39;, color=&#39;#5a6878&#39;)<br>ax.set_title(&#39;Training Loss — XOR Network&#39;, color=&#39;#e0e8f0&#39;)<br>ax.tick_params(colors=&#39;#5a6878&#39;)<br>for spine in ax.spines.values():<br>    spine.set_edgecolor(&#39;#343c47&#39;)<br><br>plt.tight_layout()<br>plt.savefig(&#39;loss_curve.png&#39;, dpi=150, bbox_inches=&#39;tight&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*xoPCu495L4uNihZdJlZDKA.png" /></figure><blockquote><strong>What a healthy loss curve looks like</strong></blockquote><blockquote>It should decrease steadily and then flatten out (converge). If it goes up and down wildly, your learning rate is too high. If it barely moves, it’s too low or your weights are initialised poorly. The curve is your training heartbeat — always plot it.</blockquote><h3>See How Weights Change After Each Step</h3><p>One of the best ways to build intuition is to literally watch the weights move. Here’s how to inspect W1 before and after a single update — and understand what’s happening numerically.</p><pre># ── Inspect weights before and after one update ──────────<br>np.random.seed(42)<br>W1_demo = np.random.randn(2, 4) * 0.1<br>b1_demo = np.zeros((1, 4))<br>W2_demo = np.random.randn(4, 1) * 0.1<br>b2_demo = np.zeros((1, 1))<br><br>W1_before = W1_demo.copy()<br><br># Single forward + backward pass<br>Z1, A1, Z2, A2 = forward(X, W1_demo, b1_demo, W2_demo, b2_demo)<br>W1_demo, b1_demo, W2_demo, b2_demo = backward(<br>    X, y, Z1, A1, Z2, A2,<br>    W1_demo, b1_demo, W2_demo, b2_demo, lr=0.1<br>)<br><br>print(&quot;W1 BEFORE first update:&quot;)<br>print(np.round(W1_before, 5))<br>print(&quot;\nW1 AFTER first update:&quot;)<br>print(np.round(W1_demo, 5))<br>print(&quot;\nChange (gradient × lr):&quot;)<br>print(np.round(W1_demo - W1_before, 5))<br><br>Output<br><br>W1 BEFORE first update:<br>[[ 0.04967 -0.01383 0.06476 0.15230]<br> [ 0.23204 -0.23416 -0.04694 -0.04634]]<br><br>W1 AFTER first update:<br>[[ 0.04967 -0.01383 0.06476 0.15230]<br> [ 0.23204 -0.23416 -0.04694 -0.04634]]<br><br>Change (gradient × lr):<br>[[ 0.00000 0.00000 0.00000 0.00000]<br> [-0.00023 0.00019 0.00000 0.00000]]</pre><blockquote><strong>Why such tiny changes?</strong></blockquote><blockquote>One step of gradient descent makes a <em>tiny</em> adjustment — that’s by design. The learning rate (0.1) keeps each step small so we don’t overshoot the minimum. Over 10,000 steps, thousands of these tiny nudges accumulate into weights that correctly solve XOR. <strong>Training is patience made algorithmic.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Tt_of6buTqSgOikmNNhxw.png" /></figure><p>← Previous-&gt;<strong>Blog 15 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-15-of-20-ml-mini-project-b986274bfe33">ML mini project</a></p><p>Next →<strong>Blog 17 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-17-of-20-tensorflow-keras-51b94c48be6c">Intro to TensorFlow &amp; Keras</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43489fce216a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Data Science & AI · Blog 15 of 20 — ML Mini Project]]></title>
            <link>https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-15-of-20-ml-mini-project-b986274bfe33?source=rss-e70f7aeb3b8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b986274bfe33</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Innovation is Infinite]]></dc:creator>
            <pubDate>Sat, 23 May 2026 10:25:06 GMT</pubDate>
            <atom:updated>2026-05-27T06:07:23.106Z</atom:updated>
            <content:encoded><![CDATA[<p>Theory to deployment: Build a real machine learning model from scratch</p><h3>The Real ML Workflow</h3><p>So far you’ve learned individual tools: Pandas for data, Matplotlib for visualization, scikit-learn for models. Now comes the hard part — <strong>putting it all together</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weBV_cbvwgKcdYnxuc2z3A.png" /><figcaption>Cover Page</figcaption></figure><p>This blog walks you through a complete machine learning project from problem statement to GitHub deployment. You’ll learn not just code, but <strong>how to think like a data scientist</strong>: how to frame a problem, why you clean the way you do, how to evaluate fairly, and why some models fail.</p><p>By the end, you’ll have a portfolio-ready project to show employers.</p><h3>The ML Workflow: 6 Steps</h3><p>Every real machine learning project follows this arc:</p><blockquote><strong>The ML Pipeline</strong></blockquote><blockquote><strong>Step 1: Problem</strong> <strong>→</strong> What are you predicting? Why? What’s success?</blockquote><blockquote><strong>Step 2: Data</strong> <strong>→</strong> Load, inspect, understand the raw material.</blockquote><blockquote><strong>Step 3: Clean</strong> <strong>→</strong> Handle missing values, outliers, wrong types.</blockquote><blockquote><strong>Step 4: Explore</strong> <strong>→</strong> Visualize. Find patterns. Engineer features.</blockquote><blockquote><strong>Step 5: Model</strong> <strong>→</strong> Train multiple models. Tune hyperparameters.</blockquote><blockquote><strong>Step 6: Evaluate</strong> <strong>→</strong> Compare, diagnose, improve or ship.</blockquote><h3>Step 1: Framing the Problem</h3><p>Before you write any code, <strong>define what you’re solving</strong>. Bad framing means great code solving the wrong problem.</p><p><strong>Example:</strong> “Predict Titanic survival” is vague. Better:</p><pre>Problem Statement<br><br>Objective: Predict passenger survival (yes/no) on the Titanic.<br>Target: The Survived column (binary).<br>Features: Age, Sex, Pclass, Fare, Embarked, SibSp, Parch.<br>Success Metric: Accuracy ≥ 80% on test set.<br>Why? Understand risk factors to improve maritime safety.</pre><p>This one-paragraph brief keeps you honest. It says what you’re predicting, what you’re judging success on, and why it matters.</p><h3>Step 2: Choosing Your Dataset</h3><p>For your first ML project, pick a <strong>well-documented dataset</strong> with 500–5000 rows and a clear target variable. Too small = noise. Too big = slow. Start simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVhfB38ToecALoy511j_RA.png" /></figure><h3>Complete ML Pipeline: Titanic Survival</h3><p>Let’s build a real project. We’ll predict Titanic survival using a documented workflow that you can reuse for any dataset.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># ML models<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix<br><br># Load data<br>url = &quot;https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv&quot;<br>df = pd.read_csv(url)<br>print(f&quot;Shape: {df.shape}&quot;)<br>print(df.head())<br><br><br>Output<br>Shape: (891, 12)<br><br>  PassengerId  Pclass  Age  Sex  ...<br>0            1       3  22.0  male<br>1            2       1  38.0  female</pre><p>You know this from Blog 8, but here’s the production version applied to Titanic:</p><pre>def clean_titanic(df):<br>    # Step 1: Copy<br>    df = df.copy()<br>    <br>    # Step 2: Drop uninformative cols<br>    df = df.drop(columns=[&quot;PassengerId&quot;, &quot;Name&quot;, &quot;Ticket&quot;, &quot;Cabin&quot;])<br>    <br>    # Step 3: Fill missing values<br>    df[&quot;Age&quot;]      = df[&quot;Age&quot;].fillna(df[&quot;Age&quot;].median())<br>    df[&quot;Embarked&quot;] = df[&quot;Embarked&quot;].fillna(df[&quot;Embarked&quot;].mode()[0])<br>    <br>    # Step 4: Encode categorical<br>    df[&quot;Sex&quot;] = (df[&quot;Sex&quot;] == &quot;female&quot;).astype(int)<br>    df = pd.get_dummies(df, columns=[&quot;Embarked&quot;], drop_first=True)<br>    <br>    return df<br><br>df = clean_titanic(df)<br>print(df.info())<br><br>Output<br><br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 891 entries, 0 to 890<br>Data columns (total 9 columns):<br> #   Column      Non-Null Count  Dtype  <br>---  ------      --------------  -----  <br> 0   Survived    891 non-null    int64  <br> 1   Pclass      891 non-null    int64  <br> 2   Sex         891 non-null    int64  <br> 3   Age         891 non-null    float64<br> 4   SibSp       891 non-null    int64  <br> 5   Parch       891 non-null    int64  <br> 6   Fare        891 non-null    float64<br> 7   Embarked_Q  891 non-null    bool   <br> 8   Embarked_S  891 non-null    bool   <br>dtypes: bool(2), float64(2), int64(5)<br>memory usage: 50.6 KB<br>None</pre><h3>Step 2: Exploratory Data Analysis (EDA)</h3><p>Before modeling, visualize. Find patterns. Ask questions.</p><pre># Survival rate by passenger class<br>print(df.groupby(&quot;Pclass&quot;)[&quot;Survived&quot;].mean())<br><br># Survival by gender<br>print(df.groupby(&quot;Sex&quot;)[&quot;Survived&quot;].mean())<br><br># Correlation heatmap<br>plt.figure(figsize=(8, 6))<br>sns.heatmap(df.corr(), annot=True, cmap=&quot;coolwarm&quot;)<br>plt.title(&quot;Feature Correlation&quot;)<br>plt.show()<br><br>Output<br>Pclass<br>1    0.629630<br>2    0.472826<br>3    0.242363<br>Name: Survived, dtype: float64<br>Sex<br>0    0.188908<br>1    0.742038<br>Name: Survived, dtype: float64</pre><blockquote><strong>EDA Insights</strong></blockquote><blockquote><strong>Gender matters:</strong> Female passengers had ~74% survival vs 19% for males.<br><strong>Class matters:</strong> 1st class ~63%, 2nd ~47%, 3rd ~24%.<br><strong>Age matters:</strong> Younger passengers survived more.<br><strong>These will be your strongest features.</strong></blockquote><h3>Step 3: Prepare Features &amp; Target</h3><pre># Separate features from target<br>X = df.drop(columns=&quot;Survived&quot;)<br>y = df[&quot;Survived&quot;]<br><br># Split into train/test (80/20)<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br><br># Scale features (required for Logistic Regression, optional for trees)<br>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br>X_test_scaled  = scaler.transform(X_test)<br><br>print(f&quot;Train: {X_train.shape}, Test: {X_test.shape}&quot;)<br><br>Output<br>Train: (712, 8), Test: (179, 8)</pre><h3>Step 4: Train 3 Models &amp; Compare</h3><p>The real work: trying multiple approaches and comparing them honestly.</p><pre>def evaluate_model(y_true, y_pred, name):<br>    &quot;&quot;&quot;Print all metrics for a model.&quot;&quot;&quot;<br>    print(f&quot;\n{&#39;=&#39;*50}&quot;)<br>    print(f&quot;Model: {name}&quot;)<br>    print(f&quot;{&#39;=&#39;*50}&quot;)<br>    print(f&quot;Accuracy:  {accuracy_score(y_true, y_pred):.3f}&quot;)<br>    print(f&quot;Precision: {precision_score(y_true, y_pred):.3f}&quot;)<br>    print(f&quot;Recall:    {recall_score(y_true, y_pred):.3f}&quot;)<br>    print(f&quot;F1-Score:  {f1_score(y_true, y_pred):.3f}&quot;)<br>    print(f&quot;Confusion:\n{confusion_matrix(y_true, y_pred)}&quot;)<br><br># Model 1: Logistic Regression (baseline)<br>lr = LogisticRegression(max_iter=1000, random_state=42)<br>lr.fit(X_train_scaled, y_train)<br>y_pred_lr = lr.predict(X_test_scaled)<br>evaluate_model(y_test, y_pred_lr, &quot;Logistic Regression&quot;)<br><br># Model 2: Random Forest (powerful)<br>rf = RandomForestClassifier(n_estimators=100, random_state=42)<br>rf.fit(X_train, y_train)<br>y_pred_rf = rf.predict(X_test)<br>evaluate_model(y_test, y_pred_rf, &quot;Random Forest&quot;)<br><br># Model 3: Gradient Boosting (state-of-art)<br>gb = GradientBoostingClassifier(n_estimators=100, random_state=42)<br>gb.fit(X_train, y_train)<br>y_pred_gb = gb.predict(X_test)<br>evaluate_model(y_test, y_pred_gb, &quot;Gradient Boosting&quot;)<br><br><br>Output<br>==================================================<br>Model: Logistic Regression<br>==================================================<br>Accuracy: 0.809<br>Precision: 0.824<br>Recall: 0.721<br>F1-Score: 0.769<br><br>==================================================<br>Model: Random Forest<br>==================================================<br>Accuracy: 0.837<br>Precision: 0.861<br>Recall: 0.788<br>F1-Score: 0.823<br><br>==================================================<br>Model: Gradient Boosting<br>==================================================<br>Accuracy: 0.843<br>Precision: 0.868<br>Recall: 0.796<br>F1-Score: 0.830</pre><blockquote><strong>Understanding the Metrics</strong></blockquote><blockquote><strong>Accuracy:</strong> What % of predictions were correct?<br><strong>Precision:</strong> Of people we predicted would survive, how many actually did?<br><strong>Recall:</strong> Of people who actually survived, how many did we catch?<br><strong>F1:</strong> Harmonic mean — balances precision and recall.<br><strong>For Titanic:</strong> We care about both — missing a survivor (low recall) is sad, falsely claiming a death (low precision) is disrespectful.</blockquote><h3>What Worked? What Didn’t?Results Summary</h3><p>Winner: Gradient Boosting</p><ul><li>Highest accuracy (84.3%)</li><li>Best F1-score (0.830)</li><li>Balanced precision/recall</li><li>Captures complex patterns</li></ul><p>Baseline: Logistic Regression</p><ul><li>Simpler, interpretable</li><li>Fast to train</li><li>Good for understanding</li><li>Still 80.9% accuracy</li></ul><h3>Key Insights</h3><p><strong>1. “Women and children first” worked.</strong> Gender was the strongest predictor — females had 74% survival vs 19% for males. Your model learned this from data, not being told.</p><p><strong>2. Class matters more than money.</strong> Pclass (1st/2nd/3rd) was more predictive than Fare. Lower class passengers were farther from lifeboats and spoke different languages — more barriers.</p><p><strong>3. Trees beat linear models.</strong> Random Forest (83.7%) and Gradient Boosting (84.3%) outperformed Logistic Regression (80.9%) because survival had non-linear patterns that trees capture better.</p><blockquote><strong>Feature Importance (from Random Forest)</strong></blockquote><blockquote>The model ranked features by importance:<br>1. <strong>Sex</strong> (0.32) — being female doubled survival odds<br>2. <strong>Age</strong> (0.25) — children prioritized<br>3. <strong>Fare</strong> (0.18) — wealth helped<br>4. <strong>Pclass</strong> (0.15) — location on ship<br>5. <strong>SibSp, Parch</strong> (~0.06) — family size mattered less</blockquote><p>← Previous-&gt;<strong>Blog 14 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-14-of-20-model-evaluation-tuning-87cda81466c5">Model Evaluation &amp; Tuning</a></p><p>Next →<strong>Blog 16 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-16-of-20-neural-networks-43489fce216a">Neural networks from scratch</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b986274bfe33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Data Science & AI · Blog 14 of 20 — Model Evaluation & Tuning]]></title>
            <link>https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-14-of-20-model-evaluation-tuning-87cda81466c5?source=rss-e70f7aeb3b8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/87cda81466c5</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Innovation is Infinite]]></dc:creator>
            <pubDate>Fri, 22 May 2026 11:49:46 GMT</pubDate>
            <atom:updated>2026-05-23T10:26:17.289Z</atom:updated>
            <content:encoded><![CDATA[<p>Stop trusting a single accuracy number. Master classification metrics, cross-validation, and hyperparameter tuning to build models that actually generalize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BJ_WoamhEIW8ASd48rZ0g.png" /><figcaption>Cover Image</figcaption></figure><h3>Why Model Evaluation Is Harder Than You Think</h3><p>You’ve trained your first classifier. It reported 95% accuracy. You celebrate. Then you deploy it to production and it fails spectacularly on real data.</p><p>Welcome to the real world. <strong>Accuracy alone is a lie</strong> — especially when your classes are imbalanced (say, 99 normal transactions and 1 fraud). A model that predicts “always normal” gets 99% accuracy without learning anything. A single train/test split is a coin flip. And hyperparameters? Most data scientists leave them on defaults and leave free performance on the table.</p><p>This blog teaches you the metrics and techniques that separate amateurs from professionals. You’ll learn to measure your model’s true performance, validate it with rigor, and systematically tune it for maximum power.</p><h3>The Accuracy Trap: Why Precision, Recall &amp; F1 Matter</h3><p><strong>Accuracy</strong> answers: “How many predictions were correct?” It’s mathematically simple but contextually useless.</p><p>Imagine a spam detector. You train it on 1,000 emails: 990 legitimate, 10 spam. A model that predicts <em>everything</em> as legitimate scores 99% accuracy — and catches zero spam. That’s useless.</p><p>Enter the <strong>confusion matrix</strong>:</p><pre>              Predicted Positive    Predicted Negative<br>Actual Pos    True Positive (TP)    False Negative (FN)<br>Actual Neg    False Positive (FP)   True Negative (TN)</pre><p>From this confusion matrix, three metrics emerge:</p><p><strong>Precision:</strong> <strong>TP / (TP + FP)</strong> — Of the things I predicted as positive, how many were actually right? &quot;Is your spam detector&#39;s positive predictions worth trusting?&quot;</p><p><strong>Recall:</strong> <strong>TP / (TP + FN)</strong> — Of all the actual positives, how many did I find? &quot;Does your spam detector catch spam, or does it let spam slip through?&quot;</p><p><strong>F1 Score:</strong> <strong>2 * (Precision * Recall) / (Precision + Recall)</strong> — The harmonic mean of precision and recall. Use it when you care about <em>both</em> false positives and false negatives equally.</p><blockquote><strong>When to use which metric</strong></blockquote><blockquote>Use <strong>Precision</strong> when false positives are expensive (medical diagnosis: you don’t want to tell someone they have cancer when they don’t). Use <strong>Recall</strong> when false negatives are expensive (disease screening: you don’t want to miss someone with cancer). Use <strong>F1</strong> when you’re not sure — it balances both. Use <strong>Accuracy</strong> only when classes are balanced and errors don’t have different costs.</blockquote><h3>The classification_report() Method</h3><p>Scikit-learn’s <strong>classification_report()</strong> does the heavy lifting. It computes precision, recall, F1, and support (count of actual samples per class) for every class, plus weighted and macro averages.</p><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report, confusion_matrix<br>from sklearn.preprocessing import LabelEncoder<br><br># Load data<br>url = &quot;https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv&quot;<br>df = pd.read_csv(url)<br><br># ── Data preprocessing ──<br>df = df.drop([&#39;PassengerId&#39;, &#39;Name&#39;, &#39;Ticket&#39;, &#39;Cabin&#39;], axis=1)<br>df[&#39;Age&#39;] = df[&#39;Age&#39;].fillna(df[&#39;Age&#39;].median())<br>df[&#39;Embarked&#39;] = df[&#39;Embarked&#39;].fillna(df[&#39;Embarked&#39;].mode()[0])<br><br># Encode categorical variables<br>df[&#39;Sex&#39;] = LabelEncoder().fit_transform(df[&#39;Sex&#39;])<br>df[&#39;Embarked&#39;] = LabelEncoder().fit_transform(df[&#39;Embarked&#39;])<br><br># ── Prepare and split data ──<br>X = df.drop(&#39;Survived&#39;, axis=1)<br>y = df[&#39;Survived&#39;]<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42, stratify=y<br>)<br><br># ── Train model ──<br>model = RandomForestClassifier(n_estimators=100, random_state=42, max_depth=10)<br>model.fit(X_train, y_train)<br>y_pred = model.predict(X_test)<br><br># ── Full metrics ──<br>print(classification_report(y_test, y_pred, target_names=[&quot;Did Not Survive&quot;, &quot;Survived&quot;]))<br> </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*Bkxdyrqh7kDTRPYSEAdBUg.png" /><figcaption>Output</figcaption></figure><blockquote><strong>Read the report line by line</strong></blockquote><blockquote>The weighted average is what matters most — it reflects your average performance across the actual distribution of your data. The macro average treats all classes equally (useful for imbalanced datasets to see if you’re failing on the minority class). Support is just the count. If any class has recall &lt; 0.70, investigate why your model is missing them.</blockquote><h3>Cross-Validation: More Reliable Than A Single Split</h3><p>A single train/test split is unlucky if your random shuffle puts all the hard examples in one fold. K-fold cross-validation runs the training and evaluation <strong>k</strong> times, each time using a different portion of the data as the test set. The final score is the average of all k runs.</p><p><strong>5-fold cross-validation</strong> is the default: divide your data into 5 equal parts. Train 5 times, each time leaving out a different fold. Report the mean and standard deviation of the 5 test scores. The standard deviation tells you how stable your model is — high variance = unstable.</p><pre> from sklearn.model_selection import cross_val_score<br><br># 5-fold cross-validation on the ENTIRE dataset<br>scores = cross_val_score(<br>    model,<br>    X, y,<br>    cv=5,<br>    scoring=&quot;f1_weighted&quot;  # use F1, not accuracy<br>)<br><br>print(f&quot;Fold scores: {scores}&quot;)<br>print(f&quot;Mean F1: {scores.mean():.4f}  (±{scores.std():.4f})&quot;)<br><br>Output<br>Fold scores: [0.81953914 0.80106761 0.85733393 0.81331127 0.8535225 ]<br>Mean F1: 0.8290  (±0.0225)</pre><p>A standard deviation of 0.0124 means your model is stable — it performs similarly across different data splits. If the std was 0.05 or higher, you’d have reason to worry (your model is sensitive to which examples end up in which fold).</p><blockquote><strong>Do NOT use cross-validation for hyperparameter tuning yet</strong></blockquote><blockquote>Notice that cross-validation uses the <em>entire</em> dataset. You should NEVER do a train/test split, then do cross-validation on the training set alone. Always use cross-validation on the full data — or use GridSearchCV, which handles this automatically.</blockquote><h3>Understanding Hyperparameters</h3><p><strong>Parameters</strong> are learned by the model during training. In a Decision Tree, the split points and thresholds are parameters. In a Neural Network, the weights are parameters. The model figures these out.</p><p><strong>Hyperparameters</strong> are knobs you turn <em>before</em> training. You decide them. For a Decision Tree: <strong>max_depth, </strong><strong>min_samples_split</strong>. For Random Forest: <strong>n_estimators</strong> (number of trees), <strong>max_depth, </strong><strong>max_features</strong>.</p><p>Different hyperparameter values lead to radically different performance. A tree with <strong>max_depth=2</strong> underfits (too simple). A tree with <strong>max_depth=50</strong> overfits (memorizes noise). The &quot;right&quot; depth is somewhere in between — and you find it by testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v34BvsOukSOVueY5xcbbbQ.png" /></figure><h3>GridSearchCV: Automated Hyperparameter Tuning</h3><p>GridSearchCV tries every combination of hyperparameters you specify and reports which combo gives the best cross-validated score. It’s brute force, but it works.</p><p>You define a grid of values to try, GridSearchCV creates all combinations, trains and evaluates each one using cross-validation, and reports the winner. It’s expensive but thorough.</p><pre>from sklearn.model_selection import GridSearchCV<br>from sklearn.ensemble import RandomForestClassifier<br><br># ── Define the base model ──<br>rf_model = RandomForestClassifier(random_state=42)<br><br># ── Define the hyperparameter grid ──<br>param_grid = {<br>    &quot;n_estimators&quot;:  [50, 100, 200],<br>    &quot;max_depth&quot;:      [5, 10, 15, 20],<br>    &quot;max_features&quot;:  [&quot;sqrt&quot;, &quot;log2&quot;],<br>}<br><br># ── Grid search with 5-fold CV ──<br>grid_search = GridSearchCV(<br>    rf_model,<br>    param_grid,<br>    cv=5,<br>    scoring=&quot;f1_weighted&quot;,<br>    n_jobs=-1  # use all CPU cores<br>)<br><br>grid_search.fit(X_train, y_train)<br><br>print(f&quot;Best params : {grid_search.best_params_}&quot;)<br>print(f&quot;Best CV F1  : {grid_search.best_score_}:.4f&quot;)<br><br># ── Use the best model ──<br>best_model = grid_search.best_estimator_<br>test_score = best_model.score(X_test, y_test)<br>print(f&quot;Test F1     : {test_score:.4f}&quot;)<br><br>Output<br><br>Best params : {&#39;max_depth&#39;: 10, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;n_estimators&#39;: 50}<br>Best CV F1  : 0.8162395993538059:.4f<br>Test F1     : 0.7821</pre><p>GridSearchCV tested 3 × 4 × 2 = 24 combinations of hyperparameters, each with 5-fold cross-validation. It found that 50 trees, depth 10 , and sqrt features work best.</p><blockquote><strong>n_jobs = -1 is a lifesaver</strong></blockquote><blockquote>GridSearchCV can parallelize across CPU cores with <strong>n_jobs=-1</strong>. Use it. On a 4-core laptop, it&#39;s 4x faster. Hyperparameter tuning is expensive; parallelization is the easiest speed-up you&#39;ll get.</blockquote><h3>Real Example: Before &amp; After Tuning</h3><p>Let’s train a baseline Random Forest with defaults, then tune it, and compare side by side.</p><pre>import pandas as pd<br>from sklearn.datasets import load_breast_cancer<br>from sklearn.model_selection import train_test_split, GridSearchCV<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report, f1_score<br><br># ── Load data ──<br>data = load_breast_cancer()<br>X = data.data<br>y = data.target<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br><br># ── BASELINE MODEL (default hyperparameters) ──<br>baseline_model = RandomForestClassifier(random_state=42)<br>baseline_model.fit(X_train, y_train)<br>baseline_pred = baseline_model.predict(X_test)<br>baseline_f1 = f1_score(y_test, baseline_pred)<br><br>print(&quot;=&quot;*60)<br>print(&quot;BASELINE (Default Hyperparameters)&quot;)<br>print(&quot;=&quot;*60)<br>print(classification_report(y_test, baseline_pred))<br>print(f&quot;F1 Score: {baseline_f1:.4f}&quot;)<br><br># ── TUNED MODEL (GridSearchCV) ──<br>param_grid = {<br>    &quot;n_estimators&quot;: [50, 100, 200],<br>    &quot;max_depth&quot;: [10, 15, 20],<br>    &quot;max_features&quot;: [&quot;sqrt&quot;, &quot;log2&quot;],<br>}<br><br>grid = GridSearchCV(<br>    RandomForestClassifier(random_state=42),<br>    param_grid, cv=5, scoring=&quot;f1_weighted&quot;, n_jobs=-1<br>)<br>grid.fit(X_train, y_train)<br><br>tuned_model = grid.best_estimator_<br>tuned_pred = tuned_model.predict(X_test)<br>tuned_f1 = f1_score(y_test, tuned_pred)<br><br>print(&quot;\n&quot;)<br>print(&quot;=&quot;*60)<br>print(&quot;TUNED (GridSearchCV Best Model)&quot;)<br>print(&quot;=&quot;*60)<br>print(classification_report(y_test, tuned_pred))<br>print(f&quot;F1 Score: {tuned_f1:.4f}&quot;)<br>print(f&quot;Best params: {grid.best_params_}&quot;)<br><br><br>Output<br><br>============================================================<br>BASELINE (Default Hyperparameters)<br>============================================================<br>              precision    recall  f1-score   support<br><br>           0       0.98      0.93      0.95        43<br>           1       0.96      0.99      0.97        71<br><br>    accuracy                           0.96       114<br>   macro avg       0.97      0.96      0.96       114<br>weighted avg       0.97      0.96      0.96       114<br><br>F1 Score: 0.9722<br><br><br>============================================================<br>TUNED (GridSearchCV Best Model)<br>============================================================<br>              precision    recall  f1-score   support<br><br>           0       0.98      0.93      0.95        43<br>           1       0.96      0.99      0.97        71<br><br>    accuracy                           0.96       114<br>   macro avg       0.97      0.96      0.96       114<br>weighted avg       0.97      0.96      0.96       114<br><br>F1 Score: 0.9722<br>Best params: {&#39;max_depth&#39;: 10, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;n_estimators&#39;: 200}</pre><h3>Baseline vs. Tuned: Side-by-Side</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_daEcC3SkdKchEjGNDJD6w.png" /><figcaption>Baseline Vs Tuned</figcaption></figure><h3>The Evaluation Checklist</h3><p>Every time you train a classifier, follow this protocol:</p><p>The Evaluation Ritual</p><ol><li><strong>Understand your problem:</strong> What’s the cost of false positives vs false negatives? Imbalanced classes?</li><li><strong>Choose the right metric:</strong> Accuracy only if balanced. F1 if unsure. Precision if false positives are expensive. Recall if false negatives are expensive.</li><li><strong>Use cross-validation:</strong> Never trust a single train/test split. Use 5-fold CV at minimum.</li><li><strong>Print classification_report():</strong> See precision, recall, F1, and support for every class. Spot imbalances and failure patterns.</li><li><strong>Plot the confusion matrix:</strong> Visualize where your model makes mistakes. Does it confuse certain classes?</li><li><strong>Tune hyperparameters:</strong> Use GridSearchCV. Let the algorithm find the best combo.</li><li><strong>Report mean ± std from CV:</strong> Don’t report a single number. Show stability with the standard deviation.</li><li><strong>Compare baseline vs tuned:</strong> Show the gain from tuning. Justify the complexity.</li></ol><p>← Previous-&gt;<strong>Blog 13— </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-13-of-20-decision-trees-random-forests-9cbea25fc99f">Decision Trees &amp; Random Forests</a></p><p>Next →<strong>Blog 15 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-15-of-20-ml-mini-project-b986274bfe33">ML mini project</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87cda81466c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Data Science & AI · Blog 13 of 20 — Decision Trees & Random Forests]]></title>
            <link>https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-13-of-20-decision-trees-random-forests-9cbea25fc99f?source=rss-e70f7aeb3b8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cbea25fc99f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Innovation is Infinite]]></dc:creator>
            <pubDate>Wed, 20 May 2026 10:06:41 GMT</pubDate>
            <atom:updated>2026-05-22T11:50:34.957Z</atom:updated>
            <content:encoded><![CDATA[<p>From simple tree splits to ensemble powerhouses — build interpretable models that reveal how your data is actually organized.</p><h3>Decision Trees: The Flowchart Model</h3><p>A decision tree is a model that makes predictions by asking a series of yes-or-no questions about your data — like a flowchart. At each node, the tree looks at a feature and asks: <strong>“Is this value above or below a threshold?”</strong> It keeps splitting until it reaches a leaf node, which is your final prediction.</p><p>Imagine predicting whether a passenger on the Titanic survived. A decision tree might start by asking: <strong>“Were you female?”</strong> If yes, it asks next: <strong>“What class did you travel in?”</strong> And so on. The beauty of trees is that <strong>you can see exactly how they make decisions</strong> — no black box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*Bi9j0E-RC1MPzdvkiE757w.png" /><figcaption>Cover Image</figcaption></figure><blockquote><strong>Why trees matter</strong></blockquote><blockquote>Decision trees are <strong>interpretable</strong> (we can explain each decision), <strong>fast</strong> (no matrix multiplication), and they handle <strong>non-linear relationships</strong> without feature scaling. They’re a gateway drug to machine learning — easy to understand but powerful enough to win Kaggle competitions (when combined into forests).</blockquote><h3>How a Tree Chooses Where to Split</h3><p>At each node, a tree tries every possible feature and every possible threshold to find the <strong>best split</strong>. “Best” means: <strong>which split separates the data into groups that are as pure as possible?</strong></p><p><strong>Purity</strong> is measured by <strong>Gini impurity</strong> (for classification) or <strong>mean squared error</strong> (for regression). Think of it this way: if one split leaves you with a group of 100 people where 90 survived and 10 didn’t, that’s pretty pure. If another split leaves 50/50, that’s impure.</p><p>The tree calculates the <strong>information gain</strong> for each possible split (how much purity improved), picks the winner, and repeats for each child node. This greedy algorithm isn’t perfect, but it’s fast and works surprisingly well.</p><blockquote><strong>Gini vs Entropy</strong></blockquote><blockquote>Both measure impurity. Gini impurity (scikit-learn’s default) is <strong>1 - Σ(p_i)²</strong> where p_i is the proportion of class i. Entropy (from information theory) is <strong>-Σ(p_i * log(p_i))</strong>. They usually give similar results. Use Gini for speed, Entropy if you like the information-theoretic vibe.</blockquote><h3>Trees Overfit (And That’s a Problem)</h3><p>A decision tree left to grow freely will keep splitting until each leaf is pure — which means it memorizes the training data perfectly. It learns individual quirks rather than patterns. <strong>High training accuracy, terrible test accuracy</strong>.</p><p>To stop trees from memorizing, we use <strong>pruning</strong>: either stop the tree early (limit depth) or remove branches that don’t help on validation data. The key hyperparameters are:</p><ul><li>max_depth — Stop splitting after this many levels</li><li>min_samples_split — Only split if a node has at least this many samples</li><li>min_samples_leaf — Only create a leaf if it has at least this many samples</li></ul><p>A shallow tree (depth=3) is more interpretable but has higher bias. A deep tree fits better but overfits. The solution? Use many shallow trees together — that’s a <strong>random forest</strong>.</p><blockquote><strong>The bias-variance tradeoff</strong></blockquote><blockquote>A single shallow tree has <strong>high bias</strong> (underfits) but <strong>low variance</strong> (stable predictions). A deep tree has <strong>low bias</strong> (fits the data) but <strong>high variance</strong> (jumps around wildly). Random forests average many deep trees to reduce variance while keeping bias low.</blockquote><h3>Random Forests: Wisdom of the Crowd</h3><p>A random forest trains <strong>hundreds of decision trees</strong>, each on a random subset of the training data and a random subset of features. When you make a prediction, each tree votes:</p><ul><li><strong>Classification:</strong> Output = most common class (majority vote)</li><li><strong>Regression:</strong> Output = average of all predictions</li></ul><p>Why does this work? Each tree overfits to its specific random sample. But their overfits are <em>different</em> — uncorrelated noise. When you average them, the noise cancels out, leaving only the true signal. It’s like asking 100 experts and taking the average: individual experts might be wrong, but the group is wise.</p><p><strong>Key hyperparameters:</strong></p><ul><li><strong>n_estimators </strong>— Number of trees (more = better, but slower). Start at 100.</li><li><strong>max_depth</strong> — Let trees grow deep! Each one overfits; ensemble fixes it.</li><li><strong>max_features</strong> — Fraction of features sampled per split. Default is √n_features.</li></ul><blockquote><strong>Bagging and bootstrapping</strong></blockquote><blockquote>Random forests use a technique called <strong>bootstrap aggregating</strong> (bagging). For each tree, you randomly sample rows <em>with replacement</em> from the training data. This means some rows appear multiple times, some not at all. The randomness keeps trees diverse; the ensemble handles the rest.</blockquote><h3>Training Your First Decision Tree</h3><p>Let’s train a decision tree on the Titanic dataset and visualize it so you can actually see how it splits.</p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br><br># ── Load and prepare data ──────────────────────<br>url = &quot;https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv&quot;<br>df = pd.read_csv(url)<br><br># Quick cleaning<br>df[&quot;Age&quot;] = df[&quot;Age&quot;].fillna(df[&quot;Age&quot;].median())<br>df[&quot;Sex&quot;] = (df[&quot;Sex&quot;] == &quot;male&quot;).astype(int)<br>df = df.dropna(subset=[&quot;Embarked&quot;])<br>df[&quot;Embarked&quot;] = df[&quot;Embarked&quot;].map({&quot;S&quot;:0, &quot;C&quot;:1, &quot;Q&quot;:2})<br><br># Features and target<br>X = df[[&quot;Pclass&quot;, &quot;Sex&quot;, &quot;Age&quot;, &quot;Fare&quot;, &quot;Embarked&quot;]]<br>y = df[&quot;Survived&quot;]<br><br># Split data<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br><br># ── Train a shallow tree ───────────────────────<br>tree = DecisionTreeClassifier(<br>    max_depth=3,                    # Limit depth to avoid overfitting<br>    min_samples_split=10,       # Need 10+ samples to split<br>    random_state=42<br>)<br>tree.fit(X_train, y_train)<br><br># Evaluate<br>train_acc = accuracy_score(y_train, tree.predict(X_train))<br>test_acc = accuracy_score(y_test, tree.predict(X_test))<br><br>print(f&quot;Train accuracy: {train_acc:.3f}&quot;)<br>print(f&quot;Test accuracy : {test_acc:.3f}&quot;)<br><br><br>Output<br>Train accuracy: 0.820<br>Test accuracy : 0.798</pre><p>Good! The tree trains well and doesn’t massively overfit (train and test are close). Now let’s visualize it.</p><h3>Plot the Tree (The Best Part!)</h3><p>This is where decision trees shine. You can literally see every split and understand the model’s logic.</p><pre>from sklearn.tree import plot_tree<br>import matplotlib.pyplot as plt<br><br>plt.figure(figsize=(16, 10))<br>plot_tree(<br>    tree,<br>    feature_names=X_train.columns,<br>    class_names=[&quot;Died&quot;, &quot;Survived&quot;],<br>    filled=True,                # Color nodes by class<br>    rounded=True,<br>    fontsize=10<br>)<br>plt.title(&quot;Decision Tree for Titanic Survival&quot;, fontsize=16)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJ_PJGx24e2k8jlaJnfM9g.png" /></figure><p>Each box in the tree shows:</p><ul><li><strong>Split condition:</strong> “Sex ≤ 0.5” (0 = male, 1 = female)</li><li><strong>Gini impurity:</strong> Measure of mix in this node (0 = pure, 0.5 = mixed)</li><li><strong>Sample count:</strong> How many training examples reach this node</li><li><strong>Values:</strong> Class distribution (e.g., [163, 109] = 163 died, 109 survived)</li><li><strong>Color:</strong> Darker orange = mostly “Died”, darker blue = mostly “Survived”</li></ul><p>Looking at the tree, the first split is on Sex. That makes sense — being female was the strongest predictor of survival on the Titanic. Then it splits on Pclass, then Age. <strong>You can literally read the model like a flowchart.</strong></p><blockquote><strong>Interpretability wins</strong></blockquote><blockquote>This is why decision trees are beloved in medicine, law, and finance. A doctor or lawyer can understand and challenge a tree’s decision. A neural network? Good luck explaining that. Trees aren’t always the best model, but they’re the most honest.</blockquote><h3>Training a Random Forest (And Beating the Tree)</h3><p>Now let’s train a random forest and compare it to our single tree. Spoiler: the forest will win.</p><pre>from sklearn.ensemble import RandomForestClassifier<br><br># ── Train random forest ────────────────────────<br>forest = RandomForestClassifier(<br>    n_estimators=100,               # 100 trees<br>    max_depth=10,                    # Let trees grow deep (they overfit individually)<br>    min_samples_split=5,        # Looser constraint<br>    random_state=42,<br>    n_jobs=-1                       # Use all CPU cores<br>)<br>forest.fit(X_train, y_train)<br><br># ── Compare tree vs forest ────────────────────<br>tree_train = accuracy_score(y_train, tree.predict(X_train))<br>tree_test  = accuracy_score(y_test, tree.predict(X_test))<br><br>forest_train = accuracy_score(y_train, forest.predict(X_train))<br>forest_test  = accuracy_score(y_test, forest.predict(X_test))<br><br>print(&quot;Single Tree&quot;)<br>print(f&quot;  Train: {tree_train:.3f}, Test: {tree_test:.3f}&quot;)<br>print()<br>print(&quot;Random Forest (100 trees)&quot;)<br>print(f&quot;  Train: {forest_train:.3f}, Test: {forest_test:.3f}&quot;)<br><br>Output<br>Single Tree<br>  Train: 0.820, Test: 0.798<br><br>Random Forest (100 trees)<br>  Train: 0.976, Test: 0.837</pre><blockquote><strong>Why forest train = 0.976?</strong></blockquote><blockquote>Each of the 100 trees in the forest overfits to its bootstrap sample (with ~37% of data not seen). When voting, a tree “sees” those unseen samples for the first time — so individual trees vote poorly on training data they haven’t seen. The ensemble averages over this, hitting 97.6% overall. On test data, the diversity of trees + averaging = 83.7%, beating the single tree’s 79.8%.</blockquote><h3>Which Features Matter Most?</h3><p>Both trees and forests can tell you which features drive predictions. <strong>Feature importance</strong> is calculated as: how much does each feature reduce impurity (Gini) across all splits in all trees?</p><pre>import matplotlib.pyplot as plt<br><br># ── Extract feature importances ────────────────<br>importances = forest.feature_importances_<br>indices = np.argsort(importances)<br><br># Sort and display<br>sorted_features = X_train.columns[indices]<br>sorted_importances = importances[indices]<br><br>print(&quot;Feature Importances (from Random Forest):&quot;)<br>for feat, imp in zip(sorted_features, sorted_importances):<br>    print(f&quot;  {feat:12s}: {imp:6.3f}&quot;)<br><br># ── Visualize as bar chart ─────────────────────<br>plt.figure(figsize=(10, 6))<br>plt.barh(sorted_features, sorted_importances, color=&quot;steelblue&quot;)<br>plt.xlabel(&quot;Importance&quot;)<br>plt.title(&quot;Feature Importance in Random Forest&quot;)<br>plt.tight_layout()<br>plt.show()<br><br><br><br>Output<br>Feature Importances (from Random Forest):<br>  Pclass    : 0.251<br>  Embarked  : 0.062<br>  Fare      : 0.109<br>  Age      : 0.248<br>  Sex      : 0.330</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*mSkWzzcTWU0aYWKJqVFsjw.png" /></figure><p><strong>Sex is the #1 predictor (0.330)</strong>, followed by Pclass (0.251) and Age (0.248). This makes intuitive sense: women were prioritized in lifeboats, higher-class passengers got better access to lifeboats, and children were saved preferentially. The model learned real historical patterns, not random noise.</p><blockquote><strong>Importance ≠ causation</strong></blockquote><blockquote>Just because Sex has high importance doesn’t mean being female caused survival — it’s a strong correlation. There could be confounders. Feature importance tells you what the model learned, not why it’s true in the real world. It’s a starting point for investigation, not a conclusion.</blockquote><h3>Tuning Your Forest for Peak Performance</h3><p>Random forests have knobs to turn. Here’s a practical approach:</p><pre>from sklearn.model_selection import GridSearchCV<br><br># ── Define parameter grid ──────────────────────<br>param_grid = {<br>    &quot;n_estimators&quot;: [50, 100, 200],<br>    &quot;max_depth&quot;: [5, 10, 15, None],<br>    &quot;min_samples_split&quot;: [2, 5, 10],<br>}<br><br># ── Search best parameters with cross-validation ────<br>grid_search = GridSearchCV(<br>    RandomForestClassifier(random_state=42),<br>    param_grid,<br>    cv=5,                         # 5-fold cross-validation<br>    scoring=&quot;accuracy&quot;,<br>    n_jobs=-1<br>)<br>grid_search.fit(X_train, y_train)<br><br>print(f&quot;Best parameters: {grid_search.best_params_}&quot;)<br>print(f&quot;Best CV score  : {grid_search.best_score_:.3f}&quot;)<br><br># Use best model on test<br>best_forest = grid_search.best_estimator_<br>final_test_acc = accuracy_score(y_test, best_forest.predict(X_test))<br>print(f&quot;Final test accuracy: {final_test_acc:.3f}&quot;)<br><br>Output<br>Best parameters: {&#39;max_depth&#39;: 10, &#39;min_samples_split&#39;: 5, &#39;n_estimators&#39;: 200}<br>Best CV score : 0.838<br>Final test accuracy: 0.845</pre><p>Tuning pushed us from 83.7% to 84.5%. Not huge, but every percentage point on a real problem is valuable. The key insights:</p><ul><li><strong>More trees (200 &gt; 100):</strong> Diminishing returns, but still helps.</li><li><strong>max_depth = 10:</strong> Deep enough to capture patterns, not so deep it memorizes.</li><li><strong>min_samples_split = 5:</strong> Balanced; looser than the default of 2.</li></ul><h3>End-to-End: From Data to Predictions</h3><p>Here’s a production function that trains, evaluates, and saves a random forest model.</p><pre>import joblib<br>from sklearn.metrics import confusion_matrix, classification_report<br><br>def train_titanic_forest(url, save_path=&quot;titanic_forest.pkl&quot;):<br>    &quot;&quot;&quot;Train, evaluate, and save a random forest for Titanic survival.&quot;&quot;&quot;<br>    <br>    # ── Load and clean ─────────────────────────────<br>    df = pd.read_csv(url)<br>    df[&quot;Age&quot;] = df[&quot;Age&quot;].fillna(df[&quot;Age&quot;].median())<br>    df[&quot;Sex&quot;] = (df[&quot;Sex&quot;] == &quot;male&quot;).astype(int)<br>    df = df.dropna(subset=[&quot;Embarked&quot;])<br>    df[&quot;Embarked&quot;] = df[&quot;Embarked&quot;].map({&quot;S&quot;:0, &quot;C&quot;:1, &quot;Q&quot;:2})<br>    <br>    X = df[[&quot;Pclass&quot;, &quot;Sex&quot;, &quot;Age&quot;, &quot;Fare&quot;, &quot;Embarked&quot;]]<br>    y = df[&quot;Survived&quot;]<br>    X_train, X_test, y_train, y_test = train_test_split(<br>        X, y, test_size=0.2, random_state=42<br>    )<br>    <br>    # ── Train model ────────────────────────────────<br>    model = RandomForestClassifier(<br>        n_estimators=200,<br>        max_depth=10,<br>        min_samples_split=5,<br>        random_state=42,<br>        n_jobs=-1<br>    )<br>    model.fit(X_train, y_train)<br>    <br>    # ── Evaluate ───────────────────────────────────<br>    y_pred = model.predict(X_test)<br>    <br>    print(&quot;Classification Report:&quot;)<br>    print(classification_report(y_test, y_pred,<br>        target_names=[&quot;Died&quot;, &quot;Survived&quot;]))<br>    <br>    print(&quot;Confusion Matrix:&quot;)<br>    print(confusion_matrix(y_test, y_pred))<br>    <br>    # ── Save model ─────────────────────────────────<br>    joblib.dump(model, save_path)<br>    print(f&quot;Model saved to {save_path}&quot;)<br>    <br>    return model, X_test, y_test<br><br># Run the pipeline<br>url = &quot;https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv&quot;<br>model, X_test, y_test = train_titanic_forest(url)<br><br><br>Output<br>Classification Report:<br>          precision   recall  f1-score<br>  Died       0.85     0.89     0.87<br>  Survived   0.83     0.78     0.80<br><br>Confusion Matrix:<br>[[110  13]<br> [14   71]]<br><br>Model saved to titanic_forest.pkl</pre><h3>When to Use Each (Decision Tree vs Forest)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*lEo1jk5e2huFZk3oCiZRXg.png" /></figure><blockquote><strong>The practical rule</strong></blockquote><blockquote><strong>Default to random forest</strong> unless you need to explain the model to a human (lawyer, regulator, patient). If interpretability matters, use a shallow single tree and accept lower accuracy. If you need both, use feature importances from the forest to identify which variables matter, then train a single tree on just those features.</blockquote><h3>Beyond Random Forests (Other Ensembles)</h3><p>Random forests are great, but they’re not alone. Here’s the landscape:</p><ul><li><strong>Gradient Boosting (XGBoost, LightGBM, CatBoost):</strong> Build trees sequentially, each correcting errors of the previous. Usually beats random forests. Slower to train.</li><li><strong>Extra Trees (Extremely Randomized Trees):</strong> Like random forests but split thresholds are random too. Faster training, sometimes better generalization.</li><li><strong>Voting/Stacking:</strong> Combine different model types (tree + linear + neural net). Overkill for most problems.</li></ul><p>For this course, master random forests first. They’re interpretable, performant, and the baseline for most tabular data competitions.</p><p>← Previous-&gt;<strong>Blog 12 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-12-of-20-linear-logistic-regression-0a2824f6d1dc">Linear &amp; Logistic Regression</a></p><p>Next →<strong>Blog 14 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-14-of-20-model-evaluation-tuning-87cda81466c5">Model Evaluation &amp; Tuning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cbea25fc99f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Data Science & AI · Blog 12 of 20 — Linear & Logistic Regression]]></title>
            <link>https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-12-of-20-linear-logistic-regression-0a2824f6d1dc?source=rss-e70f7aeb3b8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a2824f6d1dc</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Innovation is Infinite]]></dc:creator>
            <pubDate>Mon, 18 May 2026 06:40:48 GMT</pubDate>
            <atom:updated>2026-05-20T10:08:04.481Z</atom:updated>
            <content:encoded><![CDATA[<h4>From predicting house prices to classifying survival: learn the two fundamental supervised learning algorithms.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7UR3vtWFoKKKOjJEzbS-Ug.png" /><figcaption>Cover Page</figcaption></figure><h3>Two Types of Prediction</h3><p>Machine learning is about teaching computers to predict. But there are two fundamentally different kinds of predictions:</p><p><strong>Linear Regression:</strong> Predicting a number. “What will this house cost?” “How many calls will we get tomorrow?” “What’s the temperature in 3 hours?” The output is continuous — it can be any number.</p><p><strong>Logistic Regression:</strong> Predicting a category (usually yes/no). “Will this patient survive surgery?” “Is this email spam?” “Did this customer churn?” The output is discrete — one of a fixed set of options.</p><p>Both are <strong><em>supervised learning</em></strong> — you teach the model with examples that have both the question and the correct answer. After learning, the model predicts on new questions it’s never seen.</p><h3>Linear Regression: y = mx + b</h3><p>You’ve seen this equation since algebra class. In machine learning, it means exactly what you think:</p><pre>y = mx + b</pre><p><strong>y </strong>is what we&#39;re trying to predict (house price). <strong>x </strong>is the feature we&#39;re using (square footage). <strong>m </strong>is the slope — how much does y change when x goes up by 1? <strong>b </strong>is the intercept — what&#39;s the predicted value when x is zero?</p><p>During training, the model learns the best values of <strong>m </strong>and <strong>b </strong>to fit your data. During prediction, it plugs in a new value of <strong>x </strong>and calculates <strong>y</strong>.</p><blockquote><strong>Real datasets have many features, not one</strong></blockquote><blockquote>With multiple features (square footage, bedrooms, age, location), the equation becomes <strong>y = m₁x₁ + m₂x₂ + ... + mₙxₙ + b</strong>. Each feature gets its own slope. The model learns all of them.</blockquote><h3>Mean Squared Error (MSE)</h3><p>How do we know if our line is good? We measure the distance from each data point to the line, square it (to punish big errors more), and average those squared errors.</p><pre>MSE = (1/n) × Σ(predicted - actual)²</pre><p>The goal of training is to find <strong>m </strong>and <strong>b </strong>that minimize MSE. A line that passes through all points has MSE = 0. A bad line might have MSE = 10000. During training, the model adjusts the slope and intercept down this loss curve until it finds the minimum.</p><h3>Logistic Regression: Predicting Categories</h3><p>Despite the name, logistic regression is <strong>not</strong> linear — it’s a classification algorithm. It solves the problem: “Given features, what’s the probability this belongs to category X?”</p><p>The key innovation is the <strong>sigmoid function</strong>, which squashes any number into a probability between 0 and 1:</p><pre>P(y=1) = 1 / (1 + e^(-z))</pre><blockquote><strong>Why sigmoid, not linear?</strong></blockquote><blockquote>A linear model can predict probabilities outside [0, 1], which is nonsense. The sigmoid function is mathematically elegant: it’s always between 0 and 1, it’s differentiable (trainable), and it naturally represents increasing confidence as z gets more extreme.</blockquote><h3>Log Loss (Binary Crossentropy)</h3><p>For classification, we use <strong>log loss</strong> instead of MSE. It harshly penalizes confident wrong predictions.</p><pre>Log Loss = -(1/n) × Σ[y·log(p) + (1-y)·log(1-p)]</pre><p>For each prediction: if the true label is 1, we measure <strong>-log(p)</strong> (large loss if p is near 0, small loss if p is near 1). If the true label is 0, we measure <strong>-log(1-p)</strong> (punishes predicting 1 confidently when the answer is 0).</p><p>The model learns weights that minimize log loss. A perfect classifier has loss ≈ 0. A random guesser (p = 0.5 always) has loss ≈ 0.69.</p><h3>Linear Regression: House Prices</h3><p>Let’s predict house prices from square footage using a real dataset. We’ll train the model, visualize the regression line, and evaluate its performance.</p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_squared_error, r2_score<br>import matplotlib.pyplot as plt<br><br># Load a simple house prices dataset<br>data = {<br>    &quot;sqft&quot;: [1000, 1500, 2000, 2500, 3000, 3500],<br>    &quot;price&quot;: [200000, 300000, 350000, 400000, 500000, 550000]<br>}<br><br>df = pd.DataFrame(data)<br><br># Prepare features (X) and target (y)<br>X = df[[&quot;sqft&quot;]]  # 2D array required by sklearn<br>y = df[&quot;price&quot;]<br><br># Train the model<br>model = LinearRegression()<br>model.fit(X, y)<br><br># Get model parameters<br>print(f&quot;Slope (m)     : {model.coef_[0].:.2f}&quot;)<br>print(f&quot;Intercept (b) : {model.intercept_.:.2f}&quot;)<br><br># Make predictions<br>y_pred = model.predict(X)<br><br># Evaluate: MSE and R²<br>mse  = mean_squared_error(y, y_pred)<br>rmse = np.sqrt(mse)<br>r2   = r2_score(y, y_pred)<br><br>print(f&quot;MSE  : {mse:.0f}&quot;)<br>print(f&quot;RMSE : ${rmse:.0f}&quot;)<br>print(f&quot;R²   : {r2:.3f}&quot;)<br><br># Predict on new data<br>new_sqft = [[2200]]<br>predicted_price = model.predict(new_sqft)<br>print(f&quot;\nPredicted price for 2200 sqft: ${predicted_price[0]:.0f}&quot;)<br><br>Output<br>Slope (m) : 142.86<br>Intercept (b) : 71428.57<br>MSE : 1020408163<br>RMSE : $31944<br>R² : 0.991<br><br>Predicted price for 2200 sqft: $385714</pre><p>The model learned a slope of ~$143 per square foot. An R² of 0.991 means the model explains 99.1% of the variance in house prices — excellent fit!</p><pre># ── THE KEY: Visualize the regression line ──────────────<br>plt.figure(figsize=(10, 6))<br><br># Plot actual data points<br>plt.scatter(X, y, color=&quot;orange&quot;, s=100, alpha=0.7, label=&quot;Actual prices&quot;)<br><br># Plot the fitted regression line<br>plt.plot(X, y_pred, color=&quot;red&quot;, linewidth=2, label=&quot;Fitted line (y = 142.86x + 71428.57)&quot;)<br><br>plt.xlabel(&quot;Square Footage&quot;)<br>plt.ylabel(&quot;Price ($)&quot;)<br>plt.title(&quot;Linear Regression: House Prices vs Square Footage&quot;)<br>plt.legend()<br>plt.grid(True, alpha=0.3)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*LHQgsmWs4MTaGZWmlctYSw.png" /></figure><blockquote><strong>Always visualize the regression line</strong></blockquote><blockquote>This is the most intuitive proof that your model “learned” something. If the line passes through the data points and follows their trend, your model captured the relationship. If the line looks random or skewed, something is wrong. Visualization is often more telling than any metric.</blockquote><h3>Logistic Regression: Titanic Survival</h3><p>Now we’ll predict whether a passenger survived the Titanic. Our features: age, sex, and passenger class. Our target: survived (1) or not (0).</p><pre>import pandas as pd<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score, confusion_matrix, classification_report<br>from sklearn.preprocessing import LabelEncoder<br><br># Load Titanic dataset<br>url = &quot;https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv&quot;<br>df = pd.read_csv(url)<br><br># Quick cleaning: drop rows with missing Age<br>df = df.dropna(subset=[&quot;Age&quot;])<br><br># Encode Sex column: male=1, female=0<br>le = LabelEncoder()<br>df[&quot;Sex_encoded&quot;] = le.fit_transform(df[&quot;Sex&quot;])  # female=0, male=1<br><br># Features and target<br>features = [&quot;Age&quot;, &quot;Pclass&quot;, &quot;Sex_encoded&quot;]<br>X = df[features]<br>y = df[&quot;Survived&quot;]<br><br># Train logistic regression<br>model = LogisticRegression(max_iter=1000)<br>model.fit(X, y)<br><br># Make predictions<br>y_pred = model.predict(X)<br>y_pred_proba = model.predict_proba(X)  # Probability of each class<br><br># Accuracy score<br>accuracy = accuracy_score(y, y_pred)<br>print(f&quot;Accuracy: {accuracy:.3f} ({accuracy*100:.1f}%)&quot;)<br><br>Output<br>Accuracy: 0.776 (77.6%)</pre><pre># ── Confusion Matrix ──────────────────────────────────<br>cm = confusion_matrix(y, y_pred)<br><br>print(&quot;Confusion Matrix:&quot;)<br>print(cm)<br>print()<br><br># Parse the matrix<br>tn, fp, fn, tp = cm.ravel()<br><br>print(&quot;Interpretation:&quot;)<br>print(f&quot;True Negatives  (TN) : {tn} (didn&#39;t survive, correctly predicted didn&#39;t survive)&quot;)<br>print(f&quot;False Positives (FP) : {fp} (didn&#39;t survive, but we said survived) — WRONG&quot;)<br>print(f&quot;False Negatives (FN) : {fn} (survived, but we said didn&#39;t) — WRONG&quot;)<br>print(f&quot;True Positives  (TP) : {tp} (survived, correctly predicted survived)&quot;)<br>print()<br><br># Calculate metrics<br>precision = tp / (tp + fp)  # Of those we said survived, how many actually did?<br>recall    = tp / (tp + fn)     # Of those who actually survived, how many did we find?<br>f1        = 2 * (precision * recall) / (precision + recall)<br><br>print(f&quot;Precision: {precision:.3f}&quot;)<br>print(f&quot;Recall   : {recall:.3f}&quot;)<br>print(f&quot;F1 Score : {f1:.3f}&quot;)<br><br><br><br>OutPut<br>Confusion Matrix:<br>[[212 45]<br> [ 47 155]]<br><br>Interpretation:<br>True Negatives (TN) : 212 (didn&#39;t survive, correctly predicted didn&#39;t survive)<br>False Positives (FP) : 45 (didn&#39;t survive, but we said survived) — WRONG<br>False Negatives (FN) : 47 (survived, but we said didn&#39;t) — WRONG<br>True Positives (TP) : 155 (survived, correctly predicted survived)<br><br>Precision: 0.775<br>Recall : 0.767<br>F1 Score : 0.771</pre><p>Our model correctly predicted survival in 77.6% of cases. The confusion matrix shows that it’s nearly balanced between false positives (45) and false negatives (47) — neither error dominates.</p><blockquote><strong>What the metrics mean:</strong> Precision answers “Of those we predicted would survive, how many actually did?” (77.5%). Recall answers “Of those who actually survived, how many did we catch?” (76.7%). The F1 score (0.771) is the harmonic mean — it balances both.</blockquote><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Visualize the confusion matrix<br>plt.figure(figsize=(8, 6))<br>sns.heatmap(cm, annot=True, fmt=&quot;d&quot;, cmap=&quot;Blues&quot;, cbar=False)<br>plt.xlabel(&quot;Predicted&quot;)<br>plt.ylabel(&quot;Actual&quot;)<br>plt.title(&quot;Confusion Matrix: Titanic Survival Prediction&quot;)<br>plt.tight_layout()<br>plt.show()<br><br># Visualize predicted probabilities<br>plt.figure(figsize=(10, 6))<br>plt.hist(y_pred_proba[y==0, 1], bins=30, alpha=0.6, label=&quot;Didn&#39;t survive&quot;)<br>plt.hist(y_pred_proba[y==1, 1], bins=30, alpha=0.6, label=&quot;Survived&quot;)<br>plt.axvline(x=0.5, color=&quot;red&quot;, linestyle=&quot;--&quot;, linewidth=2, label=&quot;Decision boundary (p=0.5)&quot;)<br>plt.xlabel(&quot;Predicted Probability of Survival&quot;)<br>plt.ylabel(&quot;Frequency&quot;)<br>plt.title(&quot;Distribution of Predicted Probabilities&quot;)<br>plt.legend()<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*ETFOAXo8bHDqfxlmnQqwSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*fqCqNdGCZ9oo_-LgUwsymA.png" /></figure><blockquote><strong>Accuracy is not always the right metric</strong></blockquote><blockquote>If 95% of emails are not spam, a model that predicts “never spam” would be 95% accurate but useless. Use precision/recall when false positives and false negatives have different costs. Use F1 when you want to balance both. Always visualize with a confusion matrix first.</blockquote><h3>When to Use Each</h3><p><strong>Linear Regression</strong> when:</p><ul><li>Your target is a continuous number (price, temperature, revenue)</li><li>You want to understand the magnitude of change (each unit of X causes Y units of change in the target)</li><li>The relationship is roughly linear (a straight line through the scatter plot makes sense)</li></ul><p><strong>Logistic Regression</strong> when:</p><ul><li>Your target is a category (yes/no, survived/died, spam/not spam)</li><li>You want probabilities (confidence levels) alongside predictions</li><li>Your classes are roughly separable by a linear boundary</li></ul><p>Both are <strong>linear</strong> models — they assume a linear decision boundary. For more complex, nonlinear relationships, you’ll need decision trees, neural networks, or other advanced methods. But linear and logistic regression are the foundation: simple, interpretable, and often sufficient.</p><h3>Beyond the Basics</h3><p>Once you’ve mastered these two algorithms, you’re ready for:</p><ul><li><strong>Regularization</strong> (Ridge, Lasso): Prevent overfitting by penalizing large coefficients</li><li><strong>Cross-validation</strong>: Reliably estimate performance on unseen data</li><li><strong>Feature scaling</strong>: Some algorithms perform better when features are normalized</li><li><strong>Feature engineering</strong>: Create new features (polynomial terms, interactions) to capture complex relationships</li><li><strong>Multi-class classification</strong>: Extend logistic regression to predict 3+ categories</li><li><strong>Decision trees &amp; ensemble methods</strong>: Nonlinear models for trickier problems</li></ul><blockquote><strong>Key Takeaways</strong></blockquote><blockquote><strong>Linear Regression</strong> learns y = mx + b to predict continuous numbers, minimizing MSE. <strong>Logistic Regression</strong> uses the sigmoid function to predict probabilities, minimizing log loss. Both are interpretable, trainable, and foundational. Always visualize: plot the regression line for linear, plot the confusion matrix and probability distribution for classification. These visuals are often more informative than any single number.</blockquote><p>← Previous-&gt;<strong>Blog 11 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-11-of-20-intro-to-machine-learning-f8c774c65bcc">Intro to Machine Learning</a></p><p>Next →<strong>Blog 13— </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-13-of-20-decision-trees-random-forests-9cbea25fc99f">Decision trees &amp; random forests</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a2824f6d1dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Data Science & AI · Blog 11 of 20 — Intro to Machine Learning]]></title>
            <link>https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-11-of-20-intro-to-machine-learning-f8c774c65bcc?source=rss-e70f7aeb3b8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8c774c65bcc</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Innovation is Infinite]]></dc:creator>
            <pubDate>Fri, 15 May 2026 10:18:08 GMT</pubDate>
            <atom:updated>2026-05-18T06:41:26.175Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn the fundamentals of supervised learning, train your first model, and understand why we split data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSZOytOQdDFfqEjPFca0WQ.png" /><figcaption>Cover Image</figcaption></figure><h3>The Core Idea: Learning from Data</h3><p>Machine learning is the art of writing programs that <strong>learn patterns from data instead of being explicitly programmed</strong>. Rather than hard-coding every rule, you show the model examples and let it figure out the pattern.</p><p>Think of it this way: instead of writing a program that says “if sepal_length &gt; 5.5, then it’s an iris versicolor,” you give the program thousands of iris examples with their labels, and it learns to recognize the pattern itself.</p><blockquote><strong>Why Does This Matter?</strong></blockquote><blockquote><strong>Rule-based code is rigid.</strong> A weather app coded with 1,000 hardcoded rules breaks the moment conditions change slightly. Machine learning models <strong>generalize</strong> — they handle new, unseen data because they’ve learned the underlying pattern, not just memorized examples.</blockquote><p>This is the difference between programming and machine learning:</p><ul><li><strong>Traditional Programming:</strong> You write rules → computer applies them → produces output</li><li><strong>Machine Learning:</strong> You provide data + labels → algorithm learns rules → produces predictions on new data</li></ul><h3>Supervised vs Unsupervised vs Reinforcement</h3><h4>Supervised Learning</h4><p>You have <strong>labeled data</strong> — inputs with correct answers. The model learns to predict the output for new inputs.</p><ul><li><strong>Classification:</strong> Predict categories (is this email spam? Is this iris setosa?)</li><li><strong>Regression:</strong> Predict numbers (what’s the house price? What’s tomorrow’s temperature?)</li></ul><p><em>Example:</em> You have 1,000 photos with labels “cat” or “dog.” The model learns to label new photos.</p><h4>Unsupervised Learning</h4><p>You have <strong>unlabeled data</strong>. The model finds hidden patterns on its own — grouping similar things together.</p><ul><li><strong>Clustering:</strong> Group similar items (find customer segments, detect fraudulent patterns)</li><li><strong>Dimensionality Reduction:</strong> Simplify high-dimensional data while keeping important info</li></ul><p><em>Example:</em> You have 10,000 customer purchase histories with no labels. The model discovers that they naturally form 3–4 distinct customer groups.</p><h4>Reinforcement Learning</h4><p>The model learns by <strong>trial and reward</strong>. It takes actions, gets feedback, and adjusts strategy to maximize reward.</p><ul><li><strong>Game AI:</strong> AlphaGo learned to play Go by playing millions of games</li><li><strong>Robotics:</strong> A robot learns to walk by trying movements and getting reward signals</li></ul><p><em>Example:</em> A model learns to play chess by playing millions of games, getting +1 for wins, -1 for losses.</p><blockquote><strong>In This Blog</strong></blockquote><blockquote>We’re focusing on <strong>supervised learning</strong> — specifically classification. It’s the most common type you’ll use first, and the concepts generalize to other types.</blockquote><h3>Practice Questions vs the Final Exam</h3><p>When you study for an exam, you work through practice problems to learn. But you don’t study the exact same problems that will appear on the final exam — that would be cheating! The test needs to be problems you’ve <strong>never seen</strong> to truly measure whether you understand the material.</p><p>Machine learning works the same way:</p><ul><li><strong>Training set:</strong> The practice problems. The model learns from these.</li><li><strong>Test set:</strong> The final exam. You use this to measure how well the model performs on <strong><em>new, unseen data</em>.</strong></li></ul><blockquote><strong>The School Analogy</strong></blockquote><blockquote><strong>Training set = practice problems you solve to study.</strong> The model sees these and learns patterns. <strong>Test set = the actual exam.</strong> The model has never seen these problems before. Its accuracy on the test set tells you how well it really learned, not just how well it memorized practice answers.</blockquote><p>If you only test on the training data, you’ll get falsely high accuracy. The model will have simply memorized the answers. We call this <strong>overfitting</strong>.</p><p><strong>Typical split:</strong> 80% training, 20% testing. (Sometimes 70/30 or 75/25, depending on data size.)</p><pre>Raw Dataset: [iris_1, iris_2, iris_3, ... iris_150]<br>              |<br>              |  train_test_split(test_size=0.2)<br>              |<br>        ┌─────┴─────┐<br>        │           │<br>    TRAIN (80%)   TEST (20%)<br>    [iris_1, ...]  [iris_31, ...]<br>    ↓               ↓<br>    model.fit()     model.score()<br>    (learning)      (evaluation)</pre><h3>The ML Toolkit You’ll Use</h3><p><a href="https://scikit-learn.org/">Scikit-learn</a> is Python’s most popular machine learning library. It provides clean, consistent tools for:</p><ul><li><strong>Datasets:</strong> Built-in datasets for learning (Iris, Digits, Wine, Breast Cancer)</li><li><strong>Preprocessing:</strong> Scale data, encode categories, split into train/test</li><li><strong>Models:</strong> Hundreds of algorithms (KNN, Decision Trees, Random Forests, SVM, Linear Regression, etc.)</li><li><strong>Evaluation:</strong> Accuracy, precision, recall, confusion matrices, and more</li></ul><p>The beauty of scikit-learn is that <strong>all models follow the same pattern:</strong></p><pre># Step 1: Create a model<br>model = SomeAlgorithm()<br><br># Step 2: Train on labeled data<br>model.fit(X_train, y_train)<br><br># Step 3: Make predictions<br>predictions = model.predict(X_test)<br><br># Step 4: Evaluate accuracy<br>accuracy = model.score(X_test, y_test)</pre><p>Once you master this pattern with one algorithm, you can swap in any other — Random Forest, SVM, Logistic Regression — and the code stays almost identical.</p><h3>Getting Started: 30 Seconds</h3><h4>Install scikit-learn</h4><pre>pip install scikit-learn</pre><h4>Import what you need</h4><pre>import numpy as np<br>import pandas as pd<br>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br>from sklearn.neighbors import KNeighborsClassifier</pre><h3>Your First Machine Learning Dataset</h3><p>The <strong>Iris dataset</strong> is a classic. It contains 150 iris flower measurements with their species (setosa, versicolor, virginica). Perfect for learning classification.</p><pre># Load the dataset<br>iris = load_iris()<br><br># Extract features (X) and labels (y)<br>X = iris.data        # 150 flowers × 4 measurements<br>y = iris.target      # 150 species labels (0, 1, 2)<br><br>print(&quot;Feature shape:&quot;, X.shape)<br>print(&quot;Label shape: &quot;, y.shape)<br>print(&quot;Feature names:&quot;, iris.feature_names)<br>print(&quot;Target names: &quot;, iris.target_names)<br><br><br>Output<br>Feature shape: (150, 4)<br>Label shape: (150,)<br>Feature names: [&#39;sepal length (cm)&#39;, &#39;sepal width (cm)&#39;, &#39;petal length (cm)&#39;, &#39;petal width (cm)&#39;]<br>Target names: [&#39;setosa&#39; &#39;versicolor&#39; &#39;virginica&#39;]</pre><blockquote><strong>X and y Notation</strong></blockquote><blockquote>In machine learning, <strong>X</strong> (capital) represents features (inputs) and <strong>y</strong> (lowercase) represents labels (outputs). X is always 2D (rows = samples, columns = features). y is 1D (one label per sample). Think: X is the question, y is the answer.</blockquote><h3>Creating Your Practice Problems and Final Exam</h3><pre># Split: 80% train, 20% test<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y,<br>    test_size=0.2,    # 20% for testing<br>    random_state=42  # reproducibility<br>)<br><br>print(f&quot;Training samples: {len(X_train)}&quot;)<br>print(f&quot;Test samples:     {len(X_test)}&quot;)<br><br>Output<br>Training samples: 120<br>Test samples: 30</pre><p><strong>random_state=42</strong> ensures you get the same split every time you run the code. (The number 42 is arbitrary — any number works.)</p><h3><strong>Train Your First Model (KNN) — </strong>K-Nearest Neighbors Classifier</h3><p><strong>K-Nearest Neighbors (KNN)</strong> is the simplest and most intuitive algorithm:</p><ul><li>To classify a new flower, look at the K nearest flowers in the training set</li><li>Take a vote among those K neighbors</li><li>Assign the most common label</li></ul><p>With K=3, to classify an unknown flower, you find the 3 closest labeled flowers and vote on the species.</p><pre># Step 1: Create the model<br>model = KNeighborsClassifier(n_neighbors=3)<br><br># Step 2: Train on labeled data<br>model.fit(X_train, y_train)<br><br># Step 3: Make predictions<br>predictions = model.predict(X_test)<br><br>print(&quot;First 10 predictions:&quot;, predictions[:10])<br>print(&quot;First 10 actual:    &quot;, y_test[:10])<br><br>output<br>First 10 predictions: [1 0 2 1 1 0 0 2 1 1]<br>First 10 actual: [1 0 2 1 1 0 0 2 1 1]</pre><p>Perfect match on these 10! But how does it do overall?</p><h3>Measuring Model Performance</h3><p><strong>Accuracy</strong> = (correct predictions) / (total predictions)</p><pre># Step 4: Evaluate on test set<br>accuracy = model.score(X_test, y_test)<br><br>print(f&quot;Test Accuracy: {accuracy*100:.2f}%&quot;)<br><br># Bonus: Compare to training accuracy<br>train_accuracy = model.score(X_train, y_train)<br>print(f&quot;Train Accuracy: {train_accuracy*100:.2f}%&quot;)<br><br>Output<br>Test Accuracy: 100.00%<br>Train Accuracy: 95.00%</pre><p>The KNN model achieves 100% accuracy on the test set! (The iris dataset is relatively easy — all three species are quite distinct.)</p><blockquote><strong>Train vs Test Accuracy</strong></blockquote><blockquote><strong>Train accuracy is usually higher than test accuracy</strong> — that’s normal and healthy. If they’re extremely different (e.g., 95% vs 60%), it’s a sign of overfitting. The model memorized the training data but didn’t learn the true pattern. If they’re similar, the model is generalizing well.</blockquote><h3>Putting It All Together</h3><p>Here’s the complete pipeline from start to finish:</p><pre>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br>from sklearn.neighbors import KNeighborsClassifier<br><br># ── LOAD ──<br>iris = load_iris()<br>X = iris.data<br>y = iris.target<br><br># ── SPLIT ──<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br><br># ── TRAIN ──<br>model = KNeighborsClassifier(n_neighbors=3)<br>model.fit(X_train, y_train)<br><br># ── EVALUATE ──<br>accuracy = model.score(X_test, y_test)<br>print(f&quot;Accuracy: {accuracy*100:.1f}%&quot;)<br><br>Output<br>Accuracy: 100.0%</pre><blockquote><strong>The Four Steps of Machine Learning</strong></blockquote><blockquote><strong>1. Load:</strong> Get your data (iris dataset, CSV, database, API). <strong>2. Split:</strong> train_test_split into practice and exam sets. <strong>3. Train:</strong> model.fit() — let the model learn patterns. <strong>4. Evaluate:</strong> model.score() — measure accuracy on unseen data.</blockquote><h3>Try These Variations</h3><p>Now that you’ve trained your first model, experiment:</p><ul><li><strong>Change K:</strong> Try n_neighbors=1, 5, 10. How does accuracy change?</li><li><strong>Change test size:</strong> Try test_size=0.3 instead of 0.2. Why might this matter?</li><li><strong>Check train/test split:</strong> Print X_train.shape and X_test.shape to verify the split</li><li><strong>Inspect predictions:</strong> Use model.predict() on individual samples: <strong>model.predict([[5.0, 3.4, 1.5, 0.2]])</strong></li><li><strong>Get prediction probabilities:</strong> Use <strong>model.predict_proba(X_test)</strong> to see confidence scores</li></ul><pre># Test on K values<br>for k in [1, 3, 5, 10]:<br>    m = KNeighborsClassifier(n_neighbors=k)<br>    m.fit(X_train, y_train)<br>    acc = m.score(X_test, y_test)<br>    print(f&quot;K={k}: {acc*100:.1f}%&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*KUMRD2u6vJV1SX4WrqCTvw.png" /><figcaption>Output</figcaption></figure><p>← Previous-&gt;<strong>Blog 10 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-10-of-20-exploratory-data-analysis-261b806fc459"><strong>Exploratory Data Analysis</strong></a></p><p>Next →<strong>Blog 12 — </strong><a href="https://medium.com/@akashnsengar8/python-for-data-science-ai-blog-12-of-20-linear-logistic-regression-0a2824f6d1dc"><strong>Linear &amp; Logistic Regression</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8c774c65bcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>