<?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 Likhitha K on Medium]]></title>
        <description><![CDATA[Stories by Likhitha K on Medium]]></description>
        <link>https://medium.com/@likhitha.k2003?source=rss-328b393d69f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xg04PlHNaGALmvQX</url>
            <title>Stories by Likhitha K on Medium</title>
            <link>https://medium.com/@likhitha.k2003?source=rss-328b393d69f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:43:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@likhitha.k2003/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[Artificial Intelligence(AI)]]></title>
            <link>https://medium.com/@likhitha.k2003/artificial-intelligence-ai-ee4a3fdebdef?source=rss-328b393d69f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee4a3fdebdef</guid>
            <dc:creator><![CDATA[Likhitha K]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 09:27:33 GMT</pubDate>
            <atom:updated>2026-06-10T09:27:33.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RM3gG0UtxB8nir6YkkiouQ.png" /></figure><h3>What exactly is AI, and why should anyone care?</h3><p>There is a moment in every generation when a technology stops being a concept people talk about in conference rooms and starts being something they use without thinking. The internet had that moment. The smartphone had it. Artificial Intelligence is having it right now — and most of us are still catching up to what that actually means.</p><p>At its simplest, Artificial Intelligence is the ability of a machine to do things that would normally require human thinking. Reading a sentence and understanding its meaning. Recognising a face in a photograph. Predicting what a customer is likely to buy next week. Writing code based on a description in plain English.</p><p>AI does not think the way humans think. It does not have feelings, opinions, or intentions. What it has is pattern recognition at a scale no human brain can match — trained on billions of examples until it becomes very, very good at making useful predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_j3Y3we4E0A5CjD7dF63g.png" /></figure><p>The reason this matters is not that AI is magical. It matters because it is genuinely useful at a growing number of things that businesses have always needed to do but have paid a high price to do well — screening documents, answering routine questions, processing data, generating first drafts, detecting anomalies. When a technology starts handling those tasks reliably, the economics of running an organisation change.</p><h3>Why is everyone talking about it right now?</h3><p>AI has existed in research labs for decades. The reason it matters so intensely right now comes down to three things that happened at the same time: computing power became cheap enough, data became abundant enough, and the algorithms finally became smart enough.</p><p>Put those three things together and you get a threshold moment — the kind that happens once in a generation. AI crossed from “impressive in a lab” to “useful in the real world” within the span of about three years. Today it is inside the tools your team already uses. Your email client. Your customer support system. Your code editor. Your hiring platform. The shift did not announce itself loudly. It simply arrived.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMxbtqXTopfWAwz0QQovMA.png" /></figure><p>The companies that started taking AI seriously two years ago are not still experimenting. They are ahead. And the gap between them and the businesses still waiting for “the right moment” is widening every quarter.</p><h3>How does AI actually learn? The part most articles skip.</h3><p>This is the question that most explainers skip, and it is the most important one to understand if you want to have an honest conversation about what AI can and cannot do.</p><p>AI learns from examples — enormous numbers of them. A model that can diagnose disease from an X-ray has been trained on millions of correctly labelled scans. A model that writes code has been trained on billions of lines of code written by human developers. A model that answers questions in natural language has been trained on a significant portion of text ever written on the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDA4fLK_Z9yneK8-5TvByQ.png" /></figure><p>The learning process involves adjusting millions of internal numbers — called weights — until the model gets reliably good at predicting the right answer. It does not understand the way a person understands. But it is often correct in ways that look, from the outside, indistinguishable from understanding. This distinction matters. It explains why AI can be confidently wrong. It also explains why, with the right oversight, it can be extraordinarily useful.</p><h3>Where is AI actually being used today?</h3><p>This is the part that surprises most people when they see it laid out. The breadth of where AI has quietly taken root is wider than most professionals realise. It has not arrived as a single dramatic announcement. It has seeped in — quietly, industry by industry, use case by use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEmOKHPW6Iwtupz8-T0DiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRROqVI-H_sU_KS-7Oue6w.png" /></figure><p>In manufacturing, AI is predicting equipment failures before they happen — saving companies from unplanned downtime that costs far more than the preventive fix. In legal, it is reviewing contracts for risk clauses at a fraction of the time a junior associate would take. In logistics, it is optimising delivery routes in real time based on traffic, weather, and order volumes. The list keeps growing every quarter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-C-xIeWeouf7wkdvakL1xg.png" /></figure><h3>The honest conversation about jobs, skills, and what actually changes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47tGcvV1ckggGbIusR5lFg.png" /></figure><p>The most common fear about AI is job loss. It is a legitimate concern, and it would be dishonest to dismiss it. What the evidence actually shows, though, is more nuanced than the headlines suggest.</p><p>AI is very good at tasks that are routine, repetitive, and well-defined. It is far weaker at tasks that require judgment in ambiguous situations, genuine empathy, creative leaps, or the kind of trust that only comes from a real relationship between two people. The jobs that shrink will be the ones that were always, at their core, pattern-matching work. The roles that grow will be built around what only humans can do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzVtS2HHaYV8NeLgbhW6hw.png" /></figure><p>This requires a different kind of literacy. Not everyone needs to learn to code. But everyone in a knowledge-based role needs to understand what AI can and cannot do, how to use it effectively, how to verify its output, and when to override it. The professionals who will do the most with AI are the ones who redirect their freed-up time toward judgment, creativity, and the problems that still need a human in the room.</p><h3>What are the real risks — and why pretending they do not exist makes them worse</h3><p>Any serious conversation about AI has to address this directly. The technology carries genuine risks, and leaders who dismiss them do not look confident. They look uninformed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlrZggwuCr4OO_ZtuYG1nA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjF79z99gsQpmzD-bMgl4Q.png" /></figure><h3>Where is AI going next — and what does it mean for your business?</h3><p>The short answer is: further and faster than most people expect. The models being built today are significantly more capable than the ones that impressed people two years ago. The direction of travel is toward AI that can take multi-step actions in the world — not just answer a question, but book a meeting, run a workflow, investigate an anomaly, draft a response, and flag it for human review — all without being prompted at each step.</p><p>This is already happening in limited contexts. In the next three to five years, it will be standard. The businesses that have figured out how to work alongside AI effectively will have a structural advantage that is very difficult to close later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PzUAeooBNV_aS9nI10HZg.png" /></figure><p>There is also serious work happening on AI safety — making sure that as these systems become more capable, they remain aligned with human values and subject to meaningful oversight. This is not science fiction. It is active engineering work, funded by some of the largest technology companies in the world, and it is arguably the most important technical challenge of this decade.</p><p>For businesses in healthcare, financial services, and other high-stakes sectors, this safety work is not abstract. It is the difference between deploying AI that genuinely helps people and deploying AI that causes harm nobody intended.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8dwTeSU3Pn5yyHpx4bJaA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee4a3fdebdef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning: A Complete Guide — From Basics to Real-World AI Systems]]></title>
            <link>https://medium.com/@likhitha.k2003/fine-tuning-a-complete-guide-from-basics-to-real-world-ai-systems-c5336a68bcc4?source=rss-328b393d69f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5336a68bcc4</guid>
            <dc:creator><![CDATA[Likhitha K]]></dc:creator>
            <pubDate>Sun, 24 May 2026 16:12:52 GMT</pubDate>
            <atom:updated>2026-05-24T16:12:52.411Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Why this article exists</h3><p>Spend an hour on LinkedIn or in any AI Slack community and you’ll quickly notice something: people throw around “fine-tuning” and “RAG” like they’re interchangeable. Or worse, they treat fine-tuning as this vague mystical process that somehow makes AI smarter about everything.</p><p>It doesn’t work that way. And that confusion is genuinely costing teams months of wasted effort and thousands of dollars in compute bills.</p><p>So here’s what this article is going to do. It’s going to explain both concepts clearly — not in textbook language, but in the kind of plain English you’d use to explain something to a smart friend who’s new to AI. Then it’s going to walk through every type of fine-tuning that exists, what each one actually does, when to use it, and how it plugs into a real RAG system. With code. With diagrams. With real examples.</p><p>By the time you finish this, you’ll be able to make smart decisions — not just parrot the terminology.</p><h3>2. What is RAG? Let’s start simple</h3><p>Picture this. You hire a brilliant consultant. She has a PhD in computer science, she’s read thousands of books, and she can hold a sophisticated conversation on almost any topic. The problem? She graduated five years ago. She knows nothing about your company’s internal policies, your latest product launch, what your support team calls a “priority one ticket,” or anything that happened in the news last week.</p><p>Now you hand her a filing cabinet. Every time a client asks her a question, she first opens the cabinet, flips through the relevant folders, reads the most useful documents she finds — and then answers, using both her background knowledge and the fresh material she just pulled.</p><p><strong>💡 THE ANALOGY</strong></p><p><strong>That consultant is a Large Language Model (LLM). The filing cabinet is your document database. The act of searching, pulling the right files, and answering is RAG — Retrieval-Augmented Generation.</strong></p><p>RAG is a technique where, instead of asking an AI to rely purely on what it memorised during training, you give it a live database of documents. When a question comes in, the system searches that database for the most relevant chunks of text, hands them to the LLM alongside the question, and the LLM generates a response using that real information.</p><p>The key benefit: the AI is grounded in your actual data. It doesn’t hallucinate an answer from vague training memory — it reads a real document and works from that. You can update that database any time without touching the model itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wW_99BIYEJYSabNn3UdHQ.png" /></figure><p>Notice there are two separate jobs happening here: retrieval(find the right documents) and generation (write a good answer from those documents). Both of these can be improved. That’s where fine-tuning comes in — but we’re getting ahead of ourselves.</p><h3>3. What is fine-tuning, really?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*-VEdRwKP3-muRRtn" /></figure><p>Our consultant is brilliant. But she speaks very formally when your customers want casual and warm. She gives long, structured responses when your users need quick bullet-pointed answers. She doesn’t know your internal shorthand — when someone says “tier 3 escalation” she looks puzzled. And she tends to over-explain things that your most experienced users already know.</p><p>So you put her through an internal training program. You show her dozens of recorded conversations from your best support agents. You correct her when she’s too stiff. You highlight what a great response looks like versus a mediocre one. You run her through scenarios specific to your industry. Over weeks, she adapts. She starts sounding like she’s been on your team for years.</p><p><strong>💡 THE ANALOGY</strong></p><p><strong>That internal training program is fine-tuning. You’re taking a pre-trained model and continuing to train it on your own specific data — so it learns your preferred format, your domain language, your tone, and the exact kinds of tasks you care about.</strong></p><p>Here’s the crucial thing to understand. Fine-tuning doesn’t fill the model’s head with new facts the way studying does. It changes <em>how the model behaves</em> — how it structures outputs, what level of detail it defaults to, what vocabulary it uses, how it handles edge cases, what it prioritises when information is ambiguous.</p><p>Under the hood, what’s actually happening is that the model’s parameters — the numerical weights that determine how it processes language — are being slightly adjusted through more gradient descent on your data. The model was already trained on a mountain of internet text. Fine-tuning nudges those weights specifically toward your task.</p><p><em>“RAG gives the AI what to know. Fine-tuning teaches it how to act.”</em></p><h3>4. RAG vs fine-tuning — the clear side-by-side</h3><p>Let’s kill the confusion once and for all. Here’s a direct comparison across every dimension that matters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TD9b1jOHXyICjuuidXvMQg.png" /></figure><p>The important realisation here: these are complementary techniques, not alternatives. Most serious production AI systems eventually use both — RAG for accurate, up-to-date knowledge; fine-tuning for consistent, polished behaviour.</p><h3>5. All the types of fine-tuning — explained properly</h3><p>This is where most articles wave their hands and say “there are several types.” That’s not good enough. Let’s go through each one with real clarity — what it is, how it works mechanically, and when you’d actually choose it.</p><h3>THE BIG PICTURE FIRST</h3><p>Fine-tuning broadly splits into three categories: methods that update all the model’s parameters (full fine-tuning), methods that update only a small portion of them (parameter-efficient fine-tuning, or PEFT), and methods that teach the model to produce outputs that humans prefer(alignment fine-tuning). Within each category, several specific techniques exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqTlROeJjEUdDgdL7zST4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YSflvu3iE1JIVZeZr3qdbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*f4gn0wmeCybjvviHRJaQpg.png" /></figure><p>That’s a lot. Let’s go deeper on the most important ones — because each has subtleties that matter when you’re deciding which to use.</p><h3>6. Full Fine-Tuning — the original approach</h3><p>Full Fine-Tuning (FFT) is conceptually the simplest: take a pre-trained model, feed it your training data, and run gradient descent to update all of its weights. Every parameter in the model adjusts to fit your data better.</p><p>The upside is obvious — you can theoretically reshape the model’s behaviour in any direction, deeply and completely. If you have a massive, high-quality proprietary dataset and serious GPU infrastructure, FFT gives you maximum control.</p><p>But the downsides are real and they’re painful. First, cost — updating billions of parameters across thousands of training steps requires significant compute. A 7B parameter model can take hours on multiple high-end GPUs; a 70B model can take days. Second, storage — you end up with a full separate copy of the model for each fine-tuned task. If you have five tasks, you need five 14GB+ model files. Third, and most importantly: catastrophic forgetting.</p><p>⚠️ CATASTROPHIC FORGETTING</p><p>When you train a neural network heavily on new data, it can “forget” things it previously knew. Fine-tune a general-purpose model intensively on legal documents, and it may start giving worse answers on general questions. The original knowledge gets overwritten. This is a serious practical concern with FFT on small datasets.</p><p>For most teams building on top of existing foundation models, FFT is overkill. The PEFT methods below were invented specifically to get most of the benefit at a fraction of the cost and without the forgetting problem.</p><h3>7. LoRA and QLoRA — the game-changers</h3><p>LoRA stands for Low-Rank Adaptation, and it is — without exaggeration — one of the most practically important ideas in the fine-tuning space in recent years. Understanding it properly will save you a lot of confusion.</p><p>Here’s the insight behind LoRA. When you fine-tune a model, the <em>change</em> in the weight matrices is what matters — not the full weight matrix itself. And that change, it turns out, often has a much lower rank than the original matrix. In other words, the useful adjustment to the weights can be compressed into a much smaller representation.</p><p>So instead of updating the full weight matrix W directly, LoRA freezes W and adds two small matrices — call them A and B — whose product approximates the necessary update. Only A and B are trained. The original model stays untouched.</p><p>🔬 LORA IN CONCEPT (SIMPLIFIED)</p><pre>🔬 LORA IN CONCEPT (SIMPLIFIED)<br># Original: model has a weight matrix W (e.g., 4096 x 4096 = 16M params)<br># LoRA: freeze W, add two small matrices A and B<br>#   A: shape (4096, r)  — r is the &quot;rank&quot;, typically 4 to 64<br>#   B: shape (r, 4096)<br>#   Effective update = A × B  (much smaller than W)<br><br># At rank r=8, you&#39;re training 2 × 4096 × 8 = 65,536 params<br># vs the original 16,777,216 — that&#39;s 256x fewer parameters<br><br>from peft import LoraConfig, get_peft_model<br><br>config = LoraConfig(<br>    r=8,               # Rank — lower = fewer params, faster, less capacity<br>    lora_alpha=32,     # Scaling factor<br>    target_modules=[&quot;q_proj&quot;, &quot;v_proj&quot;],  # Which layers to adapt<br>    lora_dropout=0.05,<br>    bias=&quot;none&quot;<br>)<br><br>model = get_peft_model(base_model, config)<br>model.print_trainable_parameters()<br># → trainable params: 4,194,304 || all params: 6,742,609,920 || ~0.06%</pre><p>If you’re working on a single GPU or on a tight budget: QLoRA every time. If you have multiple GPUs and a large, clean dataset: LoRA at a higher rank. Only reach for full fine-tuning if you have a compelling reason that LoRA genuinely can’t satisfy — which is rare.</p><h3>8. Instruction Tuning (Supervised Fine-Tuning)</h3><p>Before ChatGPT launched, most language models were pure next-token predictors. You gave them text and they continued it. Useful for some things, but not for having a conversation or following instructions.</p><p>Instruction tuning — also called Supervised Fine-Tuning (SFT) — changed that. The idea is simple: collect a large dataset of (instruction, ideal response) pairs, and fine-tune the model on those. The model learns to treat the input not just as text to continue, but as a task to complete.</p><p>📋 INSTRUCTION TUNING DATA FORMAT</p><pre>📋 INSTRUCTION TUNING DATA FORMAT<br>{<br>  &quot;system&quot;: &quot;You are a helpful customer support agent for Acme SaaS. Be concise and friendly.&quot;,<br>  &quot;user&quot;: &quot;How do I export my data to CSV?&quot;,<br>  &quot;assistant&quot;: &quot;Sure! Go to Settings → Data → Export, choose CSV as your format, and click Download. The file will arrive in your email within a few minutes. Let me know if anything gets stuck!&quot;<br>}<br><br># You need hundreds to thousands of these pairs<br># Quality matters far more than quantity<br># Each &quot;assistant&quot; response should represent your ideal output exactly</pre><p>Imagine your consultant needs to handle three different clients: a law firm, a hospital, and a tech startup. Each needs a slightly different communication style and domain vocabulary. You can’t run three separate training programs for three full copies of her brain.</p><p>Adapter layers solve this. Instead of modifying the core model, you insert small, task-specific neural network modules between the existing transformer layers. The original model weights stay completely frozen. Only these tiny inserted modules are trained.</p><p>The practical advantage: you train one adapter per task, and they’re tiny files — sometimes just a few hundred megabytes compared to the many gigabytes of the base model. At inference time, you load the base model once and swap adapters on the fly depending on which task is needed. No reloading, no separate deployments.</p><p>✅ WHEN TO USE ADAPTERS</p><p>When you need a single model to handle multiple distinct tasks or user groups — different departments, different product lines, different languages — and you want to manage them modularly without maintaining separate model deployments.</p><h3>10. Alignment fine-tuning — RLHF and DPO</h3><p>Here’s a problem SFT alone can’t fully solve. You train the model to produce an answer that looks like your training examples. But training examples are written by humans, and humans aren’t perfect. Sometimes there are multiple valid answers with different levels of quality. And sometimes the model generates something that is technically correct but not what a real user would prefer.</p><p>Alignment fine-tuning teaches the model to produce outputs that humans actually prefer — not just outputs that pattern-match to training data.</p><h3>RLHF — THE CLASSIC APPROACH</h3><p>Reinforcement Learning from Human Feedback has three stages. First, SFT — train the base model on instruction pairs. Second, train a separate reward model — humans rate pairs of model outputs (preferring one over the other), and you train a classifier to predict those preference scores. Third, use Proximal Policy Optimisation (PPO) — a reinforcement learning algorithm — to update the LLM toward generating outputs that score highly on the reward model.</p><p>It works. ChatGPT and Claude are both trained with variants of RLHF. But it’s genuinely difficult to implement — two separate models, an RL training loop that can be unstable, and a lot of human annotation cost.</p><h3>DPO — THE MODERN ALTERNATIVE</h3><p>Direct Preference Optimisation, introduced in 2023, achieves essentially the same result without a separate reward model or RL training. Instead, it derives a training objective directly from preference pairs — given (prompt, preferred response, rejected response), it updates the model to prefer the preferred response over the rejected one, in a single stable supervised training step.</p><p>📋 DPO TRAINING DATA FORMAT</p><pre>{<br>  &quot;prompt&quot;: &quot;Explain why the payment failed.&quot;,<br>  &quot;chosen&quot;: &quot;Your payment was declined because the card details didn&#39;t match what your bank has on file. The most common fix is to double-check the billing address. Would you like me to walk you through updating it?&quot;,<br>  &quot;rejected&quot;: &quot;The payment failed due to a card verification error (code 4916). Please ensure your billing information is correct and retry the transaction.&quot;<br>}<br><br># &quot;chosen&quot; = what a human rater preferred<br># &quot;rejected&quot; = what they preferred less (not necessarily wrong — just less good)<br># Both can be generated by your model, then human-rated</pre><p>✅ RLHF VS DPO IN PRACTICE</p><p>For almost all applied use cases today, start with DPO. It’s simpler, more stable, and produces comparable results. RLHF is worth the complexity only if you have dedicated ML research capacity and genuinely need to push beyond what DPO can achieve.</p><h3>11. Now — fine-tuning inside a RAG pipeline</h3><p>Okay. You now understand RAG and every major type of fine-tuning. Here’s where it gets interesting: a RAG pipeline has multiple distinct components, and fine-tuning applies differently to each one. Getting this right is what separates a mediocre RAG system from a great one.</p><p>Let’s map the full pipeline and show exactly where each type of fine-tuning applies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsKMoJGTaPFWU6oA3Qy7nw.png" /></figure><h3>12. Fine-tuning the embedding model</h3><p>When you load documents into a RAG system, each chunk of text gets converted into a vector — a long array of numbers that represents its meaning. This conversion is done by an embedding model. When a user asks a question, the question also gets converted into a vector, and the system finds the document chunks whose vectors are closest to the question’s vector.</p><p>Generic embedding models are trained on broad internet data. They’re good at general semantic similarity. But if your documents are in a specialised domain — medical literature, legal contracts, financial filings, engineering specs, customer support tickets — the model may not understand what “similar” means in your context.</p><p>A user asking “what’s the contraindication for this drug with beta blockers?” might get a chunk about drug pricing retrieved because both mention the drug name — even though the pricing chunk is completely irrelevant. That bad retrieval cascades into a bad answer, and no amount of LLM fine-tuning will fix it.</p><p>✅ HOW TO FIX IT — FINE-TUNE THE EMBEDDER</p><p>Collect pairs of (query, relevant document chunk) from your domain. Mark them as positive pairs. Add hard negatives — queries paired with plausible-but-wrong documents. Fine-tune using contrastive loss, which teaches the model to pull similar pairs together and push dissimilar ones apart in the vector space.</p><pre>🔬 FINE-TUNING AN EMBEDDING MODEL WITH CONTRASTIVE LOSS<br>from sentence_transformers import SentenceTransformer, InputExample, losses<br>from torch.utils.data import DataLoader<br><br># Load a pre-trained embedding model<br>model = SentenceTransformer(&quot;BAAI/bge-base-en-v1.5&quot;)<br><br># Your domain-specific training pairs<br>train_examples = [<br>    InputExample(texts=[<br>        &quot;What are the contraindications for metoprolol?&quot;,<br>        &quot;Metoprolol is contraindicated in patients with severe bradycardia...&quot;<br>    ]),<br>    InputExample(texts=[<br>        &quot;How do I cancel my subscription?&quot;,<br>        &quot;To cancel, navigate to Account Settings and select Cancel Plan...&quot;<br>    ]),<br>    # ... hundreds more domain-specific pairs<br>]<br><br>loader = DataLoader(train_examples, shuffle=True, batch_size=32)<br><br># MultipleNegativesRankingLoss: treats all other items in the batch as negatives<br># Very effective and requires no explicit negative labelling<br>loss = losses.MultipleNegativesRankingLoss(model)<br><br>model.fit(<br>    train_objectives=[(loader, loss)],<br>    epochs=3,<br>    warmup_steps=100,<br>    show_progress_bar=True<br>)<br><br>model.save(&quot;my-domain-embedder&quot;)</pre><p>This is often the highest-leverage improvement you can make in a RAG system. Better retrieval means better context. Better context means the LLM has something useful to work with. Fix this first before you fine-tune anything else.</p><h3>13. Fine-tuning the retriever</h3><p>The retriever is more than just the embedding similarity search — it’s the complete mechanism for deciding which documents to surface. In more sophisticated RAG systems, this can include re-ranking models that take the initial set of retrieved chunks and reorder them based on a more nuanced relevance judgment.</p><p>A generic re-ranker doesn’t understand your users’ query patterns. In a legal system, “motion to compel” is a highly specific term that should retrieve documents about discovery disputes — not documents that merely mention compulsion. In a customer support system, “my account is locked” should prioritise account recovery docs over general security policy pages.</p><p>✅ FINE-TUNING A CROSS-ENCODER RE-RANKER</p><p>A cross-encoder takes (query, document) pairs as input and outputs a relevance score. Fine-tune one on your domain data — pairs of (query, document, label: relevant / not relevant). After fine-tuning, it dramatically improves the precision of what the LLM actually reads.</p><pre>🔬 CROSS-ENCODER RE-RANKER FINE-TUNING<br>from sentence_transformers import CrossEncoder<br><br># Start from a pre-trained cross-encoder<br>reranker = CrossEncoder(&quot;cross-encoder/ms-marco-MiniLM-L-6-v2&quot;)<br><br># Training data: (query, document, relevance_score)<br># Score 1 = highly relevant, 0 = not relevant<br>train_samples = [<br>    (&quot;refund policy enterprise&quot;, &quot;Enterprise clients may request refunds within 30 days...&quot;, 1),<br>    (&quot;refund policy enterprise&quot;, &quot;Our starter plan includes 5GB of storage...&quot;, 0),<br>    # ... many more examples<br>]<br><br># Fine-tune on your domain data<br>reranker.fit(<br>    train_dataloader=train_samples,<br>    epochs=3,<br>    evaluation_steps=500<br>)</pre><h3>14. Fine-tuning the generator LLM</h3><p>This is the step most people think of first when they say “fine-tune for RAG.” The generator is the LLM that takes the retrieved documents and the user’s question, and writes the actual answer. Fine-tuning it changes how it uses that retrieved context.</p><p>Without fine-tuning, a general-purpose LLM might ignore the retrieved documents and answer from memory. Or it might quote them verbatim when your users need a synthesis. Or it might give a five-paragraph essay when your product needs a one-sentence answer with a follow-up question.</p><p>Fine-tune it on examples of (question + retrieved context → ideal answer), and it learns to use the context reliably, in the format you want, in the tone you need.</p><pre>📋 GENERATOR FINE-TUNING DATA FORMAT (FOR RAG)<br>{<br>  &quot;system&quot;: &quot;You are a support agent. Answer using only the provided context. Be concise.&quot;,<br>  &quot;user&quot;: &quot;[CONTEXT]\nEnterprise customers may request refunds within 30 days of purchase by contacting billing@acme.com with their order number.\n\n[QUESTION]\nCan I get a refund on my enterprise plan?&quot;,<br>  &quot;assistant&quot;: &quot;Yes — enterprise customers can request a refund within 30 days of purchase. Just email billing@acme.com with your order number and they&#39;ll take care of it.&quot;<br>}<br><br># Key things this example teaches the model:<br># 1. Use the context, not general knowledge<br># 2. Answer directly without re-stating the question<br># 3. Match the casual, friendly tone<br># 4. Include the actionable detail (email + order number)</pre><p>For the generator, instruction tuning with LoRA or QLoRA is the most common approach. You’re not trying to fundamentally reshape the model — you’re teaching it to follow a specific pattern reliably. LoRA at rank 8–16 typically handles this well, and you can run the training on a single GPU if you use QLoRA.</p><p>If you care deeply about the <em>quality</em> of the outputs — not just the format — consider adding a DPO stage after SFT. Collect pairs of (question + context, good answer, acceptable-but-worse answer) and fine-tune the model to prefer the better one. This is how you get outputs that feel genuinely thoughtful, not just technically correct.</p><h3>15. How to actually do this — step by step</h3><p>Here’s a practical workflow. Not academic theory — the actual sequence of decisions and actions you make when fine-tuning for a RAG system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmvWjbuRaW1lRW9NuuxULA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGvCaqMWVVU40BxXz4ypSw.png" /></figure><h3>16. A real example — AI customer support from scratch</h3><p>Let’s make this concrete. You’re building an AI support agent for a SaaS product. Users ask things like “how do I cancel?” and “why did my payment fail?” and “can I export my data to Excel?” Here’s exactly how you’d architect and fine-tune this system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKt0oZmmX8TQEF_A78To1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKt0oZmmX8TQEF_A78To1Q.png" /></figure><p>The result: an agent that sounds like your best support rep, stays grounded in your actual documentation so it doesn’t hallucinate, updates instantly when you publish new help articles, and continuously improves as it sees more real user conversations.</p><h3>17. Mistakes people make — so you don’t have to</h3><p>⚠️ MISTAKE 1 — FINE-TUNING WHEN BETTER PROMPTING WOULD WORK</p><p>If the model isn’t following your formatting instructions, try a more specific system prompt first. Prompt engineering is free and instant. If 20 minutes of prompt iteration can fix the problem, spending a week on fine-tuning is waste. Fine-tuning makes sense when you’ve genuinely exhausted what prompts can do, not as a first resort.</p><p>⚠️ MISTAKE 2 — USING TOO LITTLE OR TOO LOW-QUALITY DATA</p><p>Fine-tuning on 50 examples of inconsistent quality will make your model behave worse, not better. The model learns the pattern — if the pattern is noisy, it learns noise. If you can’t produce at least 300 high-quality, consistent examples for your task, hold off. Invest in getting better data first.</p><p>⚠️ MISTAKE 3 — FINE-TUNING THE LLM TO MEMORISE FACTS</p><p>“Let’s fine-tune it to know all our product specs.” This is the most common trap. Facts that change belong in a RAG database — not baked into model weights through fine-tuning. When those facts change (and they will), you’d need to retrain. And fine-tuning on factual data significantly increases hallucination risk. Keep dynamic knowledge in the database. Always.</p><p>⚠️ MISTAKE 4 — IGNORING THE EMBEDDING MODEL</p><p>Teams go straight to fine-tuning the LLM and wonder why their RAG system is still giving bad answers. The problem is often upstream. If retrieval is pulling the wrong documents, no amount of generator fine-tuning will save you. Measure retrieval quality first. Fine-tune the embedder before you touch the generator.</p><p>⚠️ MISTAKE 5 — CHOOSING FULL FINE-TUNING WHEN LORA WOULD DO</p><p>Full fine-tuning sounds more powerful, so teams assume it’s always better. For most practical tasks, LoRA at rank 8–16 gets you 95% of the performance at 2% of the compute cost — with no catastrophic forgetting risk. Don’t reach for FFT unless you have a specific, demonstrated reason. That reason is rarer than people think.</p><p>⚠️ MISTAKE 6 — TREATING FINE-TUNING AS A ONE-TIME EVENT</p><p>Your product changes. Your users change. Your data changes. A model fine-tuned on your data from six months ago is already drifting. Build a retraining pipeline from day one. Collect feedback continuously. Schedule regular evaluation and retraining. The teams who build great AI products treat fine-tuning as a living process, not a launch task.</p><h3>18. The decision guide — what should you actually use?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OnsC3ghQb0TQPualuoPt8w.png" /></figure><h3>The whole thing in two paragraphs</h3><p>RAG and fine-tuning solve different problems, and they’re not rivals — they’re partners. RAG is about what the model knows: you connect it to a live database of documents so it can retrieve real facts before generating an answer. Fine-tuning is about how the model behaves: you train it to adopt your tone, follow your format, understand your vocabulary, and handle your specific tasks reliably. In a RAG pipeline, fine-tuning can be applied at three distinct points — the embedding model (for smarter document retrieval), the retriever or re-ranker (for better relevance judgement), and the generator LLM (for better, more consistent output quality). Each fixes a different part of the chain, and each makes a real difference.</p><p>When you fine-tune, you have real choices about how to do it. Full fine-tuning updates every parameter — powerful but expensive, slow, and risks catastrophic forgetting. LoRA freezes the original model and trains tiny adapter matrices instead, getting most of the benefit at a fraction of the cost. QLoRA compresses the base model to 4-bit and adds LoRA on top, making fine-tuning a 70B model possible on one or two GPUs. Adapters let you train modular, swappable task-specific modules without duplicating the full model. Instruction tuning (SFT) teaches the model to follow your task format. And alignment methods — DPO being the modern default, RLHF for more complex scenarios — teach it to produce outputs that humans genuinely prefer, not just outputs that technically fit the training data. Used together intelligently, these techniques let you build AI systems that are accurate, grounded, consistent, and actually pleasant to use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5336a68bcc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning]]></title>
            <link>https://medium.com/@likhitha.k2003/deep-learning-11d2ff2055af?source=rss-328b393d69f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/11d2ff2055af</guid>
            <dc:creator><![CDATA[Likhitha K]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 10:00:18 GMT</pubDate>
            <atom:updated>2026-03-23T10:00:18.875Z</atom:updated>
            <content:encoded><![CDATA[<p>Deep learning is a type of machine learning where computers learn patterns from data using <strong>neural networks with many layers</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*NBcbai0z2LQJ_LqB.jpg" /></figure><h4><strong>Activation Function</strong></h4><p>An activation function is a rule in a neural network that <strong>decides how much of a neuron’s input should be passed to the next layer</strong>.</p><h4><strong>Why activation functions exist</strong></h4><p>Imagine you’re adjusting a <strong>camera app</strong> .</p><ul><li>The camera captures raw light (input).</li><li>But before showing the photo, it applies filters:</li><li>Brightness</li><li>Contrast</li><li>Saturation</li></ul><p>Without these transformations, every photo would look dull and similar.</p><p>Now imagine:</p><ul><li>You stack 10 filters, but each filter only <em>adds brightness linearly</em>.</li></ul><p>No matter how many filters you stack → the result is still just a simple brightness change.</p><p><strong>Key idea:</strong><br> Without non-linear transformations, stacking layers adds <em>no real power</em>.</p><p>Activation functions are like <strong>intelligent filters</strong> that reshape information in powerful ways.</p><h3>2. What is an activation function?</h3><p>A neuron does two things:</p><ol><li>Combines inputs:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*iLfOV52BJgThG9aH4s8EHA.png" /></figure><p>2. Passes it through an activation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*Azqy8gJQIcLGL4un4h15kg.png" /></figure><p><strong>Activation function = a rule that decides how much signal should pass forward.</strong></p><h3>Why neural networks fail without it</h3><p>If you remove activation functions:</p><ul><li>Every layer becomes just linear math</li><li>Multiple layers collapse into a <em>single linear equation</em></li></ul><p>A 10-layer network = same as 1 layer</p><p>That means:</p><ul><li>Cannot learn complex patterns</li><li>Cannot model real-world relationships</li></ul><h3>3. Non-linearity (the core idea)</h3><h3>Simple intuition</h3><ul><li>Linear = straight line</li><li>Non-linear = curves, bends, shapes</li></ul><h3>Real-world example</h3><p>Predicting house price:</p><ul><li>Linear model:<br> “Price increases steadily with size”</li><li>Reality:</li><li>Small → cheap</li><li>Medium → rapidly increasing</li><li>Very large → luxury jump</li></ul><p>That curve is <strong>non-linear</strong></p><p><strong>Deep learning = learning complex curves in high dimensions</strong></p><p>Activation functions are what allow <strong>curves instead of straight lines</strong></p><h3><strong>4. Activation functions</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlBNN3G1vKJvRLohiak71g.png" /></figure><h3>Types of Activation Functions</h3><p>At the highest level, activation functions are divided into just <strong>two fundamental types</strong>:</p><h3>1. Linear Activation Function</h3><h3>Idea</h3><p>Output is directly proportional to input.</p><h3>Formula</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*1DAXRxkI5mGwwlT7ZS7i7Q.png" /></figure><h3>Intuition</h3><ul><li>Whatever goes in → comes out unchanged</li><li>No transformation, no filtering</li></ul><p>Like a pipe: water in = water out</p><h3>Key Insight</h3><p>Even if you stack many layers using linear activation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*-Nubcw0d1JJ2XhzMBNzxYA.png" /></figure><p>Multiple layers collapse into <strong>one single linear function</strong></p><h3>Limitation</h3><ul><li>Cannot learn complex patterns</li><li>Cannot model curves or relationships in real-world data</li></ul><h3>Where it is used</h3><ul><li>Output layer in <strong>regression problems</strong> (predicting continuous values like price)</li></ul><h3>2. Non-Linear Activation Functions</h3><h3>Idea</h3><p>Output is <strong>not proportional</strong> to input → introduces curves and complexity</p><h3>Intuition</h3><p>Instead of a straight line:</p><ul><li>It bends</li><li>Squashes</li><li>Clips</li><li>Amplifies differently in different regions</li></ul><p>Like a smart filter that reshapes information</p><h3>Why it is critical</h3><p>Without non-linearity:</p><ul><li>Deep learning becomes <strong>shallow learning</strong></li><li>Network behaves like <strong>linear regression</strong></li></ul><p>With non-linearity:</p><ul><li>Network can learn:</li><li>Images</li><li>Speech</li><li>Language</li><li>Complex patterns</li></ul><h3>Types of Non-Linear Activations</h3><p>These are the ones we actually use in deep learning:</p><ul><li>Sigmoid</li><li>Tanh</li><li>ReLU</li><li>Leaky ReLU</li><li>PReLU</li><li>ELU</li><li>Softmax</li></ul><h3>Key Insight</h3><p>Deep learning works <strong>only because of non-linear activation functions</strong></p><h3>Ultra-simple summary</h3><ul><li><strong>Linear activation</strong> → simple, limited, rarely used</li><li><strong>Non-linear activation</strong> → powerful, essential, always used</li></ul><h3>1. Sigmoid</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/0*XlgHm6nEKS0e6SoC.png" /></figure><h3>What it does</h3><p>Takes any number and compresses it into a value between <strong>0 and 1</strong></p><p>Think: <em>“How confident am I?”</em></p><h4><strong>Formula</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*gidIKsYNxwoL5yfzC3rp9g.png" /></figure><h3>Graph intuition</h3><ul><li>S-shaped curve</li><li>Very negative → close to <strong>0</strong></li><li>Very positive → close to <strong>1</strong></li><li>Middle (0) → <strong>0.5</strong></li></ul><h3>Advantages</h3><ul><li>Output behaves like probability</li><li>Smooth and continuous</li></ul><h3>Disadvantages</h3><ul><li><strong>Vanishing gradient</strong> (learning slows down deeply)</li><li>Not centered around zero → inefficient learning</li></ul><h3>Where used</h3><ul><li>Output layer for <strong>binary classification</strong></li></ul><h3>2. Tanh</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/0*HvwdEZEmCMlXG_gk.png" /></figure><h3>What it does</h3><p>Like sigmoid, but outputs between <strong>-1 and 1</strong></p><p>Think: <em>“Direction + strength”</em></p><h4><strong>Formula</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*ceabP_LYRbNnw_LXoZii4g.png" /></figure><h3>Graph intuition</h3><ul><li>S-shaped</li><li>Centered at 0</li><li>Negative inputs → negative outputs</li><li>Positive inputs → positive outputs</li></ul><h3>Advantages</h3><ul><li>Zero-centered → faster learning than sigmoid</li><li>Stronger gradients near center</li></ul><h3>Disadvantages</h3><ul><li>Still suffers from <strong>vanishing gradient.</strong></li></ul><h3>Where used</h3><ul><li>Hidden layers (older networks)</li><li>RNNs</li></ul><h3>3. ReLU (Rectified Linear Unit)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*qyCUFNONuiGXGWR-.png" /></figure><h3>What it does</h3><p>Keeps positive values, removes negative ones</p><p>Think: <em>“Only useful signals pass”</em></p><h4><strong>Formula</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*7WR5xcd8QRYAQZ6Ol5HqUQ.png" /></figure><h3>Graph intuition</h3><ul><li>Left side (negative) → flat at 0</li><li>Right side (positive) → straight line</li></ul><h3>Advantages</h3><ul><li>Very fast</li><li>Works extremely well in deep networks</li><li>Avoids vanishing gradient (on positive side)</li></ul><h3>Disadvantages</h3><ul><li><strong>Dead neurons</strong> (stuck at 0 forever)</li></ul><h3>Where used</h3><ul><li>Default choice for hidden layers</li></ul><h3>4. Leaky ReLU</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*38L_MmCBOq3oa2p4.png" /></figure><h3>What it does</h3><p>Allows a small negative signal instead of zero</p><p>Think: <em>“Even weak signals matter a little”</em></p><h3>Formula</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*pPON20hvlsAXQ5BY07eACw.png" /></figure><h3>Graph intuition</h3><ul><li>Slight slope in negative region (not flat)</li><li>Positive side same as ReLU</li></ul><h3>Advantages</h3><ul><li>Prevents dead neurons</li><li>Keeps learning alive</li></ul><h3>Disadvantages</h3><ul><li>Negative slope is fixed (not adaptive)</li></ul><h3>Where used</h3><ul><li>When ReLU causes too many dead neurons</li></ul><h3>5. Parametric ReLU (PReLU)</h3><h3>What it does</h3><p>Learns how much negative slope is needed</p><p>Think: <em>“Model decides how much to listen to negatives”</em></p><h3>Formula</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*9U7tFytKI0aqsKp2WCh75g.png" /></figure><h3>Graph intuition</h3><ul><li>Same as Leaky ReLU</li><li>But slope is <strong>learned</strong>, not fixed</li></ul><h3>Advantages</h3><ul><li>More flexible</li><li>Better performance in some cases</li></ul><h3>Disadvantages</h3><ul><li>Extra parameters → slight complexity</li></ul><h3>Where used</h3><ul><li>Advanced deep models</li></ul><h3>6. ELU (Exponential Linear Unit)</h3><h3>What it does</h3><p>Smoothly curves negative values instead of cutting them</p><p>Think: <em>“Soft landing instead of hard cutoff”</em></p><h4><strong>Formula</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*7X-k1VhkbTS7j5ShEdA6Tg.png" /></figure><h3>Graph intuition</h3><ul><li>Positive → linear</li><li>Negative → smooth curve approaching a limit</li></ul><h3>Advantages</h3><ul><li>Faster learning</li><li>Reduces bias shift</li><li>More stable training</li></ul><h3>Disadvantages</h3><ul><li>Slightly slower computation</li></ul><h3>Where used</h3><ul><li>Deep networks needing stability</li></ul><h3>7. Softmax</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xe5SC5J-oPWyTwu3.png" /></figure><h3>What it does</h3><p>Turns multiple outputs into probabilities that sum to 1</p><p>Think: <em>“Which option is most likely?”</em></p><h3>Formula</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*sMSIFlWX0C9-3Qy06dO8nA.png" /></figure><h3>Graph intuition</h3><ul><li>Not a single curve</li><li>Converts a list → probability distribution</li></ul><p>Example:</p><ul><li>Input: [2, 1, 0]</li><li>Output: [0.7, 0.2, 0.1]</li></ul><h3>Advantages</h3><ul><li>Gives clear probabilities</li><li>Perfect for classification</li></ul><h3>Disadvantages</h3><ul><li>Sensitive to large values</li></ul><h3>Where used</h3><ul><li>Output layer for <strong>multi-class classification</strong></li></ul><h3>Graph intuition for all Activation Functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*ECB4wy2uTK-YZc5o.png" /></figure><h4><strong>Summary Table</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PPvyecvgTnk5le28Stt38w.png" /></figure><h3><strong>Conclusion</strong></h3><p>Activation functions are what make neural networks <strong>powerful and intelligent</strong>.</p><ul><li>Without them → the network is just a <strong>linear model (very limited)</strong></li><li>With them → the network can learn <strong>complex, real-world patterns</strong></li></ul><p><strong>Quick rules:</strong></p><ul><li>Use <strong>ReLU</strong> for hidden layers</li><li>Use <strong>Sigmoid</strong> for binary output</li><li>Use <strong>Softmax</strong> for multi-class output</li></ul><p><strong>Key idea:</strong></p><p>Activation functions add <strong>non-linearity</strong>, and non-linearity is what makes deep learning actually work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11d2ff2055af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Discreet Probability Distributions]]></title>
            <link>https://medium.com/@likhitha.k2003/discreet-probability-distributions-da6c5ad13894?source=rss-328b393d69f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/da6c5ad13894</guid>
            <dc:creator><![CDATA[Likhitha K]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 18:51:12 GMT</pubDate>
            <atom:updated>2025-11-15T19:05:03.385Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>“Probability is measure of uncertainty”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IhJqYEF3j7pW74GGXkmylA.png" /></figure><p><strong>Probability is the measure of how likely something is to happen.</strong><br> It tells us the chance of an event using numbers between <strong>0</strong> (won’t happen) and <strong>1</strong> (will definitely happen).<br> It helps us describe and understand uncertainty in a precise way.</p><h3><strong>Random Variable</strong></h3><p>Random Variable<strong> (x) </strong>is a<strong> F</strong>unction which takes the Sample space as input and map’s to the real number.</p><p>A <strong>random variable</strong> is a numerical value that represents the outcome of a random process.<br> It assigns a <strong>number</strong> to each possible result of an uncertain event.</p><p>Even though the event is unpredictable, the random variable gives us a structured way to describe and analyze it using mathematics.</p><h4><strong>Mathematical Representation</strong></h4><h3><strong>X:SS →|R</strong></h3><h4>Why It’s Called a “Variable”</h4><p>It’s called a <em>variable</em> because its value <strong>changes</strong> depending on the outcome of the experiment.</p><p>It’s called <em>random</em> because the outcome itself is uncertain.</p><h3>1. Discrete Random Variable</h3><p>Takes <strong>countable</strong> values (whole numbers).</p><p><strong>Examples:</strong></p><ul><li>Number of heads in 3 coin flips (0, 1, 2, or 3)</li><li>Number of customers arriving in 1 hour</li><li>Number of defective items in a batch</li><li>Outcome of rolling a die (1–6)</li></ul><h3>What Is a Distribution?</h3><p>A <strong>distribution</strong> describes how the probabilities of a random variable are spread across its possible values.<br> In other words, it tells us <strong>which outcomes are likely, less likely, or unlikely</strong>, and how those probabilities are arranged.</p><p>A distribution gives a complete picture of the behavior of a random variable.</p><p>Distribution is used to find how the total frequency/probability is distributed or shared among the datapoints.</p><h4><strong>Significance of Distribution:</strong></h4><ol><li>Understanding the nature about the data.</li><li>To estimate population data parameters on sample parameters.</li><li>To choose Type of visualization.</li><li>To perform Hypothesis Testing.</li><li>The assumptions of few ML Algorithms.</li></ol><h4>Discrete Probability Distribution:</h4><p>If the outcomes of a random experiment is discreet is called <strong>Discrete Probability Distribution.</strong></p><p>A <strong>discrete probability distribution</strong> describes how the probability of a discrete random variable is spread across its <strong>countable</strong> possible values. Each value has its own specific probability, and all those probabilities together must add up to <strong>1</strong>.</p><h3>Key Points</h3><ul><li>Outcomes are <strong>distinct and countable</strong> (0, 1, 2, 3, …).</li><li>Each outcome has a <strong>probability between 0 and 1</strong>.</li><li>Total probability across all outcomes equals <strong>1</strong>.</li><li>Represented using a <strong>Probability Mass Function (PMF)</strong>.</li></ul><h3>Simple Examples</h3><ul><li>Rolling a die: each value 1–6 has probability 1/61/61/6.</li><li>Number of heads in 3 coin tosses: probabilities assigned to {0,1,2,3}.</li><li>Number of customer arrivals in an hour: probabilities for 0,1,2,3,… arrivals.</li></ul><h3>What It Tells You</h3><p>It shows which outcomes are common, which are rare, and how the random variable behaves overall — giving a full picture of uncertainty in situations where results come in separate steps or counts.</p><h4><strong>Types of discrete probability distributions:</strong></h4><ul><li>Bernoulli distribution</li><li>Binomial distribution</li><li>Multinomial distribution</li><li>Poisson distribution</li><li>Negative binomial distribution</li><li>Geometric distribution</li></ul><h4>Bernoulli distribution:</h4><p>A <strong>Bernoulli distribution</strong> models a random experiment that has only <strong>two possible outcomes</strong>:</p><ul><li><strong>Success (1)</strong></li><li><strong>Failure (0)</strong></li></ul><p>The probability of success is p, and the probability of failure is 1−p</p><p><strong>Bernoulli Distribution Models the Random Variable with two possible outcomes (Success/Failure) in one trail.</strong></p><h4>Mathematical Representation</h4><p><strong>X~B(1,p)</strong></p><p>p=Probability of success</p><p>The<strong> PMF(</strong>Probability Mass Function) of<strong> Bernoulli Distribution</strong> is given by</p><p><strong>p(X=x){p if x=1 ,1-p if x=0</strong></p><h4>Example</h4><p>Flipping a coin where:</p><ul><li>Head = 1</li><li>Tail = 0</li></ul><p>If the probability of getting a head is p=0.5p = 0.5p=0.5, then the flip follows a Bernoulli distribution.</p><h4>Expected Value (Mean)</h4><p><strong>E(X)=p</strong></p><h3>Variance</h3><p><strong>Var(X)=p(1−p)</strong></p><h3><strong>Binomial distribution</strong></h3><p>A <strong>Binomial distribution</strong> models the number of <strong>successes</strong> obtained in a fixed number of <strong>independent trials</strong>, where each trial has only two outcomes (success or failure) and the probability of success remains constant.</p><p>It is essentially the sum of multiple Bernoulli trials.</p><p>Binomial distribution models Random Variable with two possible Outcomes(success/Failure)in “n” number of Trails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*9CMAWA2d-ZazGVokBDIkcA.png" /></figure><h4>Mathematical Representation</h4><p><strong>X~B(n,p)</strong></p><p>n=Number of Trails</p><p>p=probability of success.</p><p>X = number of successes in n trials.</p><h3>Conditions for Binomial Distribution</h3><p>A random variable follows a binomial distribution when:</p><ol><li>There are <strong>n fixed trials</strong></li><li>Each trial has <strong>two outcomes</strong> (success/failure)</li><li>Probability of success p is the <strong>same</strong> for each trial</li><li>Trials are <strong>independent</strong></li></ol><h3>Probability Mass Function (PMF)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*8r1aHuXAJb8jqEd86gcvnw.png" /></figure><h3>Example</h3><p>Toss a fair coin <strong>10 times</strong>, and let XXX be the number of heads.</p><ul><li>Each toss = Bernoulli trial</li><li>Probability of head p=0.5</li><li>Number of trials n=10</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*7uniNVdwEZFWFWwSarQe3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*-hl_hv8EYeqpoyo6mfOs1Q.png" /></figure><h3><strong>Multinomial distribution</strong></h3><p>A <strong>Multinomial distribution</strong> generalizes the binomial distribution to experiments where each trial has <strong>more than two possible outcomes</strong>.<br> Each trial results in one of <strong>k categories</strong>, and the probabilities of these categories remain constant across all trials.</p><p>It models how many times each category occurs in <strong>n independent trials</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*ZpsL7o4ohxPl_z_27sNuVw.png" /></figure><p><strong>Multinomial distribution models random variable with more than two outcomes in n number of trails.</strong></p><h4>Mathematical Representation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*fG7nCoq0SrLmdg0gW-RJKQ.png" /></figure><h3>Conditions</h3><p>A random vector follows a multinomial distribution when:</p><ol><li>There are <strong>n fixed trials</strong></li><li>Each trial has <strong>k outcomes</strong></li><li>Probabilities p1,p2,…,pk remain constant</li><li>All trials are <strong>independent</strong></li></ol><h3>Probability Mass Function (PMF)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*R3OAxROl873BfdEONXvYNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*354iiq0vgIJ5z9YWefFOZg.png" /></figure><h3>Poisson Distribution</h3><p>A <strong>Poisson distribution</strong> models the number of times an event occurs in a <strong>fixed interval</strong> of time or space, <strong>when the events happen independently and at a constant average rate</strong>.</p><p>It is widely used for <strong>rare events</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*b_GwleiU4xOLYAZecuiwxA.png" /></figure><p><strong>Poisson distribution </strong>Models the random variable with number of sucess in the given average time.</p><h4>Mathematical Representation</h4><h4><strong>x~p(lambda)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*QmUHGjjMVzp5xhlhq7wN8Q.png" /></figure><h3>Key Conditions</h3><p>A random variable follows a Poisson distribution when:</p><ol><li>Events occur <strong>independently</strong></li><li>Events occur at a <strong>constant average rate</strong> λ\lambdaλ</li><li>Two events cannot happen <strong>at the exact same instant</strong> (events are rare)</li><li>The probability of an event in a small interval is proportional to the length of the interval</li></ol><h3>Probability Mass Function (PMF)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*QUPBNVq26yrVmY0134PSog.png" /></figure><h3>Example</h3><p>Suppose a call center receives an average of <strong>5 calls per hour</strong>.<br> Let XXX = number of calls in the next hour.</p><p>Then:</p><p><strong>X∼Poisson(5)</strong></p><p>You can compute probabilities like:</p><ul><li>probability of receiving 0 calls</li><li>probability of receiving 3 calls</li><li>probability of receiving more than 5 calls</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*v2A1SOvWfsQ1X3XCXiLVKg.png" /></figure><h3><strong>Negative binomial distribution</strong></h3><p>A <strong>Negative Binomial distribution</strong> models the number of trials required to achieve a fixed number of <strong>r successes</strong>, where each trial has only two outcomes and the probability of success remains constant.</p><p>It is essentially a generalization of the geometric distribution (which is the special case when r=1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*XDQXGPhAyzG6XaAnAtqTCw.png" /></figure><p><strong>Negative binomial distribution </strong>Models the random variable with number of required trails (X) to get r success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*5ITRnmAPR2JLDueif93S0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*9QWSOszQO-2-82uxkZbjHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*XZEyO7djcxusU_vwN1EgKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*ghTIrJsJz6v-VhayqtQC4A.png" /></figure><h4><strong>Geometric distribution</strong></h4><p>A <strong>Geometric distribution</strong> models the number of <strong>trials required to get the first success</strong> in a sequence of independent trials, where each trial has only two outcomes and the probability of success remains constant.</p><p>It captures “how long it takes until success happens.”</p><p><strong>Geometric distribution</strong> models the random variable with number of trails required to get first Success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*BbxcbxvUebgFbRSFw8aJCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*11e1y6R3b55t49FCGBoHeQ.png" /></figure><h3>Example</h3><p>Suppose the probability of hitting a target in one attempt is p=0.3.<br> Let X = number of attempts until the first hit.</p><p>Then:</p><p><strong>X∼Geometric(0.3)</strong></p><p>You can find probabilities like:</p><ul><li>the first hit occurs on the 1st shot</li><li>the first hit occurs on the 4th shot</li><li>no hit until several attempts</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*ivJUIWLEUEEL_UMYYADkyQ.png" /></figure><h3>Conclusion</h3><p>Discrete probability distributions provide a powerful framework for understanding and predicting outcomes in situations where results occur in <strong>countable steps</strong>. From simple yes/no processes in Bernoulli trials to more complex models like binomial, geometric, Poisson, negative binomial, and multinomial distributions, each distribution captures a distinct pattern of randomness found in real life.</p><p>These models help quantify uncertainty, calculate risks, and support smarter decision-making across fields such as data science, machine learning, finance, operations, and everyday analytics. By choosing the right distribution for a problem, we gain clearer insights into the behavior of random events and build stronger, more reliable statistical models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da6c5ad13894" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MISSING VALUES..]]></title>
            <link>https://medium.com/@likhitha.k2003/missing-values-1d6e85d68905?source=rss-328b393d69f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6e85d68905</guid>
            <category><![CDATA[handling-missing-values]]></category>
            <dc:creator><![CDATA[Likhitha K]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 08:27:27 GMT</pubDate>
            <atom:updated>2025-09-17T08:32:48.978Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is python?</h4><p><strong>Python</strong> is a computer programming language that helps people tell computers what to do in an easy way. It is known for being simple, clear, and beginner-friendly, almost like writing everyday English.</p><p>With Python, you can create <strong>websites, build apps, analyze data, make games, automate tasks, and even power artificial intelligence. </strong>It’s like a Swiss army knife for coding — one tool with many uses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*Qrmkfneh4MXOiGpH.jpg" /></figure><p>Because it’s <strong>easy to learn and very powerful, Python is one of the most popular languages in the world today.</strong></p><h4>What is pandas?</h4><p>Pandas is a <strong>special tool (library) </strong>in Python that makes working with data very easy. Think of it like an Excel sheet inside Python, where you can store information in rows and columns.</p><p><strong>With Pandas, you can:</strong></p><ul><li>Read data from files like Excel, CSV, or databases.</li><li>Clean messy data and organize it.</li><li>Filter, sort, and analyze information quickly.</li><li>Create summaries and even prepare data for charts or machine learning.</li></ul><p>In short, Pandas is Python’s data assistant — it helps you handle data smoothly and efficiently.</p><h4><strong>Missing values</strong></h4><h4>What are missing values?</h4><p>Missing values in Pandas are the empty or null entries in a dataset, usually represented as <strong>NaN (Not a Number)</strong>. They indicate that some data is unavailable, not recorded, or undefined.</p><h4><strong>Representation of missing values?</strong></h4><p>In <strong>Pandas</strong>, missing values are mainly represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*Dic7i18CrXO-6Ts2yDUYDA.png" /></figure><ul><li><strong>NaN</strong> → <em>Not a Number</em> (most common for numerical or mixed data).</li><li><strong>NaT</strong> → <em>Not a Time</em> (used for missing date/time values).</li><li><strong>None</strong> → Python’s built-in null object (often seen in text/object data).</li></ul><p>👉 Pandas automatically treats all of these as <strong>missing values</strong>.</p><h4><strong>Impact of Missing Values</strong></h4><p>Missing values can affect your data analysis and results in many ways:</p><ol><li><strong>Inaccurate Calculations</strong> — A single<strong> NaN</strong> can break formulas like mean, sum, or percentage.</li><li><strong>Biased Insights</strong> — If too many values are missing, your conclusions may be misleading.</li><li><strong>Errors in Models</strong> — Machine learning algorithms may reject or misinterpret missing data.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMiaHANA9qXGj_iXAVwK3g.png" /></figure><ol><li><strong>Loss of Data</strong> — Removing missing values might reduce the dataset and hide useful patterns.</li><li><strong>Difficulty in Visualization</strong> — Charts and graphs may appear incomplete or misleading.</li></ol><p>👉 In short, missing values, if not handled properly, can reduce accuracy, reliability, and usefulness of your analysis.</p><h4>Main reasons for missing values</h4><ol><li><strong>Human Error</strong> — People forget to fill in forms, enter wrong data, or leave blanks.</li><li><strong>Data Entry Issues</strong> — Mistakes during typing, scanning, or importing files.</li><li><strong>Not Applicable Data</strong> — Some information doesn’t apply (e.g., “Spouse Name” for unmarried people).</li><li><strong>Survey Non-Response</strong> — Respondents skip certain questions.</li><li><strong>System/Technical Errors</strong> — Data lost during collection, transfer, or storage.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*60eiBkPPTLVcZTFTSdVhaQ.png" /></figure><ol><li><strong>Merging Datasets</strong> — When combining two tables, some records don’t match, leading to blanks.</li><li><strong>Sensor/Instrument Failure</strong> — In scientific or IoT data, devices may stop recording temporarily.</li></ol><p>👉 In short: Missing values happen because of <strong>human mistakes, system errors, or data that simply doesn’t exist</strong>.</p><h3>Types of Missing Values</h3><p>Missing values don’t all occur for the same reason. In data science, they are grouped into three main types:</p><h4>1. Missing Completely at Random (MCAR)</h4><ul><li><strong>Meaning</strong>: The missingness happens purely by chance, unrelated to any variable in the dataset.</li><li><strong>Impact</strong>: Doesn’t introduce bias — your dataset is still representative, just smaller.</li></ul><p><strong>Example</strong>:</p><ul><li>A student accidentally skips a question on a survey form.</li><li>A sensor randomly fails to record a value once in a while.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*q8DOkrtki2r0yaDnLCPf5w.png" /></figure><h4>2. Missing at Random (MAR)</h4><ul><li><strong>Meaning</strong>: The missingness is related to some <em>other</em> observed variable, but not to the missing data itself.</li><li><strong>Impact</strong>: If not handled, it can introduce bias. But since the reason is linked to other known data, we can adjust.</li></ul><p><strong>Example</strong>:</p><ul><li>In a medical survey, <strong>older patients</strong> are less likely to answer income questions.</li><li>The missingness depends on <strong>age</strong>, not on <strong>income itself</strong>.</li></ul><h4>3. Missing Not at Random (MNAR)</h4><ul><li><strong>Meaning</strong>: The missingness depends on the <em>value of the missing data itself</em>.</li><li><strong>Impact</strong>: This is the trickiest — ignoring it creates serious bias. Often needs domain knowledge to fix.</li></ul><p><strong>Example</strong>:</p><ul><li>People with very <strong>high salaries</strong> choose not to reveal their income.</li><li>Patients with <strong>severe illness</strong> avoid answering health questions.</li></ul><h4>Identification of Missing Values</h4><p>Pandas makes it very easy to detect missing values in a dataset. Since missing values are usually shown as <strong>NaN, NaT, or None</strong>, we can use built-in functions to find them.</p><h3>isna()</h3><p><strong>Definition</strong>:<br> <strong>isna()</strong> is a function in Pandas used to <strong>detect missing values</strong> in a DataFrame or Series.<br> It returns a <strong>Boolean mask</strong>:</p><ul><li><strong>True</strong> → if the value is missing (NaN, NaT, or None)</li><li><strong>False</strong> → if the value is present</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*Zg5ezS2B8vOTlVvaD9UG_g.png" /></figure><h4>Syntax:</h4><p>DataFrame.isna()<br> Series.isna()</p><pre>import pandas as pd<br><br>data = {&#39;Name&#39;: [&#39;Ananya&#39;, &#39;Rohan&#39;, &#39;Meera&#39;],<br>        &#39;Age&#39;: [21, None, 19],<br>        &#39;Marks&#39;: [85, 90, None]}<br><br>df = pd.DataFrame(data)<br><br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br><br>print(&quot;\nDetecting missing values with isna():&quot;)<br>print(df.isna())<br></pre><h4>Output:</h4><pre>Original DataFrame:<br>     Name   Age  Marks<br>0  Ananya  21.0   85.0<br>1   Rohan   NaN   90.0<br>2   Meera  19.0    NaN<br><br>Detecting missing values with isna():<br>    Name    Age  Marks<br>0  False  False  False<br>1  False   True  False<br>2  False  False   True</pre><ul><li><strong>isna()</strong> works the same as <strong>isnull()</strong> in Pandas.</li><li>Commonly used with <strong>.sum()</strong> to count missing values</li></ul><pre>print(df.isna().sum())</pre><pre>Name     0<br>Age      1<br>Marks    1<br>dtype: int64</pre><h4>Identification of Missing Values Using Visualization Methods</h4><p>Data is rarely perfect. When working with real-world datasets, missing values are almost inevitable. Identifying them early is critical because they can distort statistical analyses, bias models, and weaken insights. While simple functions like .isnull().sum() in Python can show counts of missing values, visualization methods make the problem <strong>intuitive, interpretable, and actionable</strong>.</p><h4>Why Visualization for Missing Data?</h4><ul><li><strong>Pattern recognition</strong>: See where missingness is concentrated (e.g., specific columns, time ranges, or categories).</li><li><strong>Scale of the problem</strong>: Spot whether missing data is minimal (e.g., &lt;5%) or extensive.</li><li><strong>Correlation of missingness</strong>: Understand if missing values in one column are linked to another.</li></ul><h4>Common Visualization Methods</h4><h4>1. Heatmap</h4><p>A heatmap highlights missing values across rows and columns.</p><ul><li><strong>How</strong>: Each cell is colored based on whether data is missing or present.</li><li><strong>Insight</strong>: Quickly shows which variables have the most missing entries.</li><li><strong>Tools</strong>: seaborn.heatmap(df.isnull()) or missingno.matrix() in Python.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5OBBcoMDo-_I1GPE.png" /></figure><p><strong><em>Example</em>:</strong> In a medical dataset, a heatmap may reveal entire rows of missing lab results, indicating systematic collection issues.</p><h4>2. Bar Plot</h4><p>A bar plot quantifies missing values per column.</p><ul><li><strong>How</strong>: Each bar represents the count or percentage of missing entries in a column.</li><li><strong>Insight</strong>: Useful for prioritizing which variables require imputation or removal.</li><li><strong>Tools</strong>: missingno.bar(df) or plotting df.isnull().sum() with Matplotlib.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjiacYt0U4Wy5GSIjsNggg.png" /></figure><p><strong><em>Example</em></strong>: In a customer dataset, a bar chart may show that phone_number is missing for 60% of customers—suggesting low reliability of that field.</p><h4>3. Matrix Plot</h4><p>A matrix plot visualizes the dataset row by row, with gaps indicating missingness.</p><ul><li><strong>How</strong>: Present values are shaded, while missing ones appear blank or in a contrasting color.</li><li><strong>Insight</strong>: Helps detect data-entry patterns (e.g., blocks of missing values).</li><li><strong>Tools</strong>: missingno.matrix(df).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfj6CCr26MjDZvIfhbcuNw.png" /></figure><p><strong><em>Example</em></strong>: In time-series data, a matrix plot can reveal that sensor readings are missing for continuous days, pointing to device failure.</p><h4>Advantages of Visualization-Based Detection</h4><ul><li>Makes missingness patterns clear to <strong>non-technical stakeholders</strong>.</li><li>Identifies not just the <strong>extent</strong>, but also the <strong>structure</strong> of missing data.</li><li>Guides the choice between <strong>deletion, imputation, or advanced techniques</strong> like multiple imputation.</li></ul><p>Detecting missing values is the <strong>first diagnostic checkpoint</strong> in data preprocessing. Visualization transforms missingness from abstract counts into <strong>actionable insights</strong>. Heatmaps, bar charts, matrix plots, dendrograms, and correlation maps each offer unique perspectives, making them indispensable for exploratory data analysis.</p><h4>Treatment of Missing Values</h4><p>Missing values can cause errors or bias in data analysis, so they must be handled carefully.</p><h4><strong>The two main approaches are:</strong></h4><h4>1. Dropping Missing Values</h4><p>We simply remove the rows or columns that contain missing values.</p><h4>When to Drop Rows</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UJfuvvuy7uPUox5n7A8zg.png" /></figure><ul><li>When the percentage of missing values in a row is <strong>less than 5%</strong>.</li><li>When missing values occur <strong>completely at random (MCAR)</strong>.</li><li>When the dataset is <strong>large</strong> and losing a few rows doesn’t harm the analysis.</li></ul><h4><strong>Code Example:</strong></h4><pre>df.dropna(inplace=True)    # Drops rows with missing values</pre><h4>When to Drop Columns</h4><ul><li>If a column has <strong>too many missing values</strong> (40–50% or more).</li><li>If the column is <strong>irrelevant</strong> for analysis or prediction.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUM8YDCr4sIhTWjAOgGX6g.png" /></figure><ul><li>If the column is <strong>highly correlated</strong> with another column (to avoid multicollinearity).</li></ul><pre>df.dropna(axis=1, inplace=True)   # Drops columns with missing values</pre><h4>2. Imputing Missing Values (Filling In Data)</h4><p>Instead of dropping data, we can <strong>fill missing values</strong> with meaningful substitutes.</p><h4>Methods of Imputation</h4><h4><strong>1. Statistical Value Imputation</strong></h4><ul><li>Replace missing values with <strong>mean, median, or mode</strong>.</li><li>Best for numeric columns.</li></ul><pre>df[&#39;Age&#39;].fillna(df[&#39;Age&#39;].mean(), inplace=True)<br>df[&#39;Marks&#39;].fillna(df[&#39;Marks&#39;].median(), inplace=True)<br>df[&#39;City&#39;].fillna(df[&#39;City&#39;].mode()[0], inplace=True)</pre><h4><strong>2. Constant Value Imputation</strong></h4><ul><li>Fill with a fixed value like <strong>0</strong>, <strong>&quot;Unknown&quot;</strong>, etc.</li></ul><pre>df[&#39;Age&#39;].fillna(0, inplace=True)<br>df[&#39;City&#39;].fillna(&quot;Unknown&quot;, inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gyOaRnhFH5TmPRay.png" /></figure><h4>3. <strong>Dataset Value Filling</strong></h4><ul><li>Use nearby values to fill missing entries.</li><li><strong>Forward Fill (ffill)</strong>: Copy the previous value.</li><li><strong>Backward Fill (bfill)</strong>: Copy the next value.</li></ul><pre>df.fillna(method=&#39;ffill&#39;, inplace=True)<br>df.fillna(method=&#39;bfill&#39;, inplace=True)</pre><h4>4. <strong>Group-wise Imputation</strong></h4><ul><li>Fill missing values using group-specific statistics (mean, median, etc.).</li></ul><p><strong>Example: </strong>Fill missing age by calculating the <strong>mean age per gender</strong>.</p><pre>df[&#39;Age&#39;] = df.groupby(&#39;Gender&#39;)[&#39;Age&#39;].transform(lambda x: x.fillna(x.mean()))</pre><h4><strong>5. Interpolation</strong></h4><ul><li>Estimate values using mathematical trends.</li><li>Best for <strong>time-series or continuous numeric data</strong>.</li></ul><pre>df[&#39;Marks&#39;].interpolate(method=&#39;linear&#39;, inplace=True)</pre><h4><strong>6. ML-based Imputation</strong></h4><ul><li>Use machine learning algorithms (e.g., <strong>KNN Imputer, Iterative Imputer</strong>) to predict missing values.</li><li>Suitable for complex datasets.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*IjGiEn6v0hgemIyKqQVvLA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6e85d68905" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Naming: A Deep Dive into Python Variables and Identifiers]]></title>
            <link>https://medium.com/@likhitha.k2003/the-power-of-naming-a-deep-dive-into-python-variables-and-identifiers-1b52a9515a5c?source=rss-328b393d69f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b52a9515a5c</guid>
            <dc:creator><![CDATA[Likhitha K]]></dc:creator>
            <pubDate>Sat, 12 Jul 2025 07:28:57 GMT</pubDate>
            <atom:updated>2025-07-12T07:28:57.309Z</atom:updated>
            <content:encoded><![CDATA[<p>Discover how to store data efficiently and write readable, maintainable Python code from the ground up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*joGVw25AbXM-0INFf8f_Vg.png" /></figure><h4><strong>Introduction: Giving Your Python Code a Memory</strong></h4><p>Ever wondered how your Python programs remember things? How they keep track of numbers, words, or complex information? The secret lies in something fundamental: <a href="https://www.w3schools.com/python/python_variables.asp"><strong>variables</strong></a> and <a href="https://www.geeksforgeeks.org/python/python-keywords-and-identifiers/"><strong>identifiers</strong></a>. Think of them as the memory cells of your code, allowing you to store and retrieve data with meaningful names.</p><p>In this article, you’ll learn:</p><ol><li>What variables are and why they’re essential.</li><li>How to assign values to variables.</li><li>The strict (but simple!) rules for naming identifiers.</li><li>Best practices for writing clean, readable variable names.</li></ol><p>Let’s dive in and empower your Python code with clarity</p><h4>What are Variables? The Labeled Jar in Your Program’s Pantry</h4><p>Imagine your Python program as a bustling kitchen, and your computer’s memory as its vast pantry. In this pantry, you don’t just dump all your ingredients into one giant pile. Instead, you use <strong>labeled jars</strong> to keep everything organized — flour in the ‘Flour’ jar, sugar in the ‘Sugar’ jar, and so on.</p><p>In Python, a <strong>variable</strong> is exactly like one of those <strong>labeled jars in your program’s pantry</strong>. It’s a dedicated spot in your computer’s memory where you can store a piece of data. When you create a variable, you’re essentially saying to Python, ‘Hey, set aside some space, and I’m going to call it <em>this name</em> to hold <em>this piece of data</em>.’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*O_XRtJiaDkV2soQrpXiOgQ.png" /></figure><p>One of Python’s super powers is that it’s <strong>dynamically typed</strong>. This means Python acts like a magic label maker for your jars. You don’t have to specify what <em>type</em> of ingredient (number, text, etc.) will go into a jar beforehand. Python automatically figures that out when you put the ‘ingredient’ (value) in. Need to store a number? Just put it in! Want to store text? No problem, Python adjusts the ‘label’ behind the scenes.</p><pre># Storing a number (integer) - Think of this as putting &#39;30&#39; into the &#39;age&#39; jar<br>age = 30<br>print(age) # Output: 30<br><br># Storing text (string) - Now we put &#39;Alice&#39; into the &#39;name&#39; jar<br>name = &quot;Alice&quot;<br>print(name) # Output: Alice<br><br># Storing a true/false value (boolean) - A jar for a simple yes/no<br>is_student = True<br>print(is_student) # Output: True<br><br># Storing a decimal number (float) - A jar for a price or measurement<br>price = 19.99<br>print(price) # Output: 19.99</pre><h4><strong>Meet the Identifier: Your Code’s Glossary — Speaking Human to Python</strong></h4><p>Now that we know variables are like labeled jars, what exactly are those labels? In Python, the name you give to your variable is called an <strong>identifier</strong>. But these aren’t just any labels; they’re the words that make your code understandable, turning cryptic instructions into something almost like a conversation.</p><p>Think of identifiers as your code’s <strong>built-in glossary</strong>. They let you speak “human” to Python, explaining your intentions directly in the code itself. Consider the difference:</p><h3>Understanding the Distinction: Variables vs. Identifiers</h3><p>While often used interchangeably in casual conversation, it’s crucial to understand the precise relationship between a <strong>variable</strong> and an <strong>identifier</strong> in Python. Think of it this way:</p><ul><li>A <strong>Variable</strong> is the <strong>container</strong> itself — the actual memory location set aside to store a piece of data. In our kitchen analogy, it’s the physical jar. It’s where the flour <em>actually sits</em>.</li><li>An <strong>Identifier</strong> is the <strong>name</strong> or <strong>label</strong> you put on that container. It’s how you refer to the variable in your code. In our analogy, it’s the “Flour” label on the jar.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rM4-kw-vHVnGrm-fK6Pkpw.png" /></figure><p>So, when you write age = 30:</p><ul><li>30 is the <strong>value</strong> being stored.</li><li>The memory location holding 30 is the <strong>variable</strong>.</li><li>age is the <strong>identifier</strong> (the name) you use to access that memory location and its value.</li></ul><p>The identifier is how <em>you</em> and Python’s interpreter can find and work with the data stored in the variable. Without a meaningful identifier, your variables would be lost in your program’s memory, like unlabeled jars in a dark pantry!</p><pre># Code without a clear glossary (hard to understand!)<br>x = 1000000000<br>y = 0.05<br>z = x * y<br>print(z)<br><br># Code with a clear glossary (easy to understand!)<br>annual_salary = 1000000000<br>tax_rate = 0.05<br>calculated_tax = annual_salary * tax_rate<br>print(calculated_tax)</pre><h4>The Rules of the Road: Naming Identifiers — Python’s Secret Handshake</h4><p>Just like any exclusive club, Python has a ‘secret handshake’ for naming its identifiers. These aren’t just arbitrary rules; they’re specific patterns Python expects to recognize your variable names. If you don’t use the correct handshake, Python won’t understand what you’re trying to do, leading to frustrating errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*5-k1g-gA3SZlj56D_X2E9w.png" /></figure><p>Here’s how to perform Python’s variable naming handshake correctly:</p><ol><li><strong>Must Start with a Letter or Underscore:</strong> Your identifier <em>must</em> begin with an English letter (A-Z, a-z) or an underscore (_). You can&#39;t start with a number!</li><li><em>Why?</em> If you started with a number (like 1st_place), Python might confuse it with an actual numeric value.</li><li><strong>Can Only Contain Alphanumeric Characters and Underscores:</strong> After the first character, you can use any letter, number (0–9), or underscore (_).</li><li><em>Why?</em> Special symbols like hyphens (-), spaces ( ), or exclamation marks (!) have different meanings in Python and would break the &#39;handshake&#39;.</li><li><strong>Case-Sensitive:</strong> Python cares about capitalization! myVar is completely different from myvar.</li><li><em>Why?</em> This gives you more flexibility, but it demands consistency. Treat Name, name, and NAME as three entirely separate entities.</li><li><strong>Cannot Be a Python Keyword:</strong> Certain words are reserved by Python for its own special commands (like if, else, while, for, print, def, class). You cannot use these as your own variable names.</li><li><em>Why?</em> Using a keyword would confuse the Python interpreter, as it already has a predefined meaning for that word.</li></ol><p>Let’s look at some examples of valid and invalid handshakes:</p><pre># Valid Identifiers (Python recognizes these handshakes!)<br>my_first_variable = 100<br>_internal_value = &quot;confidential&quot;<br>userAge2 = 25<br>total_score_today = 95.5<br><br># Invalid Identifiers (These handshakes will cause errors!)<br># 1st_place = &quot;Gold&quot;    # Error: Cannot start with a digit<br># my-score = 80         # Error: Hyphens are not allowed (they mean subtraction!)<br># class = &quot;Python&quot;      # Error: &#39;class&#39; is a reserved Python keyword<br># customer name = &quot;Bob&quot; # Error: Spaces are not allowed</pre><h4>Best Practices: Writing Pythonic Variable Names — The Art of Clear Conversation</h4><p>While the ‘Rules of the Road’ tell you what you <em>can’t</em> do, <strong>PEP 8</strong> (Python Enhancement Proposal 8) is Python’s style guide that tells you what you <em>should</em> do. Following PEP 8 isn’t just about avoiding errors; it’s about mastering the <strong>art of clear conversation</strong> in your code, making it incredibly readable and easy to understand for anyone who encounters it.</p><p>Think of it as learning the standard ‘accent’ and etiquette of Python’s code conversation.</p><p><strong>Embrace </strong><strong>snake_case:</strong> This is the universal Python accent for variable and function names. All lowercase letters, with words separated by underscores. It&#39;s clean, readable, and widely adopted.</p><pre># Good Pythonic example (clear conversation)<br>first_name = &quot;Jane&quot;<br>total_items_in_cart = 5</pre><p><strong>Be Descriptive, Not Cryptic:</strong> Your variable names should tell a story. Avoid single-letter names unless they’re common loop counters (i, j) or very temporary.</p><pre># Avoid this (mumbling)<br>x = 10<br>a = &quot;data&quot;<br><br># Prefer this (clear communication)<br>student_count = 10<br>raw_user_input = &quot;some data&quot;<br></pre><h4>Variable Reassignment: The Dynamic Label — Jars That Can Hold Anything</h4><p>Here’s where Python variables truly show their flexibility. Unlike some other languages where a jar labeled ‘Flour’ can <em>only ever</em> hold flour, Python’s variables are like <strong>dynamic labels</strong> on jars that can hold anything you put into them, and their contents can change!</p><p>This means you can assign a value to a variable, and later, you can replace that value with something entirely different — even a different <em>type</em> of data. Python automatically handles the ‘re-labeling’ for you.</p><pre># Our &#39;score&#39; jar starts with a number<br>score = 100<br>print(f&quot;Initial score: {score}&quot;) # Output: Initial score: 100<br><br># Now, we put a new number in the &#39;score&#39; jar<br>score = 150<br>print(f&quot;Updated score: {score}&quot;) # Output: Updated score: 150<br><br># The magic of dynamic typing: we can even put text into the &#39;score&#39; jar!<br>score = &quot;Game Over!&quot;<br>print(f&quot;Final message: {score}&quot;) # Output: Final message: Game Over!</pre><p>This ability to reassign values dynamically makes Python incredibly versatile. Your programs aren’t rigid; they can adapt and change the data they’re working with as they execute, making them powerful tools for handling real-world scenarios where data is constantly in flux.</p><h4><strong>Conclusion: Mastering Your Code’s Memory</strong></h4><p>Variables and identifiers are far more than just technical terms; they are the fundamental building blocks that give your Python code memory and clarity. By understanding how to effectively use these ‘labeled jars’ and giving them ‘meaningful names’ through Python’s ‘secret handshake’ and ‘clear conversation’ best practices, you’re not just writing code that works — you’re writing code that <em>speaks</em> and is a pleasure to maintain.</p><p>We hope this deep dive has empowered you with a clearer understanding. Now, it’s your turn to experiment! Open your Python environment, create some variables, give them descriptive names, and practice reassigning values. The more you practice, the more intuitive these core concepts will become.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b52a9515a5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>