<?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 Niharikaponnam on Medium]]></title>
        <description><![CDATA[Stories by Niharikaponnam on Medium]]></description>
        <link>https://medium.com/@niharikaponnam80?source=rss-fcbbf1a0596d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*wUpuQs002thnqTPJ</url>
            <title>Stories by Niharikaponnam on Medium</title>
            <link>https://medium.com/@niharikaponnam80?source=rss-fcbbf1a0596d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:10:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@niharikaponnam80/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[Classification Metrics vs Regression Metrics: How to Know Whether a Machine Learning Model Is…]]></title>
            <link>https://medium.com/@niharikaponnam80/classification-metrics-vs-regression-metrics-how-to-know-whether-a-machine-learning-model-is-b2dca37b71b5?source=rss-fcbbf1a0596d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2dca37b71b5</guid>
            <dc:creator><![CDATA[Niharikaponnam]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 08:02:41 GMT</pubDate>
            <atom:updated>2026-11-20T08:02:41.090Z</atom:updated>
            <content:encoded><![CDATA[<h3>Classification Metrics vs Regression Metrics: How to Know Whether a Machine Learning Model Is Really Good?</h3><p>A machine learning model can make thousands of predictions, but how can its performance be measured? A prediction may look reasonable and still be wrong in a way that matters.</p><p>Consider a food-processing factory that uses a model to identify contaminated food packages before they reach stores. Another model predicts how many hours a batch of fruit can remain in cold storage before its quality begins to decline.</p><p>The first model predicts a <strong>category</strong>: Contaminated or Safe. The second predicts a <strong>numerical value</strong>: Hours of storage.</p><p>Both models need evaluation, but the metrics used to measure their performance are different.</p><p>This is where classification metrics and regression metrics become important. They help measure model performance, identify weaknesses, compare different models, and determine whether a model is suitable for its real-world purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JmBLTZi71-o3IiadB8n3bA.png" /></figure><h4>Two Types of Predictions, Two Ways to Measure Performance</h4><p>Before exploring evaluation metrics, it is important to understand the difference between classification and regression.</p><h4>Classification: Predicting a Category</h4><p>Classification is used when a model predicts a class or label.</p><p>Real-world examples include:</p><ul><li>Identifying whether a food package is contaminated or safe.</li><li>Predicting whether a manufactured component will pass or fail inspection.</li><li>Classifying a fruit as unripe, ripe, or overripe.</li><li>Identifying whether a bank transaction is legitimate or suspicious.</li></ul><p>The output belongs to a category rather than representing a continuous numerical quantity.</p><h4>Regression: Predicting a Numerical Value</h4><p>Regression is used when a model predicts a numerical quantity.</p><p>Real-world examples include:</p><ul><li>Predicting the remaining shelf life of fresh produce.</li><li>Estimating the amount of electricity a cold-storage facility will consume.</li><li>Predicting how many liters of water a greenhouse will require.</li><li>Estimating the time required to repair a damaged industrial machine.</li></ul><p>The output is a number, and the difference between the predicted value and the actual value becomes important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*alTS5lEwTr3B0jc7TR5cCQ.png" /></figure><h4>Part 1: Classification Metrics<strong> — Key Measures of Model Performance</strong></h4><h4>1. The Confusion Matrix: The Foundation of Classification Metrics</h4><p>Classification metrics become much easier to understand when they are derived from a confusion matrix rather than memorized as separate formulas.</p><p>Consider a food-processing factory that uses a machine learning model to identify contaminated food packages. A test containing 100 packages is evaluated, and each prediction is compared with the result of a laboratory inspection.</p><p>For this example:</p><ul><li><strong>Positive:</strong> The package is contaminated.</li><li><strong>Negative:</strong> The package is safe.</li></ul><p>The model produces the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xN5RvA9B6uVHCSL_MZK5Fw.png" /></figure><p>The confusion matrix contains four important values.</p><p><strong>True Positive (TP) = 30</strong></p><p>Thirty contaminated packages are correctly identified as contaminated.</p><p><strong>False Negative (FN) = 10</strong></p><p>Ten contaminated packages are incorrectly classified as safe. These are missed contamination cases.</p><p><strong>False Positive (FP) = 10</strong></p><p>Ten safe packages are incorrectly flagged as contaminated. These are false alarms.</p><p><strong>True Negative (TN) = 50</strong></p><p>Fifty safe packages are correctly identified as safe.</p><h4>How can these four values be remembered?</h4><p>The names become easier to understand by separating them into two parts:</p><ul><li><strong>True or False</strong> describes whether the prediction is correct.</li><li><strong>Positive or Negative</strong> describes the class predicted by the model.</li></ul><p>For example, a False Negative means that the model predicted the negative class, even though the package was actually positive.</p><p>These four values form the foundation of several classification metrics: accuracy, precision, recall, F1-score, and specificity.</p><h4>2. Accuracy: How Often Is the Model Correct?</h4><p>Accuracy measures the proportion of all predictions that are correct.</p><p><strong>Formula:</strong></p><p>Accuracy = (TP + TN) / (TP + TN + FP + FN)</p><p>Using the food-inspection example:</p><p>Accuracy = (30 + 50) / 100 = 0.80</p><p><strong>Accuracy = 80%</strong></p><h4>Why does the formula work?</h4><p>True positives and true negatives are both correct predictions. Adding them gives the total number of correct predictions.</p><p>Dividing by the total number of evaluated packages gives the proportion classified correctly.</p><h4>How is accuracy helpful?</h4><p>Accuracy provides a quick overview of overall model performance. It is useful when both classes matter and the class distribution is reasonably balanced.</p><p>However, accuracy can be misleading when one class is much more common than the other.</p><p>Imagine that only 2 out of 100 packages are contaminated. A model that predicts every package as safe achieves 98% accuracy but misses both contaminated packages.</p><p>A high accuracy score does not automatically mean that the model is safe or useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBRG1T7wqhI1wqoPO7oOJA.png" /></figure><h4>3. Precision: How Trustworthy Are Positive Predictions?</h4><p>Imagine that a factory discards every package flagged as contaminated. False alarms can cause safe products to be wasted and increase inspection costs.</p><p>Precision measures how many positive predictions are actually positive.</p><p><strong>Formula:</strong></p><p>Precision = TP / (TP + FP)</p><p>Using the example:</p><p>Precision = 30 / (30 + 10) = 0.75</p><p><strong>Precision = 75%</strong></p><h4>Why does the formula work?</h4><p>The model flagged 40 packages as contaminated. Only 30 were genuinely contaminated, while 10 were safe.</p><p>Precision divides the correctly identified contaminated packages by all packages predicted as contaminated.</p><h4>How is precision helpful?</h4><p>Precision is important when false positives are costly.</p><p>For example, a manufacturing inspection system should avoid rejecting large numbers of acceptable components unnecessarily. High precision means that a large proportion of the components flagged as defective are genuinely defective.</p><p><strong>Easy way to remember:</strong> Precision asks, “Out of everything predicted as positive, how much was actually positive?”</p><p>The denominator contains TP and FP because both are positive predictions made by the model.</p><h4>4. Recall: How Many Actual Positive Cases Were Found?</h4><p>Precision focuses on positive predictions. Recall focuses on actual positive cases.</p><p>In the food-processing factory, missing contaminated packages could allow unsafe products to reach consumers. Therefore, detecting as many genuinely contaminated packages as possible is important.</p><p><strong>Formula:</strong></p><p>Recall = TP / (TP + FN)</p><p>Using the example:</p><p>Recall = 30 / (30 + 10) = 0.75</p><p><strong>Recall = 75%</strong></p><h4>Why does the formula work?</h4><p>Laboratory inspection identified 40 contaminated packages. The model found 30 and missed 10.</p><p>Recall divides the number of correctly detected contaminated packages by the total number of genuinely contaminated packages.</p><h4>How is recall helpful?</h4><p>Recall is particularly useful when missing a positive case has serious consequences.</p><p>Examples include:</p><ul><li>Detecting contaminated food before distribution.</li><li>Identifying dangerous faults in industrial equipment.</li><li>Screening for potentially serious medical conditions.</li></ul><p><strong>Easy way to remember:</strong> Recall asks, “Out of everything actually positive, how much did the model find?”</p><p>The denominator contains TP and FN because both represent actual positive cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*19dmPCauL4_3vMJfa5S-yw.png" /></figure><p>In the example, precision and recall are both 75%. This is coincidental; the two metrics often have different values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMXEiFhtBVQkRTwVNIEwzw.png" /></figure><h4>5. F1-Score: Balancing Precision and Recall</h4><p>A model can achieve high precision by making very few positive predictions, but this may cause it to miss many actual positive cases.</p><p>Another model may achieve high recall by flagging almost everything as positive, creating many false alarms.</p><p>F1-score combines precision and recall into a single metric.</p><p><strong>Formula:</strong></p><p>F1-score = 2 × (Precision × Recall) / (Precision + Recall)</p><p>Using the example:</p><p>F1-score = 2 × (0.75 × 0.75) / (0.75 + 0.75)</p><p><strong>F1-score = 0.75, or 75%</strong></p><h4>Why use the harmonic mean?</h4><p>The harmonic mean penalizes an imbalance between precision and recall more strongly than a simple arithmetic average.</p><p>For example, if precision is 90% and recall is 30%, the F1-score is 45%.</p><p>The high precision cannot compensate fully for the poor recall.</p><h4>How is F1-score helpful?</h4><p>F1-score is useful when both false alarms and missed positive cases matter, particularly when the dataset contains imbalanced classes.</p><p>However, F1-score does not directly consider true negatives. It should be used alongside other metrics when the quality of negative predictions also matters.</p><p><strong>Easy way to remember:</strong> F1-score combines precision and recall into one balanced measure.</p><h4>6. Specificity: How Well Are Negative Cases Recognized?</h4><p>Precision, recall, and F1-score focus on positive predictions and actual positive cases. Specificity measures performance on actual negative cases.</p><p>In the food-inspection example, specificity measures how effectively the model identifies packages that are genuinely safe.</p><p><strong>Formula:</strong></p><p>Specificity = TN / (TN + FP)</p><p>Using the example:</p><p>Specificity = 50 / (50 + 10) = 0.8333</p><p><strong>Specificity ≈ 83.33%</strong></p><h4>Why does the formula work?</h4><p>There are 60 packages that are actually safe. The model correctly identifies 50 and incorrectly flags 10 as contaminated.</p><p>Specificity divides correctly identified negative cases by all actual negative cases.</p><h4>How is specificity helpful?</h4><p>Specificity is useful when correctly recognizing negative cases is important, such as avoiding unnecessary rejection of safe products or unnecessary follow-up inspections.</p><p><strong>Easy way to remember:</strong> Recall measures how many actual positives were found; specificity measures how many actual negatives were correctly recognized.</p><h4>7. ROC Curve and AUROC: How Does a Model Separate Safe and Contaminated Packages?</h4><p>Imagine a food-inspection model that predicts the probability of a package being contaminated. For example, one package receives a contamination probability of 0.85, while another receives 0.25.</p><p>To convert these probabilities into class labels, the model uses a <strong>classification threshold</strong>. If the threshold is 0.5, a package with a probability of 0.85 is classified as contaminated, while a package with a probability of 0.25 is classified as safe.</p><p><strong>But what happens when the threshold changes? A lower threshold may detect more contaminated packages, but it may also incorrectly flag more safe packages. A higher threshold may reduce false alarms, but it may miss more contaminated packages.</strong></p><p>This is where the ROC curve becomes useful.</p><h4>What are TPR and FPR?</h4><p>At each classification threshold, two important rates are calculated:</p><ul><li><strong>True Positive Rate (TPR):</strong> The proportion of actually contaminated packages correctly identified as contaminated. It is also called Recall or Sensitivity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*y6yzsfCZu9lFVWMmBU2zqw.png" /></figure><ul><li><strong>False Positive Rate (FPR):</strong> The proportion of actually safe packages incorrectly flagged as contaminated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*MoJvQ1GtstpGTsJLOi1E-Q.png" /></figure><p>For example, if 100 packages are actually contaminated and the model correctly identifies 80 of them, the TPR is 80%. If 100 packages are actually safe and the model incorrectly flags 20 of them as contaminated, the FPR is 20%.</p><h4>How is the ROC curve created?</h4><p>The model’s predicted probabilities are tested at multiple thresholds, such as 0.2, 0.4, 0.6, and 0.8. At each threshold, the predicted labels change, so the TPR and FPR may also change.</p><p>These values are plotted on a graph:</p><ul><li><strong>X-axis:</strong> False Positive Rate (FPR)</li><li><strong>Y-axis:</strong> True Positive Rate (TPR)</li></ul><p>The resulting graph is called the <strong>ROC (Receiver Operating Characteristic) curve</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlkVrGSFa32vVNqSuLlvWg.png" /></figure><p>The closer the ROC curve moves toward the <strong>top-left corner</strong>, the better the model generally balances detecting contaminated packages with avoiding false alarms.</p><h4>What is AUROC?</h4><p><strong>AUROC (Area Under the ROC Curve)</strong> measures the area beneath the ROC curve. It summarizes how well the model distinguishes contaminated packages from safe ones across different thresholds.</p><p>A higher AUROC generally indicates better discrimination between the two classes.</p><h4>Understanding AUROC values</h4><p><strong>1. AUROC = 0.50 (50% area)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNcbk67zJ21KlJVJuxS1jw.png" /></figure><p>The model has discrimination equivalent to random ranking. It struggles to rank contaminated packages above safe packages.</p><p><strong>2. AUROC = 0.85 (85% area)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQdSZRYAcBEe9ktzJDCf9g.png" /></figure><p>The model generally distinguishes contaminated packages from safe ones well. It shows good class separation.</p><p><strong>3. AUROC = 0.95–0.98 (95–98% area)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTYxg8jJTtO0KlbnViAkUw.png" /></figure><p>The model shows excellent discrimination, generally ranking contaminated packages above safe packages.</p><p><strong>Important:</strong> These percentages represent the area under the curve, not the percentage of predictions that are correct. For example, an AUROC of 0.85 does not mean that 85% of all packages are classified correctly.</p><h4>How is AUROC helpful, and what are its limitations?</h4><p>AUROC helps compare classification models across different thresholds. In food inspection, it helps evaluate how effectively a model separates contaminated packages from safe ones without committing to just one threshold.</p><p>However, AUROC has a limitation: it can be less informative when the dataset is highly imbalanced, such as when only a tiny proportion of food packages are contaminated. A model may appear to discriminate well overall while still producing too many false alarms or failing to identify enough contaminated packages at the chosen threshold.</p><p>In such cases, a <strong>Precision–Recall curve</strong> can be more informative because it focuses on precision and recall for the positive class. It helps evaluate how well the model detects rare contaminated packages while controlling false alarms.</p><h4>8. Log Loss: How Good Are the Predicted Probabilities?</h4><p>The ROC curve and AUROC evaluate how well a model separates two classes across different thresholds. But they do not tell the whole story about the quality of its predicted probabilities.</p><p>Imagine that a food-inspection model predicts the probability of contamination for two packages. Both packages are actually contaminated:</p><ul><li><strong>Package A:</strong> Predicted probability of contamination = 0.95.</li><li><strong>Package B:</strong> Predicted probability of contamination = 0.10.</li></ul><p>Package A receives a high probability of contamination, which matches the actual outcome. Package B receives a low probability even though it is contaminated.</p><p>Log Loss penalizes incorrect probabilities, especially when the model is confidently wrong. Package A receives a low loss, while Package B receives a high loss.</p><h4>Log Loss formula</h4><p>For binary classification:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*WuKMEe6eZ5Bu8gQG7gbDDA.png" /></figure><p>Here:</p><ul><li>N = number of packages evaluated.</li><li><em>yi</em> = actual label (1 for contaminated, 0 for safe).</li><li><em>pi</em> = predicted probability that the package is contaminated.</li></ul><h4>How is Log Loss helpful?</h4><p>Log Loss evaluates the quality of predicted probabilities rather than only checking whether the final class label is correct.</p><p>For example, two models might classify the same package as contaminated, but one predicts a probability of 0.55 while the other predicts 0.99. If the package is actually safe, the second model receives a much larger penalty because it was more confidently wrong.</p><p><strong>Remember:</strong> Lower Log Loss is better. A confident correct prediction receives a small loss, while a confident incorrect prediction receives a large loss.</p><p>Log Loss is useful when the reliability of predicted probabilities matters, such as deciding which food packages should receive urgent manual inspection.</p><h4>Part 2: Regression Metrics — Measuring the Distance Between Prediction and Reality</h4><h4>A Cold-Storage Example: How Far Off Are the Predictions?</h4><p>A cold-storage facility stores fresh fruit and uses a regression model to predict how many hours a batch can remain in storage before its quality begins to decline.</p><p>The predicted storage times are compared with the actual observed times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*cEzkVAg5ePHIYtSuc8eQPg.png" /></figure><p>The error for each prediction is calculated as:</p><p>Error = Actual value − Predicted value</p><p>For Batch A, the error is 10 − 12 = −2 hours. The model predicted two hours more than the actual observed time.</p><p>For Batch C, the error is 20 − 16 = +4 hours. The model predicted four hours less than the actual observed time.</p><p>Regression metrics use these differences to evaluate prediction performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3JFMVYCMhIFAEsL43a-cw.png" /></figure><h4>9. MAE: Mean Absolute Error</h4><p>Mean Absolute Error (MAE) measures the average size of the prediction errors without considering whether the model predicted too high or too low.</p><p><strong>Formula:</strong></p><p>MAE = Sum of absolute errors / Number of predictions</p><p>Or:</p><p>MAE = (1/n) × Σᵢ₌₁ⁿ |yᵢ − ŷᵢ|</p><p>Here, yᵢ represents the actual value and ŷᵢ represents the predicted value.</p><p>For the five batches, the absolute errors are:</p><p>2, 2, 4, 2, 2 hours.</p><p>MAE = (2 + 2 + 4 + 2 + 2) / 5</p><p><strong>MAE = 2.4 hours</strong></p><h4>Why use absolute values?</h4><p>Positive and negative errors can cancel each other out if they are averaged directly. Absolute values remove the signs, ensuring that every error contributes to the result.</p><h4>How is MAE helpful?</h4><p>MAE is easy to interpret because it uses the same unit as the predicted quantity.</p><p>In this example, the average absolute prediction error is 2.4 hours. The result gives the facility a straightforward measure of how far predictions tend to be from observed values.</p><p><strong>Easy way to remember:</strong> MAE = Absolute errors → Average.</p><h4>10. MSE: Mean Squared Error</h4><p>Mean Squared Error (MSE) measures the average of the squared prediction errors.</p><p><strong>Formula:</strong></p><p>MSE = (1/n) × Σᵢ₌₁ⁿ (yᵢ − ŷᵢ)²</p><p>Using the example:</p><p>MSE = (2² + 2² + 4² + 2² + 2²) /5</p><p>MSE = (4 + 4 + 16 + 4 + 4) / 5</p><p><strong>MSE = 6.4 hours²</strong></p><h4>Why square the errors?</h4><p>Squaring has two important effects:</p><ol><li>Negative errors become positive, preventing cancellation.</li><li>Larger errors receive a disproportionately greater penalty.</li></ol><p>An error of 4 contributes 16 to the squared-error total, whereas an error of 2 contributes only 4.</p><h4>How is MSE helpful?</h4><p>MSE is useful when large prediction errors should have a stronger influence on evaluation or model training.</p><p>Its main limitation is interpretability: the unit is squared, making hours² less intuitive than hours.</p><p><strong>Easy way to remember:</strong> MSE = Square errors → Average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uSvOrR6Elow3ewWGWuiZw.png" /></figure><h4>11. RMSE: Mean Squared Error in the Original Unit</h4><p>Root Mean Squared Error (RMSE) addresses the squared-unit limitation of MSE by taking its square root.</p><p><strong>Formula:</strong></p><p>RMSE = √[ (1/n) × Σᵢ₌₁ⁿ (yᵢ − ŷᵢ)² ]</p><p>Using the example:</p><p>RMSE = √6.4</p><p><strong>RMSE ≈ 2.53 hours</strong></p><h4>Why take the square root?</h4><p>The square root converts the squared error measure back into the original unit. At the same time, the squaring step continues to give larger errors more influence.</p><h4>How is RMSE helpful?</h4><p>RMSE is useful when a model needs to be evaluated in the same units as the target variable while remaining sensitive to large prediction errors.</p><p>In the cold-storage example, RMSE is approximately 2.53 hours, compared with MAE of 2.4 hours.</p><p>RMSE is not always greater than MAE by a large amount, but mathematically it is at least as large as MAE when both are calculated over the same observations.</p><p><strong>Easy way to remember:</strong> RMSE = Square errors → Average → Square root.</p><h4>MAE vs. MSE vs. RMSE: Which One Should Be Used?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*YqCEOJgffJs8BkARfXuVqA.png" /></figure><p>MAE is usually easier to explain to non-technical stakeholders. MSE gives larger errors greater influence and is commonly used as a training objective. RMSE combines the large-error penalty with an interpretable unit.</p><p>The choice depends on the consequences of prediction errors in the particular application.</p><h4>12. R² Score: Is the Model Better Than a Simple Baseline?</h4><p>Low prediction errors are useful, but another question matters: how well does the model perform compared with a simple approach that predicts the mean of the actual values for every observation?</p><p>The coefficient of determination, called the <strong>R² score</strong>, measures model performance relative to this baseline.</p><p><strong>Formula:</strong></p><p>R² = 1 − (SS_res / SS_tot)</p><p>Where:</p><ul><li><strong>SS_res:</strong> Sum of squared differences between actual and predicted values.</li><li><strong>SS_tot:</strong> Sum of squared differences between actual values and their mean.</li></ul><p>For the cold-storage example, the actual values are 10, 15, 20, 25, and 30 hours.</p><p>Their mean is 20 hours.</p><p>The model’s sum of squared errors is:</p><p>SS_res = 4 + 4 + 16 + 4 + 4 = 32</p><p>The total variation around the mean is:</p><p>SS_tot = (10 − 20)² + (15 − 20)² + (20 − 20)² + (25 − 20)² + (30 − 20)²</p><p>SS_tot = 100 + 25 + 0 + 25 + 100 = 250</p><p>Therefore:</p><p>R² = 1 − (32 / 250)</p><p><strong>R² = 0.872, or 87.2%</strong></p><h4>What does this result mean?</h4><p>For this test dataset, the model’s squared prediction error is 87.2% lower than the squared error of the baseline that predicts the actual mean for every batch.</p><p>It does <strong>not</strong> mean that 87.2% of individual predictions are correct. R² is not a measure of prediction accuracy in the classification sense.</p><p>R² can be negative when a model performs worse than the mean-prediction baseline on the evaluation data.</p><h4>How is R² helpful?</h4><p>R² provides a useful comparison of regression performance relative to a simple baseline. It can help compare models evaluated on the same target and dataset.</p><p>However, R² does not reveal the typical prediction error in hours. For practical interpretation, it is often useful to report R² alongside MAE or RMSE.</p><p><strong>Easy way to remember:</strong> R² = 1 − (Model’s squared error / Total variation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmrE4B52IfyPNfedOIRNxA.png" /></figure><h4>13. Adjusted R²: Does Adding More Features Actually Improve the Model?</h4><p>Imagine a cold-storage company predicting how many hours fruit will remain fresh. The model uses features such as storage temperature and humidity.</p><p>Later, extra features are added, such as sensor ID and package number. These features may not meaningfully improve the predictions.</p><p>Ordinary R² can stay the same or increase when more predictors are added, even if those predictors contribute little useful information. <strong>Adjusted R² accounts for both model fit and the number of predictors</strong>, helping identify whether adding more features genuinely improves the model.</p><p><strong>Formula:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*SOYpT_JuN10Y6M7LEcZ0_g.png" /></figure><p>Where:</p><ul><li>R² = coefficient of determination.</li><li>n = number of observations, such as fruit samples.</li><li>p = number of predictors used by the model.</li></ul><p><strong>How is it helpful?</strong></p><p>Adjusted R² is useful when comparing regression models that use different numbers of predictors. It can decrease when an added predictor does not improve the model enough to justify its inclusion.</p><p><strong>Limitation:</strong> Adjusted R² does not prove that a model predicts accurately on new data. It should be considered alongside error metrics such as MAE and RMSE, and ideally evaluated using unseen data.</p><h4>Conclusion: Choosing the Right Metric Matters</h4><p>Model evaluation is not just about calculating scores; it is about understanding what those scores reveal about a model’s performance.</p><p>In food inspection, accuracy alone may not be enough. Precision helps understand false alarms, recall reveals how many contaminated packages are detected, and the F1-score balances precision and recall. ROC-AUC evaluates how well the model separates contaminated packages from safe ones, while Log Loss measures the quality of predicted probabilities.</p><p>For regression, MAE and RMSE express prediction errors in the target’s units, MSE penalizes larger errors more heavily, and R² and Adjusted R² help assess model fit while accounting for the number of predictors.</p><p><strong>The key takeaway:</strong> No single metric tells the complete story. The right evaluation approach depends on the problem, the cost of mistakes, and the purpose of the model. A good model is not simply one with a high score; it is one that performs reliably where it matters most.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2dca37b71b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression vs Logistic Regression in Machine Learning: One Predicts Numbers, the Other…]]></title>
            <link>https://medium.com/@niharikaponnam80/linear-regression-vs-logistic-regression-in-machine-learning-one-predicts-numbers-the-other-2e69df0ff65e?source=rss-fcbbf1a0596d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e69df0ff65e</guid>
            <dc:creator><![CDATA[Niharikaponnam]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 16:41:17 GMT</pubDate>
            <atom:updated>2026-11-14T16:41:17.888Z</atom:updated>
            <content:encoded><![CDATA[<h3>Linear Regression vs Logistic Regression in Machine Learning: One Predicts Numbers, the Other Predicts Possibilities</h3><p><em>One predicts numbers. The other predicts possibilities. But what connects these two algorithms, and why is Logistic Regression called regression when it is used for classification?</em></p><p>Imagine a music learning platform where thousands of learners enrol to learn musical instruments such as guitar, piano, and drums.</p><p>As learners use the platform, it collects different types of information, such as their practice hours, completed lessons, previous assessment scores, and learning progress.</p><p>Now, the platform wants to solve two different problems:</p><ol><li><strong>Predict the final assessment score:</strong> Based on a learner’s practice hours and completed lessons, how many marks might they score?</li><li><strong>Predict course completion:</strong> Based on the learner’s activity and progress, will they complete their chosen instrument course or not?</li></ol><p>Although both problems use the same learner information, they require different types of predictions.</p><p>One requires a numerical output, while the other requires a category.</p><p>This is where two important supervised Machine Learning algorithms come into the picture: <strong>Linear Regression and Logistic Regression.</strong></p><p>Both algorithms are based on mathematical relationships between input features and an output. However, they use different approaches to make predictions.</p><p>Let’s understand how they work, their mathematical foundations, assumptions, differences, and real-world applications.</p><h3>1. What is Linear Regression?</h3><p>Linear Regression is a supervised Machine Learning algorithm used to predict a continuous numerical value based on one or more input features.</p><p>It identifies the relationship between independent variables (input features) and a dependent variable (target variable).</p><p><strong>Let’s understand with our music learning platform.</strong></p><p>Suppose the platform wants to predict the final assessment score of a learner based on the number of hours they practise.</p><p>It has historical data like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*UVfqzaTHXlJ-zirZ5aIZWw.png" /></figure><p>We can observe that as practice hours increase, assessment scores generally increase.</p><p>Linear Regression learns this relationship from the historical data and fits a straight line that represents the relationship between practice hours and assessment scores.</p><p>Once the model learns this relationship, it can predict the assessment score of a new learner.</p><p>For example, if a learner practises for 5 hours, the model estimates their expected assessment score based on the learned relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DCNpP5BLolaMyhpkrKO3g.png" /></figure><h4>1.1 How Does Linear Regression Work?</h4><p>Linear Regression follows a process to identify the best relationship between input features and the target variable.</p><ol><li><strong>Collect the dataset:</strong> Gather historical learner information containing input features and their corresponding assessment scores.</li><li><strong>Identify the variables:</strong> Select the independent variables, such as practice hours and completed lessons, and the dependent variable, which is the assessment score.</li><li><strong>Fit the best-fit line:</strong> Find the line that minimizes the squared differences between actual and predicted values.</li><li><strong>Learn the coefficients:</strong> Estimate the slope and intercept that best represent the relationship in the training data.</li><li><strong>Make predictions:</strong> Use the learned equation to predict assessment scores for new learners.</li></ol><h4>1.2 Mathematical Equation of Linear Regression</h4><p>For Simple Linear Regression, the mathematical equation is:</p><p>ŷ = b₀ + b₁x</p><p>Where:</p><ul><li><strong>ŷ (Predicted value):</strong> The assessment score predicted by the model.</li><li><strong>b₀ (Intercept):</strong> The predicted score when the practice hours are zero.</li><li><strong>b₁ (Coefficient or slope):</strong> The expected change in the predicted score for every one-unit increase in practice hours.</li><li><strong>x (Independent variable):</strong> The number of practice hours.</li></ul><p>For example, suppose the model learns the following equation:</p><p>ŷ=25+6x</p><p>If a learner practises for 5 hours:</p><p>ŷ=25+6(5)</p><p>ŷ=55</p><p>The model predicts that the learner will score 55 marks.</p><p><strong>But what if the platform wants to consider more than one factor?</strong></p><p>For example, practice hours, lessons completed, and previous assessment scores may all influence the final score.</p><p>In that case, we use Multiple Linear Regression.</p><h4>1.3 Types of Linear Regression</h4><p><strong>1. Simple Linear Regression</strong></p><ul><li>Uses one independent variable to predict one dependent variable.</li><li>Example: Predicting a learner’s assessment score using practice hours.</li></ul><p><strong>2. Multiple Linear Regression</strong></p><ul><li>Uses two or more independent variables to predict one dependent variable.</li><li>Example: Predicting a learner’s assessment score using practice hours, lessons completed, and previous assessment scores.</li></ul><p>The general equation for Multiple Linear Regression is:</p><p>ŷ = b₀ + b₁x₁ + b₂x₂ + ⋯ + bₙxₙ</p><p>Here, each input feature has its own coefficient, representing its contribution to the predicted output while keeping the other features constant.</p><h4>1.4 How Does Linear Regression Find the Best-Fit Line?</h4><p>Linear Regression commonly uses a statistical method called <strong>Ordinary Least Squares (OLS)</strong> to estimate the coefficients.</p><p>To understand this, let’s consider two values:</p><ul><li>Actual value: The assessment score the learner really achieved.</li><li>Predicted value: The assessment score estimated by the model.</li></ul><p>The difference between these two values is called a <strong>residual</strong>.</p><p>Residual = Actual Value — Predicted Value</p><p>The model tries to find a line that minimizes the sum of squared residuals.</p><p>This is called the <strong>Sum of Squared Errors (SSE)</strong>.</p><p>SSE = Σ (yᵢ − ŷᵢ)², for i = 1 to n</p><p>Why do we square the errors?</p><ol><li>Removes negative signs: Both positive and negative errors become positive.</li><li>Penalizes larger errors: An error of 10 produces 100, whereas an error of 2 produces only 4.</li><li>Makes optimization mathematically convenient: Squared error is differentiable and allows us to find the best-fit line using mathematical optimization techniques.</li></ol><p>Therefore, Linear Regression selects the coefficients that minimize the total squared prediction errors.</p><p><strong>We square the errors so that positive and negative errors don’t cancel each other out, and larger prediction mistakes receive greater penalties.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9vUsMtmNjHrAHWws5-jNA.png" /></figure><h4>1.5 Cost Function and Optimization</h4><p>A cost function measures how far the model’s predictions are from the actual values.</p><p>For Linear Regression, a commonly used cost function is Mean Squared Error (MSE).</p><p>MSE = (1/n) Σ (yᵢ − ŷᵢ)², for i = 1 to n</p><p>The objective is to minimize this error by finding suitable values for the coefficients.</p><p>Another method used to minimize the cost function is <strong>Gradient Descent</strong>.</p><p>Gradient Descent is an optimization algorithm that updates the model’s coefficients step by step to reduce the prediction error.</p><p>It works by calculating the direction in which the cost function decreases and updating the coefficients using a learning rate.</p><p><strong>Important:</strong> Ordinary Least Squares can obtain a closed-form solution for Linear Regression, while Gradient Descent is an alternative optimization approach, particularly useful for larger datasets.</p><h4>1.6 Assumptions of Linear Regression</h4><p>Linear Regression relies on certain assumptions to produce reliable estimates and predictions.</p><p>Understanding these assumptions is important because violating them can affect model performance and the reliability of statistical conclusions.</p><p><strong>1. Linearity</strong></p><p>There should be a linear relationship between the independent variables and the expected value of the dependent variable.</p><p>For example, the relationship between practice hours and assessment scores should be reasonably represented by a straight-line relationship.</p><p>If the actual relationship is strongly curved, a simple linear model may not represent it properly.</p><p><strong>2. Independence of Errors</strong></p><p>The residuals (prediction errors) should be independent of one another.</p><p>In simple terms, the error for one learner should not depend on the error for another learner.</p><p>This is particularly important when working with time-dependent or repeated observations.</p><p><strong>3. Homoscedasticity</strong></p><p>The variance of residuals should remain approximately constant across different predicted values or levels of the input features.</p><p>In simple words, the spread of prediction errors should not increase or decrease systematically as predicted scores change.</p><p>If the spread changes significantly, it is called heteroscedasticity.</p><p><strong>4. Normality of Residuals</strong></p><p>The residuals should be approximately normally distributed.</p><p>This assumption is mainly important when performing statistical inference, such as hypothesis testing and calculating confidence intervals.</p><p>It is not a strict requirement for obtaining predictions using OLS.</p><p><strong>5. No Perfect Multicollinearity</strong></p><p>Independent variables should not have a perfect linear relationship with one another.</p><p>For example, if two input features contain exactly the same information, the model cannot reliably estimate their individual coefficients.</p><p>High multicollinearity can also make coefficient estimates unstable.</p><p><strong>6. Zero Conditional Mean of Errors</strong></p><p>The expected error should be zero for every combination of input features.</p><p>In simple terms, the model’s errors should not systematically overestimate or underestimate the target variable.</p><p>This assumption is important for obtaining unbiased coefficient estimates.</p><h4>1.7 Advantages of Linear Regression</h4><ul><li>Simple to understand and implement.</li><li>Easy to interpret the relationship between input features and the target.</li><li>Computationally efficient.</li><li>Provides a useful baseline for regression problems.</li><li>Works well when the relationship is approximately linear.</li></ul><h4>1.8 Limitations of Linear Regression</h4><ul><li>Cannot naturally capture complex nonlinear relationships without additional feature transformations.</li><li>Sensitive to outliers because squared errors give large errors more weight.</li><li>Multicollinearity can make coefficient estimates unstable.</li><li>Performance can be affected when important assumptions are violated.</li><li>May produce unrealistic predictions outside the range of the training data.</li></ul><h3>2. What is Logistic Regression?</h3><p>Logistic Regression is a supervised Machine Learning algorithm primarily used for classification problems.</p><p>Unlike Linear Regression, which predicts continuous numerical values, Logistic Regression estimates the probability that an observation belongs to a particular class.</p><p>Let’s return to our music learning platform.</p><p>This time, the platform wants to predict whether a learner will complete their chosen instrument course or not.</p><p>It uses information such as:</p><ul><li>Number of practice hours.</li><li>Number of lessons completed.</li><li>Learning progress.</li><li>Previous assessment scores.</li></ul><p>Based on these features, Logistic Regression estimates the probability of course completion.</p><p>For example:</p><ul><li>Learner A: 90% probability of completing the course.</li><li>Learner B: 25% probability of completing the course.</li></ul><p>The model does not directly predict the final category. It first calculates a probability and then uses a decision threshold to assign a class.</p><p>For example, if the threshold is 0.5:</p><ul><li>Probability ≥ 0.5 → Complete the course (Class 1).</li><li>Probability &lt; 0.5 → Not complete the course (Class 0).</li></ul><p>Therefore, Logistic Regression helps the platform classify learners into two categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_f7XI_eRrMkYcBTzD8jndw.png" /></figure><h4>2.1 How Does Logistic Regression Work?</h4><p>Logistic Regression follows these steps:</p><ol><li><strong>Collect the dataset:</strong> Gather historical learner information along with their course completion status.</li><li><strong>Identify the variables:</strong> Select independent variables such as practice hours and lessons completed, and the dependent variable representing course completion.</li><li><strong>Calculate a linear combination:</strong> Combine input features using their corresponding coefficients and an intercept.</li><li><strong>Apply the Sigmoid Function:</strong> Convert the calculated value into a probability between 0 and 1.</li><li><strong>Apply a decision threshold:</strong> Compare the predicted probability with a selected threshold.</li><li><strong>Make a classification:</strong> Assign the learner to the appropriate class.</li></ol><h4>2.2 Mathematical Equation of Logistic Regression</h4><p>Logistic Regression first calculates a linear combination of input features.</p><p>z = b₀ + b₁x₁ + b₂x₂ + ⋯ + bₙxₙ</p><p>Where:</p><ul><li><strong>z:</strong> Linear combination of input features.</li><li><strong>b₀:</strong> Intercept or bias.</li><li><strong>b₁, b₂, …, bₙ:</strong> Model coefficients.</li><li><strong>x₁, x₂, …, xₙ:</strong> Independent variables.</li></ul><p>However, this linear equation can produce any real-valued output, including negative values and values greater than 1.</p><p>Since we need a probability between 0 and 1, we apply a function called the <strong>Sigmoid Function</strong>.</p><h4>2.3 What is the Sigmoid Function?</h4><p>The Sigmoid Function converts any real-valued input into a value between 0 and 1.</p><p>Its mathematical equation is:</p><p>P(y = 1) = 1 / (1 + e⁻ᶻ)</p><p>Where:</p><ul><li><strong>P(y = 1):</strong> Probability of belonging to Class 1.</li><li><strong>e:</strong> Euler’s mathematical constant (approximately 2.718).</li><li><strong>z:</strong> Linear combination of input features.</li></ul><p>For example, suppose the model predicts a probability of 0.85.</p><p>This means the learner has an estimated 85% probability of completing the course.</p><p>If the threshold is 0.5, the learner is classified as Class 1 (Complete).</p><p><strong>Why is the Sigmoid Function important?</strong></p><p>It ensures that the model’s output can be interpreted as a probability, making it suitable for binary classification.</p><p><strong>Note:</strong> The Sigmoid Function is used in Binary Logistic Regression. Multinomial Logistic Regression commonly uses the Softmax Function to calculate probabilities across multiple classes.</p><h4>2.4 Understanding the Decision Threshold</h4><p>A decision threshold is the probability cutoff used to convert predicted probabilities into class labels.</p><p>The default threshold in many binary classification implementations is 0.5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*PC64z06l34JDCxLNFrg-YQ.png" /></figure><p>However, the threshold does not always have to be 0.5.</p><p>It can be adjusted depending on the problem and the importance of false positives and false negatives.</p><p>For example, if the music platform wants to identify more learners who might not complete their courses, it can define Not Complete as the positive class (Class 1) and Complete as the negative class (Class 0). It can then lower the decision threshold to identify more potentially at-risk learners.</p><p>This may increase recall for the Not Complete class, although it can also increase false positives.</p><h4>2.5 Why Is Logistic Regression Called Regression If It Is Used for Classification?</h4><p>This is one of the most interesting questions about Logistic Regression.</p><p>The name can be confusing because Logistic Regression is primarily used for classification, not for predicting continuous numerical values.</p><p>The reason behind its name comes from the mathematical relationship between input features and <strong>log-odds</strong>.</p><p>Let’s understand this step by step.</p><p>First, Logistic Regression calculates a linear combination of input features:</p><p>z = b₀ + b₁x₁ + ⋯ + bₙxₙ</p><p>Then, it converts this value into a probability using the Sigmoid Function.</p><p>But the probability can also be expressed in terms of odds.</p><p>Odds = p / (1 − p)</p><p>Here:</p><ul><li><strong>p:</strong> Probability of the positive class.</li><li><strong>1 − p:</strong> Probability of the negative class.</li></ul><p>Taking the natural logarithm of the odds gives us log-odds, also called the logit.</p><p>log(p / (1 − p)) = b₀ + b₁x₁ + ⋯ + bₙxₙ</p><p>This equation shows that Logistic Regression models the log-odds of an outcome as a linear combination of input features.</p><p><strong>In simple words:</strong> Logistic Regression applies a linear regression-like equation to the log-odds of the outcome, rather than directly predicting the output probability.</p><p>That is why it retains the word <strong>Regression</strong> in its name, even though it is used for classification.</p><h4>2.6 Types of Logistic Regression</h4><p>Logistic Regression can be used for different classification problems.</p><p><strong>1. Binary Logistic Regression</strong></p><ul><li>Used when the target variable has two possible classes.</li><li>Example: Predicting whether a learner will complete the course or not.</li></ul><p><strong>2. Multinomial Logistic Regression</strong></p><ul><li>Used when the target variable has more than two unordered classes.</li><li>Example: Predicting which instrument a learner will choose: Guitar, Piano, or Drums.</li></ul><p><strong>3. Ordinal Logistic Regression</strong></p><ul><li>Used when the target variable has more than two categories with a meaningful order.</li><li>Example: Predicting learner satisfaction levels: Low, Medium, or High.</li></ul><h4>2.7 Cost Function in Logistic Regression</h4><p>During model training, Logistic Regression needs to learn suitable coefficients to make accurate predictions.</p><p>Unlike Linear Regression, which commonly uses Mean Squared Error, Logistic Regression generally uses a loss function called <strong>Log Loss (Binary Cross-Entropy)</strong> for binary classification.</p><p>Its mathematical equation is:</p><p>J = −(1/n) Σ [yᵢ log(pᵢ) + (1 − yᵢ) log(1 − pᵢ)], for i = 1 to n</p><p>Where:</p><ul><li><strong>n:</strong> Number of observations.</li><li><strong>yᵢ:</strong> Actual class label (0 or 1).</li><li><strong>pᵢ:</strong> Predicted probability of the positive class.</li></ul><p>Log Loss measures how far the predicted probabilities are from the actual class labels. It uses the negative natural logarithm of the predicted probability assigned to the actual class.</p><p>It penalizes confident incorrect predictions more heavily.</p><p>The objective is to minimize Log Loss so that the model learns coefficients that produce better probability estimates.</p><p>Logistic Regression commonly uses <strong>Maximum Likelihood Estimation (MLE)</strong> to estimate its coefficients.</p><p>Optimization methods such as Gradient Descent or other numerical solvers are used to find the coefficient values that maximize the likelihood (or equivalently minimize the negative log-likelihood).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGD-TIDArpRiK5DbD5IjDQ.png" /></figure><h4>2.8 Assumptions of Logistic Regression</h4><p>Just like Linear Regression, Logistic Regression also relies on certain assumptions.</p><p>However, its assumptions are different because it is designed for classification.</p><p><strong>1. Binary Target Variable (for Binary Logistic Regression)</strong></p><p>The target variable should contain two possible classes, usually represented as 0 and 1.</p><p>For example:</p><ul><li>1 → Learner completes the course.</li><li>0 → Learner does not complete the course.</li></ul><p>This assumption applies to binary Logistic Regression. Multinomial and ordinal variants handle different target structures.</p><p><strong>2. Independence of Observations</strong></p><p>Each observation should be independent of the others.</p><p>For example, one learner’s course completion record should not depend on another learner’s record.</p><p>If the same learner contributes multiple dependent observations, the independence assumption may be violated.</p><p><strong>3. Linearity in the Logit</strong></p><p>The relationship between continuous independent variables and the log-odds of the outcome should be linear.</p><p>This is one of the most important assumptions of Logistic Regression.</p><p>Notice that Logistic Regression does not require a linear relationship between input features and the probability itself.</p><p>Instead, the relationship should be linear with respect to the log-odds.</p><p><strong>4. No Severe Multicollinearity</strong></p><p>Independent variables should not have strong linear relationships with one another.</p><p>For example, if practice hours and another feature contain almost identical information, it can become difficult to estimate their individual contributions reliably.</p><p><strong>5. Adequate Sample Size</strong></p><p>The model needs an adequate number of observations to estimate its coefficients reliably.</p><p>If the dataset is too small compared with the number of predictors, coefficient estimates may become unstable and predictions may not generalize well.</p><p>The required sample size depends on the number of predictors, class distribution, and complexity of the data.</p><p><strong>6. No Complete Separation</strong></p><p>The input features should not perfectly separate the classes.</p><p>For example, if one feature perfectly identifies every learner who completes the course and every learner who does not, standard Logistic Regression may produce extremely large or unstable coefficient estimates.</p><h4>Important Note: What Logistic Regression Does NOT Assume</h4><p>Unlike Linear Regression, Logistic Regression does not require:</p><ul><li>Normally distributed independent variables.</li><li>Normally distributed residuals.</li><li>Constant variance of residuals (homoscedasticity).</li><li>A linear relationship between input features and predicted probabilities.</li></ul><p>These differences are important when choosing between the two algorithms.</p><h4>2.9 Advantages of Logistic Regression</h4><ul><li>Simple and easy to interpret.</li><li>Produces probability estimates.</li><li>Works well for many binary classification problems.</li><li>Computationally efficient.</li><li>Can be extended to multiclass classification.</li><li>Supports regularization to help control overfitting.</li></ul><h4>2.10 Limitations of Logistic Regression</h4><ul><li>Assumes a linear relationship between predictors and log-odds unless additional transformations are introduced.</li><li>May not perform well when the underlying decision boundary is highly nonlinear.</li><li>Can be affected by multicollinearity.</li><li>May struggle with small datasets or severe class imbalance.</li><li>Requires careful threshold selection depending on the application.</li></ul><h3>3. Regularization in Linear and Logistic Regression</h3><p>Both Linear Regression and Logistic Regression can use regularization to reduce overfitting.</p><p>Regularization adds a penalty to the model’s objective function to discourage unnecessarily large coefficient values.</p><p>There are two commonly used regularization techniques:</p><p><strong>1. L1 Regularization (Lasso)</strong></p><ul><li>Adds the absolute values of the coefficients as a penalty.</li><li>Can reduce some coefficients exactly to zero.</li><li>Can help perform feature selection.</li></ul><p><strong>2. L2 Regularization (Ridge)</strong></p><ul><li>Adds the squared values of the coefficients as a penalty.</li><li>Shrinks coefficients towards zero but generally does not make them exactly zero.</li><li>Helps reduce the effect of large coefficients.</li></ul><p>In Logistic Regression, regularization is commonly controlled using a parameter such as C in Scikit-learn. A smaller C means stronger regularization, while a larger C means weaker regularization.</p><p>Regularization is useful when a model contains many features or when there is a risk of overfitting.</p><h3>4. How Do We Evaluate These Models?</h3><p>After training a Machine Learning model, we need to evaluate how well it performs on unseen data.</p><p>However, Linear Regression and Logistic Regression use different evaluation metrics because they solve different types of problems.</p><h4>Evaluation Metrics for Linear Regression</h4><p><strong>1. Mean Absolute Error (MAE)</strong></p><p>Measures the average absolute difference between actual and predicted values.</p><p><strong>2. Mean Squared Error (MSE)</strong></p><p>Calculates the average of squared prediction errors.</p><p><strong>3. Root Mean Squared Error (RMSE)</strong></p><p>Takes the square root of MSE and expresses prediction error in the same unit as the target variable.</p><p><strong>4. R² Score (Coefficient of Determination)</strong></p><p>Measures how much of the variation in the target variable is explained by the model.</p><p>For example, an R² score of 0.80 indicates that the model accounts for 80% of the variance in the target variable on the evaluated dataset, relative to a mean-based baseline.</p><h4>Evaluation Metrics for Logistic Regression</h4><p><strong>1. Accuracy</strong></p><p>Measures the proportion of correctly classified observations.</p><p><strong>2. Precision</strong></p><p>Measures how many predicted positive cases are actually positive.</p><p><strong>3. Recall</strong></p><p>Measures how many actual positive cases are correctly identified.</p><p><strong>4. F1-Score</strong></p><p>Represents the harmonic mean of precision and recall.</p><p><strong>5. Confusion Matrix</strong></p><p>Shows four important classification outcomes:</p><ul><li>True Positive (TP): Correctly predicted positive cases.</li><li>True Negative (TN): Correctly predicted negative cases.</li><li>False Positive (FP): Negative cases incorrectly predicted as positive.</li><li>False Negative (FN): Positive cases incorrectly predicted as negative.</li></ul><p><strong>6. ROC-AUC</strong></p><p>Measures how well a classification model distinguishes between positive and negative classes across different decision thresholds.</p><h3>5. Linear Regression vs Logistic Regression</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*hKWI40pwi6YpQ_Ap-FawWQ.png" /></figure><h3>6. Real-World Applications</h3><p>Both algorithms are used across different industries to solve practical problems.</p><h4>Applications of Linear Regression</h4><ul><li><strong>Education:</strong> Predicting students’ examination scores based on study hours.</li><li><strong>Real Estate:</strong> Predicting house prices based on area, location, and other features.</li><li><strong>Business:</strong> Forecasting sales revenue based on historical sales data.</li><li><strong>Healthcare:</strong> Estimating numerical measurements based on patient information.</li><li><strong>Finance:</strong> Forecasting numerical financial values.</li></ul><h4>Applications of Logistic Regression</h4><ul><li><strong>Education:</strong> Predicting whether a student will complete a course.</li><li><strong>Healthcare:</strong> Predicting whether a patient belongs to a particular disease category.</li><li><strong>Banking:</strong> Predicting whether a customer may default on a loan.</li><li><strong>Marketing:</strong> Predicting whether a customer will purchase a product.</li><li><strong>Cybersecurity:</strong> Classifying emails as spam or not spam.</li></ul><h3>7. When Should You Use Linear Regression or Logistic Regression?</h3><p>The choice depends on the type of output you want to predict.</p><p>Use <strong>Linear Regression</strong> when:</p><ul><li>The target variable is continuous.</li><li>You want to estimate a numerical value.</li><li>The relationship can be reasonably represented using a linear model.</li></ul><p>Use <strong>Logistic Regression</strong> when:</p><ul><li>The target variable is categorical.</li><li>You want to estimate the probability of belonging to a particular class.</li><li>You need a classification model with interpretable coefficients.</li></ul><p>For our music learning platform:</p><ul><li>If the platform wants to predict how many marks a learner might score, Linear Regression is appropriate.</li><li>If the platform wants to predict whether a learner will complete the course, Logistic Regression is appropriate.</li></ul><h3>8. Conclusion</h3><p>Linear Regression and Logistic Regression are two fundamental algorithms in Supervised Machine Learning.</p><p>Although both algorithms use a linear combination of input features, they differ in how they transform that information and what they predict.</p><p><strong>Linear Regression</strong> predicts continuous numerical values by learning a linear relationship between independent variables and a dependent variable.</p><p><strong>Logistic Regression</strong> predicts the probability of belonging to a particular class by applying the Sigmoid Function to a linear combination of input features.</p><p>Understanding their mathematical foundations, assumptions, cost functions, and evaluation metrics helps us choose the right algorithm for the problem.</p><p><strong>In simple terms:</strong></p><p>Linear Regression answers: <em>How much?</em></p><p>Logistic Regression answers: <em>Which class, and with what probability?</em></p><p>The key is not just understanding how these algorithms work, but knowing when and why to use each one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e69df0ff65e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decision Trees in Machine Learning: How Machines Learn Through Decisions?]]></title>
            <link>https://medium.com/@niharikaponnam80/decision-trees-in-machine-learning-how-machines-learn-through-decisions-54788403b585?source=rss-fcbbf1a0596d------2</link>
            <guid isPermaLink="false">https://medium.com/p/54788403b585</guid>
            <dc:creator><![CDATA[Niharikaponnam]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 16:36:57 GMT</pubDate>
            <atom:updated>2026-11-13T16:36:57.562Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Imagine walking into a shopping mall and trying to decide which store to visit.</strong> You might first consider your budget, then the products you need, and finally compare the available options before making a choice.</p><p>Every decision involves evaluating conditions and choosing a suitable path.</p><p>In Machine Learning, a <strong>Decision Tree</strong> follows a similar approach. It breaks complex problems into smaller questions, evaluates different conditions, and follows a sequence of decisions to arrive at a prediction.</p><p>Let’s explore how this algorithm works and how it solves both classification and regression problems using real-world examples.</p><h3>1. What is a Decision Tree?</h3><p>A Decision Tree is a <strong>supervised machine learning algorithm</strong> used for both classification and regression problems.</p><p>It learns patterns from labelled training data and represents them in a tree-like structure.</p><p>The algorithm repeatedly divides the dataset into smaller groups based on selected conditions until it reaches a final prediction.</p><p><strong>Real-world example:</strong></p><p>Imagine deciding whether to play cricket today.</p><p>You might consider:</p><ul><li>Is it raining?</li><li>Is the ground available?</li><li>Is the weather suitable?</li></ul><p>Based on the answers, you decide whether to play or not.</p><p>Similarly, a Decision Tree uses conditions on input features to reach a prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGijsigozCn6XrecKgHoDA.png" /></figure><h3>2. Structure of a Decision Tree</h3><p>A Decision Tree consists of three main components:</p><p><strong>1. Root Node</strong></p><ul><li>The starting point of the tree.</li><li>Represents the entire dataset.</li><li>Contains the first condition used to split the data.</li></ul><p><strong>2. Decision Nodes (Internal Nodes)</strong></p><ul><li>Represent the conditions used to divide the dataset further.</li><li>Each decision node splits the data into branches based on possible outcomes.</li></ul><p><strong>3. Leaf Nodes (Terminal Nodes)</strong></p><ul><li>Represent the final output or prediction.</li><li>No further splitting happens at these nodes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwgG-TBjNwhAbzAeiSoZPg.png" /></figure><h3>3. How Does a Decision Tree Work?</h3><p>A Decision Tree follows a process called <strong>Recursive Splitting</strong>.</p><p>Let’s understand the process step by step:</p><ol><li><strong>Collect the dataset:</strong> Obtain labelled data containing input features and a target variable.</li><li><strong>Select the best split: </strong>Evaluate different features and their possible conditions to identify the split that provides the best improvement.</li><li><strong>Split the dataset:</strong> Divide the data into smaller groups based on the selected condition.</li><li><strong>Repeat the process:</strong> Apply the same splitting process to the resulting groups.</li><li><strong>Stop splitting:</strong> Stop when a stopping condition is reached, such as maximum depth or minimum samples per leaf.</li><li><strong>Make a prediction:</strong> Use the final leaf node to predict the output for new data.</li></ol><p>This process continues until the tree reaches its stopping conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMDtNRzzEx0cH36UrAAdJQ.png" /></figure><h3>4. Homogeneity in Decision Trees</h3><p>Homogeneity means that the samples within a group belong to the same class or have similar target values.</p><p>A Decision Tree tries to create more homogeneous groups by splitting the dataset based on suitable conditions.</p><p><strong>Classification Example:</strong></p><p>Suppose a dataset contains 10 emails:</p><ul><li>5 Spam</li><li>5 Not Spam</li></ul><p>This group is mixed because it contains two different classes.</p><p>After splitting, suppose we get:</p><ul><li>Group 1: 5 Spam emails</li><li>Group 2: 5 Not Spam emails</li></ul><p>Both groups are now completely homogeneous because each group contains only one class.</p><p><strong>Regression Example:</strong></p><p>Suppose a group contains house prices:</p><p>₹20 lakh, ₹50 lakh, ₹80 lakh, ₹100 lakh</p><p>These values are spread out, so the group has high variation.</p><p>After splitting, we might get:</p><ul><li>Group 1: ₹20 lakh, ₹50 lakh</li><li>Group 2: ₹80 lakh, ₹100 lakh</li></ul><p>The resulting groups have more similar target values, which means lower variation within each group.</p><p>The Decision Tree evaluates possible splits and selects the split that minimizes the weighted variation within the resulting groups.</p><p>How does it make predictions?</p><p>When a new house reaches a leaf node, the Decision Tree predicts the average house price of the training samples in that leaf.</p><p>For example:</p><ul><li>Group 1 prediction: (20 + 50) / 2 = ₹35 lakh.</li><li>Group 2 prediction: (80 + 100) / 2 = ₹90 lakh.</li></ul><p>Important: A Decision Tree aims to increase homogeneity in classification and reduce variation in regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bvSfgvwKB_Du-lq8yz9w1w.png" /></figure><h3>5. Decision Tree is a Greedy Algorithm</h3><p>One important characteristic of a Decision Tree is that it uses a <strong>Greedy Approach</strong>.</p><p>But what does greedy mean here?</p><p>A greedy algorithm makes the best possible choice at the current step without considering whether that choice will produce the best overall result.</p><p>In a Decision Tree:</p><ul><li>The algorithm evaluates the available features.</li><li>It selects the split that provides the best improvement at the current node.</li><li>It divides the dataset using that split.</li><li>It repeats the process for the resulting groups.</li></ul><p><strong>Example:</strong></p><p>Suppose a dataset contains three features:</p><ul><li>Age</li><li>Income</li><li>Previous Purchases</li></ul><p>The algorithm evaluates possible splits using these features and selects the one that gives the best reduction in impurity or prediction error at that particular node.</p><p>Although the algorithm does not reconsider the previous split, the same feature can still be selected again at a later node if it provides the best split for that group.</p><p><strong>Important:</strong> A greedy approach makes locally optimal decisions, but it does not guarantee a globally optimal Decision Tree.</p><h3>6. How Does a Decision Tree Choose the Best Split?</h3><p>This is one of the most important concepts in Decision Trees.</p><p>The algorithm does not randomly select a feature. It uses mathematical measures to identify the best split.</p><p>The splitting criteria depend on whether we are solving a classification or regression problem.</p><h4>A. Classification: Gini Impurity and Entropy</h4><p>In classification, the target variable contains categories such as:</p><ul><li>Spam / Not Spam</li><li>Yes / No</li><li>Pass / Fail</li></ul><p>The algorithm tries to create groups containing samples from a single class or mostly one class. Groups containing only one class are called completely pure nodes.</p><p>Two commonly used impurity measures are:</p><p><strong>1. Gini Impurity</strong></p><p>Gini Impurity measures how mixed the classes are within a group.</p><p>Formula:</p><p>Gini = 1 − Σ(pᵢ²)</p><p>Where:</p><ul><li>pᵢ = Proportion of samples belonging to class i.</li></ul><p>Let’s take an example:</p><p>Suppose a group contains 10 emails:</p><ul><li>8 Spam</li><li>2 Not Spam</li></ul><p>Gini = 1 − [(8/10)² + (2/10)²]</p><p>Gini = 1 − (0.64 + 0.04)</p><p>Gini = 0.32</p><p>A lower Gini value indicates a purer group. A Gini value of 0 means the group contains only one class.</p><p><strong>2. Entropy</strong></p><p>Entropy measures the uncertainty or disorder present in a dataset.</p><p>Formula:</p><p>Entropy = −Σ(pᵢ log₂ pᵢ)</p><p>For the same group:</p><ul><li>Spam = 8/10</li><li>Not Spam = 2/10</li></ul><p>Entropy = −[0.8 log₂(0.8) + 0.2 log₂(0.2)]</p><p>Entropy ≈ 0.722</p><p>Lower entropy means lower uncertainty. Entropy becomes zero when all samples belong to the same class.</p><p><strong>3. Information Gain</strong></p><p>Information Gain measures how much uncertainty is reduced after splitting the dataset.</p><p>Formula:</p><p>Information Gain = Parent Entropy − Weighted Child Entropy</p><p>The algorithm prefers the split that produces the highest Information Gain.</p><p>When using Gini Impurity, the algorithm compares the weighted Gini impurity before and after splitting. When using Entropy, it can use Information Gain to evaluate the reduction in uncertainty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SnSpi-BibJbW9QyaLgIscw.png" /></figure><h4>B. Regression: Mean Squared Error (MSE)</h4><p>In regression, the target variable contains numerical values such as:</p><ul><li>House prices</li><li>Salaries</li><li>Temperature</li><li>Sales revenue</li></ul><p>Instead of separating categories, the algorithm tries to create groups where the numerical target values are close to each other.</p><p>One commonly used splitting criterion is Mean Squared Error (MSE).</p><p>Formula:</p><p>MSE = (1/n) Σ(yᵢ − ȳ)²</p><p>Where:</p><ul><li>n = Number of observations.</li><li>yᵢ = Actual target value.</li><li>ȳ = Mean of the target values.</li></ul><p><strong>Example:</strong></p><p>Suppose a group contains three house prices:</p><p>₹20 lakh, ₹22 lakh, ₹24 lakh.</p><p>Mean = ₹22 lakh.</p><p>MSE = [(20−22)² + (22−22)² + (24−22)²] / 3</p><p>MSE = 8/3 ≈ 2.67 (lakh²)</p><p>The algorithm evaluates possible splits and prefers the split that produces a greater reduction in the weighted MSE of the resulting groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxlN9mxrOEoL78q_do8DKQ.png" /></figure><h3>7. Decision Tree for Classification</h3><p>A Decision Tree Classifier predicts a categorical output.</p><p><strong>Real-world example: Predicting Whether a Customer Will Purchase a Product</strong></p><p>Suppose an online shopping company wants to predict whether a customer will purchase a product using:</p><ul><li>Age</li><li>Previous Purchases</li><li>Website Visits</li></ul><p>The target variable is Purchase (Yes/No).</p><p>The algorithm learns patterns from historical customer data and creates conditions to classify new customers.</p><p>For example:</p><ul><li>Has the customer purchased before?</li><li>Based on the learned conditions, the algorithm follows the appropriate branch.</li><li>It continues evaluating additional conditions if necessary.</li><li>At the leaf node, it predicts the class based on the majority class of the training samples in that leaf.</li></ul><p>The final prediction belongs to one of the available classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5LAcrkY7GInqYcvbPlFTw.png" /></figure><h3>8. Decision Tree for Regression</h3><p>A Decision Tree Regressor predicts a continuous numerical value.</p><p><strong>Real-world example: Predicting House Prices</strong></p><p>Suppose a real estate company wants to predict house prices using:</p><ul><li>House Area</li><li>Number of Bedrooms</li><li>House Age</li><li>Location</li></ul><p>The target variable is House Price.</p><p>The algorithm divides the dataset into smaller groups based on conditions such as house area and number of bedrooms.</p><p>For example:</p><ul><li>Is the house area greater than 1,500 square feet?</li><li>If yes, check the number of bedrooms.</li><li>If no, follow another condition.</li></ul><p>Once the algorithm reaches a leaf node, it predicts a numerical value, commonly the average target value of the training samples in that leaf.</p><p>For example, if the houses in a particular leaf have an average price of ₹50 lakh, the predicted price for a new house reaching that leaf will be ₹50 lakh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEtUVZ10EdI4uAEukp8wog.png" /></figure><h3>9. Classification vs Regression in Decision Trees</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*29-KJ-Wydu_c75x77kGdPQ.png" /></figure><h3>10. Important Hyperparameters</h3><p>Hyperparameters control how a Decision Tree is built and how complex it can become.</p><p><strong>1. max_depth</strong></p><p>Controls the maximum depth of the tree.</p><p>A deeper tree can learn more complex patterns but may overfit.</p><p><strong>2. min_samples_split</strong></p><p>Specifies the minimum number of samples required to split an internal node.</p><p><strong>3. min_samples_leaf</strong></p><p>Specifies the minimum number of samples required in a leaf node.</p><p><strong>4. criterion</strong></p><p>Defines the measure used to evaluate splits.</p><ul><li>Classification: Gini or Entropy.</li><li>Regression: Squared Error, Absolute Error, and other supported criteria.</li></ul><p><strong>5. max_leaf_nodes</strong></p><p>Controls the maximum number of leaf nodes allowed in the tree.</p><h3>11. Overfitting and Pruning</h3><p>A Decision Tree can sometimes learn the training data too closely, including noise and unnecessary patterns.</p><p>This is called <strong>Overfitting</strong>.</p><p>For example, a very deep tree might achieve almost 100% accuracy on training data but perform poorly on unseen data.</p><p>To reduce overfitting, we use pruning techniques.</p><p><strong>1. Pre-Pruning</strong></p><p>Stops the tree from growing too much by setting limits before it becomes too complex.</p><p>Examples:</p><ul><li>max_depth</li><li>min_samples_split</li><li>min_samples_leaf</li></ul><p><strong>2. Post-Pruning</strong></p><p>Allows the tree to grow first and then removes unnecessary branches to simplify it.</p><p>In Scikit-learn, Cost Complexity Pruning uses the ccp_alpha parameter to control how much the tree is pruned.</p><p>Pruning helps improve the model’s ability to generalize to unseen data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nX6SctP3Bj3PD2WAMHJWQ.png" /></figure><h3>12. Implementation of Decision Tree Using Python</h3><p>We can implement Decision Trees using the Scikit-learn library in Python.</p><p>Let’s understand both implementations.</p><h4>A. Decision Tree Classification</h4><p><strong>Example: Predicting Whether a Customer Will Purchase a Product</strong></p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.metrics import accuracy_score<br><br># Separate features and target<br>X = df.drop(&#39;Purchase&#39;, axis=1)<br>y = df[&#39;Purchase&#39;]<br><br># Split the dataset<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br><br># Create the model<br>model = DecisionTreeClassifier(<br>    criterion=&#39;gini&#39;,<br>    max_depth=3,<br>    ccp_alpha=0.01,<br>    random_state=42<br>)<br><br># Train the model<br>model.fit(X_train, y_train)<br><br># Make predictions<br>y_pred = model.predict(X_test)<br><br># Evaluate the model<br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))</pre><p><strong>Understanding the implementation:</strong></p><ul><li>DecisionTreeClassifier creates a classification model.</li><li>criterion=’gini’ uses Gini Impurity to evaluate splits.</li><li>max_depth=3 limits the tree depth.</li><li>fit() trains the model using training data.</li><li>predict() predicts the classes for test data.</li><li>accuracy_score() evaluates the model&#39;s classification accuracy.</li></ul><h4>B. Decision Tree Regression</h4><p><strong>Example: Predicting House Prices</strong></p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.tree import DecisionTreeRegressor<br>from sklearn.metrics import mean_absolute_error, r2_score<br><br># Separate features and target<br>X = df.drop(&#39;Price&#39;, axis=1)<br>y = df[&#39;Price&#39;]<br><br># Split the dataset<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br><br># Create the model<br>model = DecisionTreeRegressor(<br>    criterion=&#39;squared_error&#39;,<br>    max_depth=3,<br>    ccp_alpha=0.01,<br>    random_state=42<br>)<br><br># Train the model<br>model.fit(X_train, y_train)<br><br># Make predictions<br>y_pred = model.predict(X_test)<br><br># Evaluate the model<br>print(&quot;MAE:&quot;, mean_absolute_error(y_test, y_pred))<br>print(&quot;R2 Score:&quot;, r2_score(y_test, y_pred))</pre><p>ccp_alpha=0.01 controls Cost Complexity Pruning. A higher value results in more pruning, making the tree simpler.</p><p>One important note: 0.01 is an example value. The best value should be selected using validation or cross-validation.</p><p><strong>Understanding the implementation:</strong></p><ul><li>DecisionTreeRegressor() creates a regression model.</li><li>criterion=’squared_error’ uses squared error to evaluate splits.</li><li>max_depth=3 limits the tree depth.</li><li>fit() trains the model using training data.</li><li>predict() predicts numerical values for test data.</li><li>mean_absolute_error() measures the average absolute prediction error.</li><li>r2_score() measures how well the model explains the variation in the target variable.</li></ul><p><strong>Note:</strong> These examples assume df is an already loaded dataset with suitable numerical input features. Categorical features need appropriate encoding before training with Scikit-learn&#39;s Decision Tree implementation.</p><h3>13. Advantages and Disadvantages</h3><p><strong>Advantages</strong></p><ul><li>Easy to understand and interpret.</li><li>Supports both classification and regression.</li><li>Requires little feature scaling or normalization.</li><li>Can capture non-linear relationships.</li><li>Useful for identifying important features.</li></ul><p><strong>Disadvantages</strong></p><ul><li>Can easily overfit the training data.</li><li>Small changes in data can produce a different tree.</li><li>Very deep trees can become complicated.</li><li>Greedy splitting does not guarantee the globally optimal tree.</li></ul><h3>14. Real-World Applications</h3><p>Decision Trees are used in many industries:</p><ul><li><strong>Healthcare:</strong> Predicting whether a patient may have a particular disease.</li><li><strong>Banking:</strong> Predicting whether a loan applicant may default.</li><li><strong>E-commerce:</strong> Predicting whether a customer will purchase a product.</li><li><strong>Real Estate:</strong> Predicting house prices.</li><li><strong>Marketing:</strong> Identifying customers likely to respond to a campaign.</li><li><strong>Education:</strong> Predicting student performance.</li></ul><h3>15. Conclusion</h3><p>A Decision Tree is a simple yet powerful supervised learning algorithm that makes predictions by following a sequence of decision rules.</p><p>It uses a greedy approach to select the best split at each step based on impurity reduction in classification or error/variance reduction in regression.</p><p>However, controlling tree complexity is important to prevent overfitting and improve the model’s ability to generalize to unseen data.</p><p>Understanding Decision Trees also provides a foundation for learning more advanced ensemble algorithms, such as Random Forest and Gradient Boosting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54788403b585" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Naive Bayes Algorithm: From Mathematical Intuition to Python Implementation]]></title>
            <link>https://medium.com/@niharikaponnam80/naive-bayes-algorithm-from-mathematical-intuition-to-python-implementation-dcf3aeb1304a?source=rss-fcbbf1a0596d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcf3aeb1304a</guid>
            <dc:creator><![CDATA[Niharikaponnam]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 12:29:01 GMT</pubDate>
            <atom:updated>2026-11-09T12:43:42.417Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>“Just as we use past experiences to make decisions in everyday life, Naive Bayes uses past data and probability to make predictions.”</strong></p><p>Whether it’s identifying a spam email or classifying a customer review, Naive Bayes shows how probability can help machines make decisions.</p><p><strong>Let’s understand how it works!</strong></p><h3>1. Introduction</h3><p>Naive Bayes is a supervised machine learning algorithm primarily used for classification problems. It is based on <strong>Bayes’ Theorem</strong>, a mathematical concept that calculates the probability of an event occurring based on previously available information.</p><p>It is called <em>Naive Bayes</em> because it makes a naive assumption that all features are conditionally independent of each other, given the class label.</p><p>Despite this simplifying assumption, Naive Bayes performs remarkably well in many real-world classification problems, especially:</p><ul><li>Spam email detection</li><li>Sentiment analysis</li><li>Document classification</li><li>News categorization</li><li>Text classification</li><li>Medical diagnosis (as a predictive classification approach)</li></ul><p>One of its biggest advantages is that it is computationally efficient and works well with high-dimensional datasets.</p><h3>2. What is Bayes’ Theorem?</h3><p>Before understanding the Naive Bayes algorithm, let’s understand the mathematical concept behind it:</p><p>Bayes’ Theorem:</p><p>Bayes’ Theorem helps us update the probability of an event when new evidence becomes available.</p><p>For example:</p><p>Imagine you receive an email containing the word “Congratulations”.</p><p>You want to determine whether the email is spam or not spam.</p><p>Instead of simply checking whether the word appears in the email, Bayes’ Theorem helps calculate the probability that the email belongs to the spam category based on the presence of that word.</p><p><strong>Bayes’ Theorem:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIuJAjY6hI628AwbrYm79w.png" /></figure><p>The theorem consists of four important components:</p><ol><li><strong>Prior Probability:</strong> The probability of an event before considering new evidence.</li><li><strong>Likelihood:</strong> The probability of observing the evidence when a particular event has occurred.</li><li><strong>Evidence:</strong> The overall probability of observing the evidence.</li><li><strong>Posterior Probability:</strong> The updated probability of an event after considering the evidence.</li></ol><p>For example:</p><ul><li>Prior: Probability that an email is spam.</li><li>Likelihood: Probability of finding the word “Congratulations” in a spam email.</li><li>Evidence: Probability of finding the word “Congratulations” in any email.</li><li>Posterior: Probability that an email is spam given that it contains the word “Congratulations”.</li></ul><p>The posterior probability is what we want to calculate.</p><h3>3. What Makes Naive Bayes Different?</h3><p>Naive Bayes extends Bayes’ Theorem to classification problems.</p><p>In a classification dataset, we generally have:</p><ul><li>Features (X): Input variables used to make predictions.</li><li>Target (Y): The class we want to predict.</li></ul><p>For example, consider an email classification dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*sUfT8l_L3sU6w0gO4PyRCw.png" /></figure><p>Here:</p><ul><li>Features are the words present in the email.</li><li>Target is the email category.</li></ul><p>Naive Bayes calculates the probability of each possible class based on the given features and predicts the class with the highest probability.</p><p><strong>The Naive Assumption: Conditional Independence</strong></p><p>Suppose an email contains three words:</p><ul><li>X₁ = Free</li><li>X₂ =Prize</li><li>X₃ = Winner</li></ul><p>Naive Bayes assumes that these features are conditionally independent of one another when the class is known.</p><p>In simple terms, once we know that an email belongs to the Spam category, the algorithm treats the occurrence of each word independently when calculating the probability.</p><p>This assumption simplifies the mathematical calculations considerably.</p><p><strong>Important:</strong> The features do not have to be genuinely independent in the real world. Naive Bayes simply assumes conditional independence to make the computation manageable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ALx41fpoaWPcPNTCE-KfQ.png" /></figure><h3>4. Mathematical Derivation of Naive Bayes</h3><p>Let’s derive the Naive Bayes classifier step by step.</p><p><strong>Step 1: Start with Bayes’ Theorem</strong></p><p>For a classification problem, we want to calculate the probability of a class given the available features.</p><p>Let:</p><ul><li>C = Class label</li><li>X = Input features</li></ul><p>Using Bayes’ Theorem:</p><p>P(C | X) = P(X | C) × P(C) / P(X)</p><p>Where:</p><ul><li>P(C | X): Posterior probability</li><li>P(X | C): Likelihood</li><li>P(C): Prior probability</li><li>P(X): Evidence</li></ul><p><strong>Step 2: Expand the Features</strong></p><p>Suppose our dataset contains three features:</p><p>X = (X₁, X₂, X₃)</p><p>Using Bayes’ Theorem:</p><p>P(C | X₁, X₂, X₃) =</p><p>P(X₁, X₂, X₃ | C) × P(C) / P(X₁, X₂, X₃)</p><p><strong>Step 3: Apply the Conditional Independence Assumption</strong></p><p>Here comes the important part.</p><p>Naive Bayes assumes that all features are conditionally independent given the class.</p><p>Therefore:</p><p>P(X₁, X₂, X₃ | C) =</p><p>P(X₁ | C) × P(X₂ | C) × P(X₃ | C)</p><p>Substituting this into Bayes’ Theorem:</p><p>P(C | X₁, X₂, X₃) =</p><p>[P(X₁ | C) × P(X₂ | C) × P(X₃ | C) × P(C)] / P(X₁, X₂, X₃)</p><p><strong>Step 4: Simplify the Formula</strong></p><p>When comparing different classes for the same input, the denominator P(X) remains the same.</p><p>The denominator P(X) is constant for all possible classes because we are evaluating the same input features. Therefore, comparing the numerator is sufficient to identify the class with the highest posterior probability.</p><p>Therefore, we can ignore the denominator while finding the class with the highest probability.</p><p>The classification rule becomes:</p><p><strong>Predicted Class</strong></p><p>Ĉ = argmax_C [ P(C) × P(X₁|C) × P(X₂|C) × P(X₃|C) ]</p><ul><li>P(C): Prior probability of the class.</li><li>P(X₁|C): Probability of each feature given the class.</li><li>argmax: Selects the class with the highest calculated probability.</li></ul><p><strong>General Formula</strong></p><p>For n features, the general formula is:</p><p>P(C|X) ∝ P(C) × ∏ᵢ₌₁ⁿ P(Xᵢ|C)</p><ul><li>n = Total number of features.</li><li>∏= Multiply the probabilities of all features.</li><li>∝= Proportional to (the posterior probability is proportional to the numerator because the denominator remains constant across classes for the same input)</li></ul><p>This is the mathematical foundation of the Naive Bayes algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZnIaKlB8sWlmy2RHE9OEg.jpeg" /></figure><p><strong>Step 5: Choose the Class with the Highest Probability</strong></p><p>The algorithm calculates the probability for every possible class.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*tej2cuZwgfICOb08-Rc0ug.png" /></figure><p>Since Spam has the highest probability, the algorithm predicts the email as Spam.</p><p><strong>Key takeaway:</strong> Naive Bayes calculates the probability of each class and selects the class with the highest posterior probability.</p><h3>5. How Does the Naive Bayes Algorithm Work? (Step-by-Step)</h3><p>Let’s understand the complete workflow.</p><p><strong>Step 1: Collect the dataset</strong></p><p>Obtain a labelled dataset containing input features and target classes.</p><p><strong>Step 2: Preprocess the data</strong></p><ul><li>Handle missing values.</li><li>Encode categorical variables when necessary.</li><li>Convert text into numerical features for text classification.</li><li>Prepare the features and target variables.</li></ul><p><strong>Step 3: Calculate prior probabilities</strong></p><p>Calculate the probability of each class.</p><p>For example:</p><p>P(Spam) = Number of Spam emails / Total emails</p><p>P(Not Spam) = Number of Not Spam emails / Total emails</p><p><strong>Step 4: Calculate likelihood probabilities</strong></p><p>Calculate the probability of each feature occurring given a particular class.</p><p>For example:</p><p>P(Free | Spam)</p><p>P(Free | Not Spam)</p><p><strong>Step 5: Apply the conditional independence assumption</strong></p><p>Combine the individual feature probabilities to calculate the probability of the complete input for each class.</p><p><strong>Step 6: Calculate posterior probabilities</strong></p><p>Apply Bayes’ Theorem to obtain the posterior probability for each class.</p><p><strong>Step 7: Make predictions</strong></p><p>Select the class with the highest posterior probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ji7jFE8hOyEWWhX6-gTeYQ.png" /></figure><h3>6. Types of Naive Bayes Algorithms</h3><p>There are three commonly used types of Naive Bayes classifiers, along with a few specialized variants.</p><h4>6.1 Gaussian Naive Bayes</h4><p>Gaussian Naive Bayes is used when the input features are continuous numerical values.</p><p>It assumes that the features follow a Gaussian (Normal) distribution within each class.</p><p>For example:</p><ul><li>Age</li><li>Height</li><li>Weight</li><li>Temperature</li><li>Blood pressure</li></ul><p>The likelihood is calculated using the Gaussian probability density function.</p><p>Formula:</p><p>P(Xᵢ | C) =1 / √(2πσ²) × exp[-(Xᵢ — μ)² / (2σ²)]</p><p>Where:</p><ul><li>Xᵢ = Feature value</li><li>μ = Mean of the feature for a particular class</li><li>σ² = Variance of the feature for a particular class</li></ul><p><strong>Example:</strong> Predicting whether a patient belongs to a particular risk category based on age, blood pressure and other numerical measurements.</p><h4>6.2 Multinomial Naive Bayes</h4><p>Multinomial Naive Bayes is commonly used for text classification problems.</p><p>It works with discrete feature counts or non-negative feature values.</p><p>For example:</p><ul><li>Number of times a word appears in an email.</li><li>Word frequency in a document.</li><li>Document classification.</li><li>Spam detection.</li><li>Sentiment analysis.</li></ul><p>It is particularly suitable for text classification using Bag of Words (BoW), which represents text using word counts.</p><p>It can also work with non-negative TF-IDF values, although TF-IDF values are not raw word counts.</p><p>The likelihood is calculated using:</p><p>P(Xᵢ | C) = (Nᵢ + α) / (N + αV)</p><p>Where:</p><ul><li>Nᵢ = Count of feature i in the given class.</li><li>N = Total feature counts in the given class.</li><li>α = Smoothing parameter.</li><li>V = Number of unique features.</li></ul><p><strong>Note:</strong> This likelihood formula is based on word-count features. When using TF-IDF, the feature values represent importance-based weights rather than actual word counts. Multinomial Naive Bayes can also work with non-negative TF-IDF values.</p><p>This formula includes Laplace smoothing, which we will discuss later.</p><h4>6.3 Bernoulli Naive Bayes</h4><p>Bernoulli Naive Bayes is used when features represent binary values.</p><p>In other words, each feature indicates whether something is present or absent.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ss7F7J1Y4Lca03YiD14BCA.png" /></figure><p>Here:</p><ul><li>1 indicates that the word is present.</li><li>0 indicates that the word is absent.</li></ul><p>It considers both the presence and absence of features.</p><p>This makes it different from Multinomial Naive Bayes, which focuses on feature counts.</p><h4>Other Variants</h4><p><strong>Complement Naive Bayes:</strong></p><p>A variation of Multinomial Naive Bayes designed to address some issues with imbalanced datasets. It calculates statistics using the complement of each class.</p><p><strong>Categorical Naive Bayes:</strong></p><p>Used when features contain categorical values, such as:</p><ul><li>Weather: Sunny, Rainy, Cloudy</li><li>Education: School, Graduate, Postgraduate</li><li>Employment type: Full-time, Part-time</li></ul><p>It calculates the likelihood of each category given the class.</p><h4>Comparison of Naive Bayes Types</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Ow_BUWFOfUWMXfeuRu_p6A.png" /></figure><h3>7. Laplace Smoothing in Naive Bayes</h3><p>One important problem in Naive Bayes is the zero-frequency problem.</p><p>Let’s understand it with an example.</p><p>Suppose we are classifying emails into Spam and Not Spam.</p><p>During training, the word “Lottery” never appears in the Spam category.</p><p>Therefore:</p><p>P(Lottery | Spam) = 0</p><p>When calculating the overall probability, multiplying by zero makes the entire class probability zero.</p><p>Even if other words strongly indicate Spam, the final probability becomes zero.</p><p>This is called the <strong>Zero-Frequency Problem</strong>.</p><h4>How Does Laplace Smoothing Solve It?</h4><p>Laplace smoothing adds a small value to the feature counts so that no feature probability becomes zero.</p><p>For Multinomial Naive Bayes:</p><p>P(Xᵢ | C) = (Nᵢ + α) / (N + αV)</p><p>Where:</p><ul><li>Nᵢ = Count of the feature in the class.</li><li>N = Total feature counts in that class.</li><li>α = Smoothing parameter.</li><li>V = Vocabulary size.</li></ul><p>When α = 1, it is commonly called Laplace smoothing.</p><p>When α is greater than zero, it is generally referred to as additive smoothing.</p><p><strong>Why is it important?</strong></p><p>It prevents unseen features from assigning zero probability to an entire class.</p><h3>8. Why Does Naive Bayes Use Log Probabilities?</h3><p>When the number of features increases, Naive Bayes multiplies many small probabilities.</p><p>For example:</p><p>0.001 × 0.002 × 0.003 × 0.004</p><p>As the number of features increases, the result can become extremely small.</p><p>This may cause numerical underflow.</p><p>To avoid this problem, implementations commonly use logarithms.</p><p>Using the logarithm property:</p><p>log(a × b) = log(a) + log(b)</p><p>Instead of multiplying probabilities, we add their logarithms.</p><p>The classification equation becomes:</p><p>log P(C | X) ∝ log P(C) + Σ log P(Xᵢ | C)</p><p>The right-hand side represents the unnormalized log-posterior score.</p><p>We omit the denominator because it remains constant when comparing different classes for the same input.</p><p>The algorithm selects the class with the highest log-probability score.</p><p>This makes calculations more numerically stable.</p><p><strong>Important:</strong> Log probabilities do not change which class has the highest probability because the logarithm is a monotonically increasing function.</p><h3>9. Implementation of Naive Bayes in Python</h3><p>Now let’s implement Multinomial Naive Bayes for a sentiment classification problem.</p><p>Our objective is to predict whether a review is Positive or Negative.</p><p><strong>Step 1: Import the Libraries</strong></p><pre>import pandas as pd</pre><pre>from sklearn.model_selection import train_test_split<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.naive_bayes import MultinomialNB</pre><pre>from sklearn.metrics import (<br>    accuracy_score,<br>    classification_report,<br>    confusion_matrix<br>)</pre><p><strong>Step 2: Load the Dataset</strong></p><p>Assume our dataset contains two columns:</p><ul><li>review: Customer review text.</li><li>sentiment: Positive or Negative.</li></ul><pre>df = pd.read_csv(&quot;sentiment_data.csv&quot;)</pre><pre>print(df.head())</pre><p><strong>Step 3: Separate Features and Target</strong></p><pre>X = df[&quot;review&quot;]<br>y = df[&quot;sentiment&quot;]</pre><p>Here:</p><ul><li>X contains the input review text.</li><li>y contains the target sentiment labels.</li></ul><p><strong>Step 4: Split the Dataset</strong></p><p>We divide the dataset into training and testing data.</p><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.2,<br>    random_state=42,<br>    stratify=y<br>)</pre><p>Here:</p><ul><li>80% of the data is used for training.</li><li>20% of the data is used for testing.</li><li>stratify maintains the class distribution across the splits.</li></ul><p><strong>Step 5: Convert Text into Numerical Features</strong></p><p>Machine learning algorithms cannot directly process raw text.</p><p>Therefore, we convert the text into numerical representations using TF-IDF.</p><pre>tfidf = TfidfVectorizer()</pre><pre>X_train_tfidf = tfidf.fit_transform(X_train)</pre><pre>X_test_tfidf = tfidf.transform(X_test)</pre><p><strong>Why do we use fit_transform on training data and transform on testing data?</strong></p><ul><li>fit_transform learns the vocabulary and calculates the IDF weights using training data.</li><li>transform applies the already learned vocabulary and IDF weights to testing data.</li></ul><p>This prevents information from the test dataset from influencing the feature extraction process.</p><p><strong>Step 6: Train the Naive Bayes Model</strong></p><p>We use Multinomial Naive Bayes because our input features are non-negative TF-IDF values.</p><pre>model = MultinomialNB()<br><br>model.fit(X_train_tfidf, y_train)</pre><p>The model learns:</p><ul><li>Prior probabilities of each sentiment class.</li><li>Feature likelihood probabilities for each class.</li></ul><p><strong>Step 7: Make Predictions</strong></p><pre>y_pred = model.predict(X_test_tfidf)</pre><p>The model predicts whether each review belongs to the Positive or Negative category.</p><p><strong>Step 8: Evaluate the Model</strong></p><pre>accuracy = accuracy_score(y_test, y_pred)</pre><pre>print(&quot;Accuracy:&quot;, accuracy)</pre><pre>print(classification_report(y_test, y_pred))</pre><pre>print(confusion_matrix(y_test, y_pred))</pre><p>We use the following evaluation metrics:</p><ul><li>Accuracy: Measures the overall proportion of correct predictions.</li><li>Precision: Measures how many predicted positive cases were actually positive.</li><li>Recall: Measures how many actual positive cases were correctly identified.</li><li>F1-score: Harmonic mean of precision and recall.</li></ul><p>We should not rely only on accuracy, especially when the dataset contains imbalanced classes.</p><p><strong>Step 9: Predict a New Review</strong></p><p>Let’s test the model with a new customer review.</p><pre>new_review = [&quot;The product is amazing and I love it&quot;]</pre><pre>new_review_tfidf = tfidf.transform(new_review)</pre><pre>prediction = model.predict(new_review_tfidf)</pre><pre>print(&quot;Predicted Sentiment:&quot;, prediction[0])</pre><p>The model predicts the sentiment based on the patterns it learned during training.</p><h3>10. Advantages of Naive Bayes</h3><ol><li><strong>Simple and easy to implement:</strong> The algorithm has a straightforward mathematical foundation.</li><li><strong>Computationally efficient:</strong> Training and prediction are generally fast.</li><li><strong>Works well with high-dimensional data:</strong> It is particularly effective for text datasets containing thousands of features.</li><li><strong>Requires less training data:</strong> It can perform reasonably well even with relatively small datasets.</li><li><strong>Supports multiclass classification:</strong> It can classify data into more than two categories.</li><li><strong>Provides probabilistic predictions:</strong> It can estimate class probabilities using predict_proba in Scikit-learn.</li></ol><h3>11. Disadvantages of Naive Bayes</h3><ol><li><strong>Conditional independence assumption:</strong> Real-world features are often correlated, which can affect performance.</li><li><strong>Zero-frequency problem:</strong> Without smoothing, unseen features can result in zero probabilities.</li><li><strong>Probability estimates may not be well calibrated:</strong> Predicted probabilities are not necessarily reliable estimates of actual confidence.</li><li><strong>Distribution assumptions:</strong> Gaussian Naive Bayes assumes a Gaussian distribution for continuous features. If this assumption is inappropriate, performance may suffer.</li><li><strong>Limited ability to capture feature relationships:</strong> It does not explicitly model complex dependencies between features.</li></ol><h3>12. Important Things to Remember</h3><p>Here are some important points to understand when working with Naive Bayes:</p><ul><li>Naive Bayes is a supervised classification algorithm.</li><li>It is based on Bayes’ Theorem.</li><li>It assumes conditional independence between features given the class.</li><li>It can be used for binary as well as multiclass classification.</li><li>Gaussian Naive Bayes is suitable for continuous features.</li><li>Multinomial Naive Bayes is commonly used for text classification.</li><li>Bernoulli Naive Bayes works with binary features.</li><li>Laplace smoothing handles zero-frequency problems.</li><li>Log probabilities help prevent numerical underflow.</li><li>Feature scaling is not generally required for Naive Bayes in the same way it is for distance-based algorithms.</li><li>TF-IDF features must be non-negative when used with Multinomial Naive Bayes.</li><li>Preprocessing and feature extraction should be fitted only on training data.</li><li>Cross-validation can be used to evaluate model stability and tune hyperparameters.</li><li>The alpha parameter in Scikit-learn controls smoothing.</li></ul><h3>13. Important Hyperparameters in Scikit-learn</h3><p>Different Naive Bayes classifiers have different hyperparameters.</p><p>Some commonly used ones are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*SHdKen3nZS936ebaoiOoyA.png" /></figure><p>For example, in MultinomialNB:</p><pre>model = MultinomialNB(alpha=1.0)</pre><p>Here, alpha controls additive smoothing.</p><p>Hyperparameter tuning can help identify settings that improve model performance on unseen data.</p><h3>14. When Should We Use Naive Bayes?</h3><p>Naive Bayes is a good choice when:</p><ul><li>You need a fast classification algorithm.</li><li>You are working with text classification.</li><li>Your dataset contains high-dimensional features.</li><li>You need a simple baseline model.</li><li>You want to estimate class probabilities.</li><li>You have limited computational resources.</li></ul><p>However, if the features have strong dependencies or complex relationships, other classification algorithms may perform better.</p><p>It is always important to compare different models using appropriate evaluation metrics.</p><h3>15. Conclusion</h3><p>Naive Bayes is a simple yet powerful classification algorithm built on Bayes’ Theorem.</p><p>Its key strength lies in converting probability calculations into an efficient classification approach using the conditional independence assumption.</p><p>Although this assumption may not always hold in real-world datasets, Naive Bayes remains a useful algorithm, particularly for text classification, spam detection and sentiment analysis.</p><p>Understanding its mathematical foundation, different variants, smoothing techniques and practical implementation helps us understand not only how the algorithm works but also when and why to use it.</p><p><strong>The most important takeaway:</strong> Naive Bayes predicts the most probable class by combining prior probabilities with the likelihood of observing the given features.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcf3aeb1304a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Training: The Two Techniques That Make Machine Learning Models More Reliable]]></title>
            <link>https://medium.com/@niharikaponnam80/beyond-training-the-two-techniques-that-make-machine-learning-models-more-reliable-7d2ea0a01950?source=rss-fcbbf1a0596d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d2ea0a01950</guid>
            <dc:creator><![CDATA[Niharikaponnam]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 09:10:58 GMT</pubDate>
            <atom:updated>2026-11-07T09:10:58.933Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Cross-Validation and Hyperparameter Tuning — A Simple Guide to Evaluating Models and Finding the Right Settings.</strong></p><h4><strong>Introduction</strong></h4><p>Imagine baking a cake for the first time. You prepare the batter, put it in the oven, and wait for the result.</p><p>But how do you know whether the cake will turn out well every time? You might try baking it several times to check whether the results are consistent. This is similar to <strong>Cross-Validation</strong> in Machine Learning.</p><p>Now, what if the cake is too soft, too dry, or undercooked? You might change the oven temperature or baking time to get a better result. This is similar to <strong>Hyperparameter Tuning</strong>.</p><p>In Machine Learning, Cross-Validation helps us check how consistently a model performs, while Hyperparameter Tuning helps us find the right settings to improve its performance.</p><p>Let’s understand how both work!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pN2TygZhqdDJZDZumbCBQ.png" /></figure><h4>Part 1: Why Testing Once Is Not Enough</h4><p>After training a model, we need to check how good it is. The usual way is:</p><ul><li>Keep <strong>80%</strong> of the data for <strong>training</strong> (learning)</li><li>Keep <strong>20%</strong> of the data for <strong>testing</strong> (exam)</li></ul><p>The problem is that the score depends on <em>which 20%</em> you picked. If the test part is easy, the model looks great. If it is difficult, the model looks bad.</p><p>It’s like judging a whole cake by tasting just <strong>one piece</strong>. That piece might be burnt, or it might be perfect. One piece doesn’t tell the full story.</p><h4>Part 2: Cross-Validation (Taste Every Piece)</h4><p><strong>Cross-Validation</strong> means testing the model <strong>many times, each time on a different part of the data</strong>, and then taking the average score.</p><p><strong>The basic idea: K-Fold Cross-Validation</strong></p><ol><li>Divide the data into <strong>K equal parts</strong> (called <em>folds</em>).</li><li>Use <strong>1 part to test</strong> and the <strong>remaining parts to train</strong>.</li><li>Repeat this <strong>K times</strong>, so every part gets one turn as the test.</li><li>Take the <strong>average</strong> of all the scores.</li></ol><p><strong>K is your choice.</strong> In our cake example we used 5 pieces, but you can use any number. The most common choices are <strong>5 and 10</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dBvZvspPebvRi6wX9zw8A.png" /></figure><p><strong>How to Read the Results</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9wxWkZzpvU5-TdfRbnfpw.png" /></figure><p>The second row is like Cake 1 to Cake 5 in Figure 1. When the scores are very different, the model is not dependable.</p><p><strong>Simple Code (K-Fold)</strong></p><p>from sklearn.model_selection import cross_val_score<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.datasets import load_breast_cancer</p><p>X, y = load_breast_cancer(return_X_y=True)</p><p>model = RandomForestClassifier(random_state=42)</p><p>scores = cross_val_score(model, X, y, cv=5)</p><p>print(“Scores:”, scores)<br>print(“Average:”, scores.mean())</p><p>To change K, just change the number. For example, cv=10 gives 10 folds.</p><p><strong>Other Types of Cross-Validation</strong></p><p>K-Fold works well in most cases. For special data, there are other ways to cut the cake:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*XWG_YIPDuY7fNJDv6hLBPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZkbb-vy2vgXYe7OhXngoQ.png" /></figure><h4>Part 3: Hyperparameter Tuning (Adjust the Oven)</h4><p><strong>Parameters vs Hyperparameters</strong></p><ul><li><strong>Parameters:</strong> things the model <strong>learns by itself</strong> from the data.</li><li><strong>Hyperparameters:</strong> settings <strong>you choose before training</strong>.</li></ul><p>In our cake example:</p><ul><li>Batter = your data</li><li>Oven temperature and time = hyperparameters</li></ul><p>The same batter can burn at one setting and come out perfect at another. In Figure 1, the accuracy goes from 60% to 85% to 95% just by changing the settings.</p><h4>Grid Search (Try Every Combination)</h4><p><strong>Grid Search</strong> tries <strong>all combinations</strong> of the settings you give it, one by one. It’s like testing every temperature with every baking time.</p><p>Example with a Random Forest model:</p><ul><li>n_estimators (number of trees): 50, 100, 200</li><li>max_depth (how deep each tree can grow): 3, 5, 10</li></ul><p>That makes 3 × 3 = <strong>9 combinations</strong>. Grid Search tests all 9 and tells you which one is best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*wzivlmNt4oFnYooEdv5QYA.png" /></figure><p><strong>How does it test each combination?</strong> It uses <strong>Cross-Validation</strong>. Each combination gets its own average score, and the combination with the highest average wins.</p><p><strong>Implementation</strong></p><p>from sklearn.model_selection import GridSearchCV</p><p>settings = {<br> “n_estimators”: [50, 100, 200],<br> “max_depth”: [3, 5, 10]<br>}</p><p>grid = GridSearchCV(model, settings, cv=5) # K-Fold with K = 5<br>grid.fit(X, y)</p><p>print(“Best settings:”, grid.best_params_)<br>print(“Best score:”, grid.best_score_)</p><p>You can replace cv=5 with any other Cross-Validation type, like Stratified K-Fold.</p><h4>Random Search (Try Random Combinations)</h4><p>When there are too many combinations, Grid Search becomes slow. <strong>Random Search</strong> tests only some <strong>randomly picked</strong> combinations. It is faster and often gives a good result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9jLa-FvxAN6m4a0xFwSktg.png" /></figure><h4>Part 4: How Both Work Together</h4><p>Hyperparameter Tuning <strong>uses Cross-Validation inside it</strong>.</p><ol><li>Take one setting (for example, depth = 3).</li><li>Run Cross-Validation and take the <strong>average score</strong>.</li><li>Do the same for every other setting.</li><li>Compare the averages and <strong>pick the setting with the highest one</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*iIHJL_k0rPO4-IV_7_HN2g.png" /></figure><p>We use the average instead of one score so that one lucky result doesn’t fool us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFDtvklU0t9nnEQ6fK2YLQ.png" /></figure><p><strong>Golden rule:</strong> Never use the test data while tuning. Think of it as the final exam. If you see the questions early, the result is no longer honest.</p><h4>Part 5: Common Mistakes</h4><ol><li><strong>Looking at test data while tuning.</strong> Keep it hidden until the very end.</li><li><strong>Only checking the average.</strong> Also check if the scores are close to each other.</li><li><strong>Trying too many settings.</strong> You may end up fitting too well to your own data.</li><li><strong>Using normal splitting for date-based data.</strong> Use Time Series Split so the model doesn’t learn from the future.</li></ol><p><strong>Key Takeaways</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*PkdAB93z-3YKA9jPkmq0CA.png" /></figure><p><strong>Remember:</strong> Cross-Validation = <em>Similar</em> results? Hyperparameter Tuning = <em>Better</em> results!</p><h4>Conclusion</h4><p>A model that scores well once is not always a good model. It may just have been lucky. Cross-Validation checks that the results are steady, and Hyperparameter Tuning makes them better. Used together, you can trust your model.</p><p>So next time, remember the cake: <strong>taste every piece, then adjust the oven.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d2ea0a01950" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Nearest Neighbors (KNN): How Does a Machine Learn by Looking at Its Neighbors?]]></title>
            <link>https://medium.com/@niharikaponnam80/k-nearest-neighbors-knn-how-does-a-machine-learn-by-looking-at-its-neighbors-4a15d9b1adb3?source=rss-fcbbf1a0596d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a15d9b1adb3</guid>
            <dc:creator><![CDATA[Niharikaponnam]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 07:13:27 GMT</pubDate>
            <atom:updated>2026-10-20T07:13:27.819Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever made a decision by looking at what happened to people in a situation similar to yours?</p><p>Imagine moving into a new neighborhood and wanting to estimate the price of a house. You look at nearby houses with similar sizes, locations, and features. If those houses sold for around ₹40–50 lakh, you might estimate that your house has a similar value.</p><p><strong>Or</strong> imagine receiving an email and trying to determine whether it is spam. You compare its characteristics with emails that have already been classified as spam or not spam.</p><p>Both situations follow a simple idea: use the outcomes of similar examples to make a prediction.</p><p>This is the intuition behind K-Nearest Neighbors (KNN), one of the most intuitive algorithms in machine learning.</p><p>But how does KNN determine which examples are similar? Why does the value of K matter? Why can adding more features make the algorithm less effective? And how can we evaluate whether its predictions are reliable?</p><p>Let’s explore these questions step by step.</p><h4>1. What is K-Nearest Neighbors (KNN)?</h4><p>K-Nearest Neighbors is a supervised, distance-based machine learning algorithm used for both classification and regression.</p><p>It predicts the outcome of a new observation by identifying the K closest observations in the training dataset.</p><p>Let’s break down its name:</p><ul><li><strong>K</strong>: The number of neighbors considered.</li><li><strong>Nearest</strong>: The observations closest to the new observation according to a selected distance or similarity measure.</li><li><strong>Neighbors</strong>: Existing observations in the training dataset.</li></ul><p>Suppose we want to predict whether a customer will purchase a product. KNN identifies customers with similar characteristics and examines their purchase decisions. If most of the nearest neighbors purchased the product, KNN may predict that the new customer will purchase it too.</p><p>KNN is also described as:</p><ul><li><strong>Instance-based learning</strong>: It uses stored training examples to make predictions.</li><li><strong>Non-parametric learning</strong>: It does not assume a fixed mathematical form for the relationship between the features and target.</li><li><strong>Lazy learning</strong>: It postpones most of its computation until a prediction is requested.</li></ul><p>Unlike many algorithms, KNN does not normally learn a conventional fitted equation during training. Instead, it stores the training data and uses distance calculations when making predictions.</p><p>The <strong>central idea</strong> is simple:</p><p>Observations that are close to each other in the feature space may have similar outcomes.</p><p>However, this works well only when the chosen features and distance metric represent meaningful similarity.</p><h4>2. Why KNN? Why do we need it?</h4><p>Before understanding the algorithm, let’s understand the problem it solves.</p><p>Imagine having information about hundreds of houses, including their sizes, locations, number of bedrooms, and selling prices. You want to estimate the price of a new house.</p><p>One approach is to build a mathematical model that learns a relationship between house features and prices. Another approach is to find houses most similar to the new house and use their prices to estimate its value.</p><p>KNN follows the second approach.</p><p><strong>Why is this useful?</strong></p><p><strong>1. It is intuitive.</strong></p><p>The logic is easy to understand: find similar examples and use their known outcomes.</p><p><strong>2. It can model nonlinear relationships.</strong></p><p>KNN does not require the relationship between the features and target to follow a straight line. Its predictions can adapt to local patterns in the training data.</p><p><strong>3. It supports classification and regression.</strong></p><p>It can predict a category, such as spam or not spam, or a numerical value, such as a house price.</p><p><strong>4. It makes relatively few assumptions about the underlying data relationship.</strong></p><p>Unlike a model that assumes a specific equation, KNN relies on the local structure of the observations.</p><p><strong>5. It is useful as a baseline model.</strong></p><p>KNN can provide a straightforward reference point when comparing more complicated machine learning approaches.</p><p>However, KNN also has limitations. Predictions can become slow on large datasets, irrelevant features can distort distances, and performance can deteriorate in high-dimensional spaces.</p><h4>3. How does KNN work? The experimental framework</h4><p>Understanding KNN becomes easier when we follow the complete prediction process.</p><p>Suppose we have a dataset containing customer information and whether each customer purchased a product. We want to predict the purchase decision for a new customer.</p><p>KNN follows four main steps.</p><p><strong>Step 1: Choose the value of K</strong></p><p>The value of K determines how many neighbors influence the prediction.</p><p>For example:</p><ul><li>K=1: Consider the single nearest neighbor.</li><li>K=3: Consider the three nearest neighbors.</li><li>K=5: Consider the five nearest neighbors.</li></ul><p>The choice of <strong>K</strong> affects how sensitive the model is to individual observations and how much it smooths local patterns.</p><p><strong>Step 2: Calculate distances</strong></p><p>KNN calculates the distance between the new observation and the training observations.</p><p>A commonly used distance measure is Euclidean distance.</p><p>For two observations with n features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2z1UoAvv38Bhh1OQeyoDvA.png" /></figure><p>Here:</p><ul><li>x represents one observation.</li><li>y represents another observation.</li><li>xᵢ and yᵢ are their values for feature i.</li><li>n is the number of features.</li></ul><p>A smaller distance indicates that two observations are closer under this metric.</p><p><strong>Step 3: Identify the K nearest neighbors</strong></p><p>After calculating distances, KNN ranks the training observations and selects the K closest ones.</p><p>For example, if K=3, it selects the three training observations with the smallest distances from the new observation.</p><p><strong>Step 4: Make the prediction</strong></p><p>The final step depends on the type of problem:</p><ul><li><strong>Classification</strong>: Predict the class that receives the most votes from the neighbors.</li><li><strong>Regression</strong>: Predict a numerical value using the average of the neighbors’ target values.</li></ul><p>The distance-based search process is similar in both cases. The difference lies in how the neighbors’ outcomes are combined.</p><p><strong>Why is feature scaling important?</strong></p><p>Suppose a dataset contains age, measured in years, and annual income, measured in rupees. Income may have much larger numerical values than age.</p><p>If we calculate Euclidean distance directly, income can dominate the distance calculation because of its scale.</p><p>Standardization or min-max scaling can help make numerical features more comparable. Scaling should be fitted on the training data and then applied to validation and test data to avoid data leakage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiprmhTs_Zhg9PxPsijxSw.png" /></figure><h4>4. KNN for classification: Predicting categories</h4><p>Classification is used when the target variable represents a category or class.</p><p>Examples include:</p><ul><li>Spam or not spam</li><li>Fraudulent or legitimate transaction</li><li>Customer likely to purchase or not purchase</li><li>Benign or malignant classification in medical datasets</li></ul><p>In KNN classification, the algorithm examines the labels of the K nearest neighbors and predicts the class that receives the most votes.</p><p><strong>Example: Will a customer purchase a product?</strong></p><p>Suppose we want to predict whether a new customer will purchase a product. We select K=5 and identify the five nearest customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UK2fIPKlTqpRrEZl0y8guA.png" /></figure><p>Among the five neighbors:</p><ul><li>Yes: 3 votes</li><li>No: 2 votes</li></ul><p>Therefore, KNN predicts <strong>Yes.</strong></p><p>The mathematical expression is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hD6x1IS8cly3UD2mlC-FUA.png" /></figure><p>Here, mode represents the most frequently occurring class label.</p><p><strong>Why does KNN often use an odd value of K?</strong></p><p>This is an important question because you will often see examples using K=3, K=5, or K=7.</p><p>Consider binary classification, where the possible classes are Yes and No.</p><p>If K=4, the neighbors might vote as follows:</p><ul><li>Yes: 2</li><li>No: 2</li></ul><p>The result is a tie. There is no majority class.</p><p>Now consider K=5:</p><ul><li>Yes: 3</li><li>No: 2</li></ul><p>The <strong>Yes </strong>class wins.</p><p>An odd value of K can reduce the possibility of ties in binary classification when every neighbor gets one vote.</p><p><strong>But there is an important distinction:</strong> KNN does not require K to be odd. Odd values are a useful practical choice in some binary classification problems, not a universal rule.</p><p>Ties can still occur with multiple classes, weighted voting, or particular implementations. Even values of K can also work perfectly well when selected through validation.</p><p><strong>What if closer neighbors should matter more?</strong></p><p>Ordinary KNN gives each neighbor one vote, regardless of its distance. Weighted KNN changes this by giving closer neighbors greater influence.</p><p>One common weighting approach is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjiqTOvk9Z7yH3ZtHKBfVg.png" /></figure><p>Here, dᵢ is the distance to neighbor i, and ϵ(epsilon) is a small positive value used to prevent division by zero.</p><p>The class with the largest total neighbor weight is selected.</p><p>This can be useful when one very similar observation should contribute more than a less similar one. Exact distance-zero matches require appropriate handling in an implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SLA0bH1Yg0gw58RNPY5ulg.png" /></figure><p><strong>What happens when KNN encounters a tie?</strong></p><p>We discussed why odd values of K are often used in binary classification. But choosing an odd value does not guarantee that ties will never occur.</p><p>Let’s understand this with an example.</p><p>Suppose we want to classify a new customer using K=4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOe-auBNejxlKCaE8w_r0g.png" /></figure><p>The votes are:</p><ul><li>Yes: 2</li><li>No: 2</li></ul><p>Both classes receive the same number of votes. So, which class should KNN predict?</p><p>There is no unique majority class in this situation. The algorithm needs a tie-breaking strategy.</p><p><strong>How can we resolve a tie?</strong></p><p><strong>1. Choose an odd value of K</strong></p><p>For binary classification, an odd K can reduce ties when each neighbor gets one vote.</p><p>For example, with K=3, the votes could be Yes = 2 and No = 1.</p><p>However, odd values do not eliminate every possible tie, especially in multiclass classification or weighted voting.</p><p><strong>2. Use distance-weighted voting</strong></p><p>Give closer neighbors more influence than farther neighbors.</p><p>For example, suppose the votes are tied, but the distances are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pc9_WRQaiJuqv5vGXeBA-Q.png" /></figure><p>The total weights using wᵢ = 1/dᵢ are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TuidVOGYiKnwe-pmDUZcaQ.png" /></figure><p>Although both classes have two votes, Yes has the larger total weight. Therefore, weighted KNN predicts Yes.</p><p><strong>3. Use a predefined tie-breaking rule</strong></p><p>If the vote counts and weights are still tied, an implementation can use a predefined rule, such as a deterministic class priority or a suitable secondary criterion. The exact behavior depends on the implementation.</p><p>The important point is that tie-breaking should be deliberate rather than accidental.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2HJfOWGaXFLdv5h2psVYQ.png" /></figure><h4>5. KNN for regression: Predicting numerical values</h4><p>Classification predicts a category. Regression predicts a continuous numerical value.</p><p>Examples include:</p><ul><li>House price prediction</li><li>Estimating delivery time</li><li>Predicting product demand</li><li>Estimating customer spending</li></ul><p>KNN regression follows the same neighbor-search process as classification. However, instead of counting class labels, it calculates the average of the target values of the nearest neighbors.</p><p>The prediction is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntCDf2O4ESQuAWu3FVG-eg.png" /></figure><p>Here:</p><ul><li>ŷ is the predicted value.</li><li>K is the number of neighbors.</li><li>yᵢ is the target value of neighbor i.</li></ul><p><strong>Example: Predicting a house price</strong></p><p>Suppose the three nearest houses have these selling prices:</p><ul><li>House A: ₹40 lakh</li><li>House B: ₹45 lakh</li><li>House C: ₹50 lakh</li></ul><p>If K=3, the predicted price is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1B_vIf4s2P3lMxLqPKQKQ.png" /></figure><p>The estimated price of the new house is ₹45 lakh.</p><p>Notice that KNN does not need to fit a straight line between house size and price. It uses the values of nearby houses to make its prediction.</p><p><strong>What about weighted KNN regression?</strong></p><p>The ordinary average gives each neighbor equal influence. Weighted regression gives closer observations more influence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4gdQEx7sxskV5wBSbgz4xA.png" /></figure><p>This is the <strong>distance-weighted average</strong> for KNN regression. The plain average treats all K neighbors equally. This version lets closer neighbors count for more.</p><ul><li><strong>ŷ</strong> is the predicted value for the new point.</li><li><strong>yᵢ</strong> is the target value of neighbor i, such as its house price.</li><li><strong>wᵢ</strong> is the weight of neighbor i. It is usually wᵢ = 1 / (dᵢ + ϵ), so a smaller distance gives a larger weight.</li><li><strong>Numerator, Σ wᵢyᵢ:</strong> Each neighbor’s value is multiplied by its weight, and the results are added up.</li><li><strong>Denominator, Σ wᵢ:</strong> The weights are added up. Dividing by this keeps the result on the same scale as the original values.</li></ul><p>If every weight is equal, the formula reduces to the simple average</p><p>ȳ = (1/K) Σᵢ yᵢ, for i = 1 to K</p><p><strong>Example</strong></p><p>Take three neighbors with values 40, 45 and 50 lakh, at distances 0.5, 1 and 2, ignoring ϵ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oydXT72BU5luj17z0jjV4Q.png" /></figure><ul><li>Numerator: 80 + 45 + 25 = 150</li><li>Denominator: 2.0 + 1.0 + 0.5 = 3.5</li><li>ŷ = 150 / 3.5 ≈ <strong>42.9 lakh</strong></li></ul><p>The simple average gave 45 lakh. The weighted answer is lower because the nearest neighbor, at 40 lakh, has the biggest weight.</p><h4>6. How do we choose the right value of K?</h4><p>We already know that K represents the number of neighbors considered. But how do we determine the best value?</p><p>There is no single value of K that works best for every dataset.</p><p><strong>Small K: The model can overfit</strong></p><p>Suppose K=1.</p><p>The prediction depends entirely on the single nearest training observation. If that observation is noisy or incorrectly labeled, the prediction can be wrong.</p><p>For classification, the decision boundary can become highly irregular because the model reacts strongly to individual observations.</p><p>This is associated with high variance.</p><p><strong>Large K: The model can underfit</strong></p><p>Now suppose K is very large.</p><p>The algorithm considers observations from a much broader region. This can smooth out local patterns that are important for prediction.</p><p>In classification, a large K may favor the overall majority class, even when the local neighborhood contains a different pattern.</p><p>This is associated with higher bias.</p><p><strong>Understanding the bias-variance trade-off</strong></p><ul><li><strong>Very small K:</strong> Often more flexible, but more sensitive to noise.</li><li><strong>Very large K:</strong> Often smoother, but may miss important local patterns.</li><li><strong>Suitable K:</strong> Balances local sensitivity with generalization to unseen data.</li></ul><p>These are general tendencies rather than guarantees. The actual behavior depends on the dataset, its noise level, the distance metric, and feature scaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8ShphBnvP8NkDysI-nNKw.png" /></figure><p><strong>How should K be selected in practice?</strong></p><p>A reliable approach is to use validation rather than choosing a value arbitrarily.</p><ol><li>Split the dataset into training and test sets.</li><li>Use the training data to evaluate several candidate values of K through cross-validation.</li><li>Select the value that performs well according to the appropriate evaluation metric.</li><li>Fit the final model using the selected settings and training data.</li><li>Evaluate it on the untouched test set.</li></ol><p>For example, if the task is imbalanced classification, F1-score may be more informative than accuracy. For regression, MAE or RMSE may be appropriate.</p><p>An odd value can be a reasonable starting point for binary classification, but it should not override the results of validation.</p><h4>7. How do we evaluate KNN’s performance?</h4><p>A model that makes predictions is not automatically a good model. We need to evaluate how accurately it predicts unseen observations.</p><p>The evaluation method depends on whether KNN is being used for classification or regression.</p><p><strong>Classification evaluation metrics</strong></p><p><strong>Accuracy</strong></p><p>The proportion of predictions that are correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_szmQTdkFEbw6BX16fL--Q.png" /></figure><p>For example, if KNN correctly classifies 90 out of 100 observations, its accuracy is 90%.</p><p>However, accuracy alone can be misleading when the classes are imbalanced.</p><p><strong>Precision</strong></p><p>Precision answers: Of all the observations predicted as positive, how many were actually positive?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCaR0BGpq6Yodn7e9xyidQ.png" /></figure><p><strong>Recall</strong></p><p>Recall answers: Of all the actual positive observations, how many did the model identify?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWuBAgiln-Bw3fRY7n4ScA.png" /></figure><p><strong>F1-score</strong></p><p>The F1-score combines precision and recall using their harmonic mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpJ38gZQPuIYgWwLw2ecCg.png" /></figure><p>These metrics are particularly useful when false positives and false negatives have different consequences.</p><p><strong>Regression evaluation metrics</strong></p><p>For KNN regression, the prediction is a numerical value, so we measure the difference between predicted and actual values.</p><ul><li><strong>MAE:</strong> Mean absolute error; the average magnitude of the errors.</li><li><strong>MSE:</strong> Mean squared error; squares errors before averaging, giving larger errors more influence.</li><li><strong>RMSE:</strong> Square root of MSE; expresses error in the target’s units.</li><li><strong>R²: </strong>Measures performance relative to predicting the target mean, with important limitations in interpretation.</li></ul><p>For house-price predictions, MAE and RMSE can help quantify how far the estimated prices are from the actual prices.</p><p><strong>Why do we need separate training, validation, and test data?</strong></p><ul><li><strong>Training data:</strong> Stores the examples used by KNN and fits preprocessing steps.</li><li><strong>Validation data or cross-validation:</strong> Helps select K, the distance metric, and other settings.</li><li><strong>Test data:</strong> Estimates final performance on data that was not used for model selection.</li></ul><p>This separation reduces the risk of choosing settings that work well only on the data already examined.</p><h4>8. The curse of dimensionality: Why can more features make KNN worse?</h4><p>This is one of the most important limitations of KNN.</p><p>The curse of dimensionality describes difficulties that arise as the number of dimensions or features increases. In high-dimensional spaces, data often becomes sparse, and distance-based comparisons can become less informative.</p><p>Why does this matter so much for KNN?</p><p>Because the algorithm depends on finding observations that are meaningfully close to the new observation.</p><p><strong>Let’s build the intuition</strong></p><p>Imagine trying to identify similar houses using two features:</p><ul><li>House size</li><li>Distance from the city center</li></ul><p>Houses with similar values for both features may be reasonable neighbors.</p><p>Now imagine adding 100 features, including house age, room count, construction materials, neighborhood characteristics, and many other measurements.</p><p>Three problems can arise.</p><p><strong>Problem 1: Data becomes sparse</strong></p><p>As dimensions increase, the volume of the feature space can grow rapidly.</p><p>Unless the number of observations grows sufficiently, the available training data covers a smaller fraction of the space. Observations become sparse relative to the possible combinations of feature values.</p><p>Consequently, finding enough genuinely similar neighbors becomes harder.</p><p><strong>Problem 2: Distances become less informative</strong></p><p>In many high-dimensional datasets, the relative difference between the distances to the nearest and farthest points becomes smaller.</p><p>In other words, the nearest observation may not be meaningfully closer than many other observations.</p><p>If almost every observation appears similarly distant, selecting the nearest neighbors becomes less useful.</p><p>This behavior is not identical for every dataset. It depends on the data distribution, distance metric, and feature representation.</p><p><strong>Problem 3: Irrelevant features distort similarity</strong></p><p>Suppose two candidates have very similar skills and experience, but the dataset also contains many irrelevant features.</p><p>Those irrelevant dimensions may affect the calculated distances and make the candidates appear less similar than they really are for the task.</p><p>More features do not necessarily mean more useful information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i81GQhqAyTnhgDqsgFqypg.png" /></figure><p><strong>How can we reduce the curse of dimensionality?</strong></p><p><strong>Feature selection: </strong>Remove irrelevant or redundant features.</p><p><strong>Dimensionality reduction:</strong> Use techniques such as Principal Component Analysis (PCA) to represent the data with fewer dimensions while retaining important variation.</p><p><strong>Feature engineering:</strong> Construct features that better represent the similarity relevant to the prediction task.</p><p><strong>Collect more representative data: </strong>Additional observations can improve coverage of the feature space, although this does not automatically solve the problem.</p><p><strong>Try alternative algorithms: </strong>Depending on the dataset, tree-based models or other methods may work better in high-dimensional settings.</p><p>The key lesson is that KNN needs meaningful neighborhoods. When distance no longer represents useful similarity, its predictions can deteriorate.</p><h4>9. Distance metrics: How does KNN define the nearest neighbor?</h4><p>KNN is a distance-based algorithm, so the distance metric directly influences which observations become neighbors.</p><p><strong>Euclidean distance</strong></p><p>Measures the straight-line distance between two points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*2z1UoAvv38Bhh1OQeyoDvA.png" /></figure><p>It is commonly used with numerical features.</p><p><strong>Manhattan distance</strong></p><p>Adds the absolute differences between the feature values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iggMMXwpTbk9-NxgCwu_gw.png" /></figure><p>It resembles travelling along grid-like streets rather than moving directly in a straight line.</p><p><strong>Minkowski distance</strong></p><p>Provides a general form of distance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PG6whsZpG5hOeKV9jEtjwQ.png" /></figure><p>When p=1, it becomes Manhattan distance. When p=2, it becomes Euclidean distance.</p><p><strong>Cosine similarity</strong></p><p>Compares the angle between two vectors rather than magnitude and is often useful for text representations and other sparse, high-dimensional data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjGuhaX7aU6LVCPuFSKzaA.png" /></figure><p>Cosine distance = 1 −cosine(x,y), subject to the chosen representation and its interpretation.</p><p>The right metric depends on the meaning of similarity, the feature types, and the data distribution. No single metric is best for every problem.</p><h4>10. Advantages and limitations of KNN</h4><p><strong>Advantages</strong></p><ul><li>Simple to understand and implement.</li><li>Supports both classification and regression.</li><li>Can capture nonlinear patterns without assuming a fixed functional relationship.</li><li>Makes few assumptions about the target relationship.</li><li>Provides a useful baseline for many supervised learning problems.</li></ul><p><strong>Limitations</strong></p><ul><li>Prediction can be computationally expensive on large datasets.</li><li>Requires memory to store training observations.</li><li>Is sensitive to feature scales and irrelevant features.</li><li>Can be affected by noisy observations and class imbalance.</li><li>Can perform poorly in high-dimensional spaces.</li><li>Depends on the choice of K, distance metric, and preprocessing.</li></ul><p>KNN is therefore not automatically the best model for every problem. Its performance depends on whether meaningful neighbors can be identified efficiently.</p><h4>11. Practical applications of KNN</h4><p>KNN can be applied wherever the similarity between observations provides useful information about their outcomes.</p><p><strong>Recommendation systems:</strong> Find similar users or items based on recorded preferences and characteristics.</p><p><strong>Healthcare research:</strong> Classify observations based on similarities in measured features, subject to rigorous validation and appropriate clinical oversight.</p><p><strong>Fraud detection:</strong> Identify transactions resembling previously labeled cases, provided the features capture meaningful similarities.</p><p><strong>Price prediction:</strong> Estimate house prices or product values by examining similar examples.</p><p><strong>Text classification:</strong> Categorize documents or messages based on feature representations that capture relevant similarities.</p><p>The effectiveness of KNN depends on the quality of the features and whether the chosen distance measure captures the similarities that matter for the task.</p><h4>12. KNN Implementation in Python</h4><p>K-Nearest Neighbors (KNN) can solve both classification and regression problems. Let’s implement each using Python’s scikit-learn library.</p><p><strong>Part 1: KNN Classification — Predicting Flower Species</strong></p><p>In classification, KNN predicts a category. We will use the Iris dataset to predict a flower’s species from its measurements.</p><p><strong>Step 1: Import the required libraries</strong></p><pre>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br>from sklearn.pipeline import make_pipeline<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.metrics import accuracy_score, classification_report</pre><p><strong>Step 2: Load the dataset</strong></p><pre>X, y = load_iris(return_X_y=True)</pre><ul><li>X contains four flower measurements: sepal length, sepal width, petal length, and petal width.</li><li>y contains the flower species labels.</li></ul><p><strong>Step 3: Split the dataset</strong></p><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.2,<br>    random_state=42,<br>    stratify=y<br>)</pre><p>Here, 80% of the observations are used for training and 20% for testing. The stratify=y argument helps preserve the class proportions in both sets.</p><p><strong>Step 4: Create and train the model</strong></p><pre>model = make_pipeline(<br>    StandardScaler(),<br>    KNeighborsClassifier(n_neighbors=5)<br>)<br>model.fit(X_train, y_train)</pre><ul><li>StandardScaler() standardizes the features because KNN relies on distance calculations.</li><li>KNeighborsClassifier(n_neighbors=5) uses five nearest neighbors to predict a flower&#39;s species.</li><li>make_pipeline() ensures the scaler is fitted on the training data before transforming the data for prediction.</li></ul><p>KNN stores the training observations and uses them to identify neighbors when making predictions.</p><p><strong>Step 5: Make predictions</strong></p><pre>y_pred = model.predict(X_test)</pre><p>For every test observation, KNN finds the five nearest training observations and predicts the species using their class labels.</p><p><strong>Step 6: Evaluate the model</strong></p><pre>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))<br>print(classification_report(y_test, y_pred))</pre><ul><li><strong>Accuracy</strong> measures the proportion of correct predictions.</li><li><strong>Precision</strong> measures how many predictions for a class were correct.</li><li><strong>Recall</strong> measures how many actual observations of a class were identified.</li><li><strong>F1-score</strong> balances precision and recall.</li></ul><p>The results depend on the data split and model settings.</p><p><strong>Part 2: KNN Regression — Predicting a Numerical Value</strong></p><p>In regression, KNN predicts a numerical value rather than a category.</p><p>For this example, we will use scikit-learn’s Diabetes dataset. It contains medical measurements, and the target represents a quantitative measure of disease progression.</p><p><strong>Step 1: Import the required libraries</strong></p><pre>from sklearn.datasets import load_diabetes<br>from sklearn.model_selection import train_test_split<br>from sklearn.pipeline import make_pipeline<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.neighbors import KNeighborsRegressor<br>from sklearn.metrics import mean_absolute_error</pre><p><strong>Step 2: Load the dataset</strong></p><pre>X, y = load_diabetes(return_X_y=True)</pre><ul><li>X contains the input features.</li><li>y contains numerical target values representing disease progression.</li></ul><p><strong>Step 3: Split the dataset</strong></p><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.2,<br>    random_state=42<br>)</pre><p>The dataset is divided into 80% training data and 20% testing data.</p><p><strong>Step 4: Create and train the regression model</strong></p><pre>model = make_pipeline(<br>    StandardScaler(),<br>    KNeighborsRegressor(n_neighbors=5)<br>)<br>model.fit(X_train, y_train)</pre><ul><li>StandardScaler() standardizes the features so that their scales do not disproportionately influence distances.</li><li>KNeighborsRegressor(n_neighbors=5) predicts a numerical value using the five nearest neighbors.</li><li>make_pipeline() ensures the scaler is fitted on the training data only.</li></ul><p><strong>Step 5: Make predictions</strong></p><pre>y_pred = model.predict(X_test)</pre><pre>print(&quot;First five predictions:&quot;, y_pred[:5])</pre><p>For each test observation, KNN identifies the five nearest training observations and averages their target values to produce a numerical prediction.</p><p><strong>Step 6: Evaluate the model</strong></p><pre>mae = mean_absolute_error(y_test, y_pred)</pre><pre>print(&quot;Mean Absolute Error:&quot;, mae)</pre><p>Mean Absolute Error (MAE) measures the average absolute difference between actual and predicted values. A lower MAE generally indicates more accurate predictions on the evaluated dataset.</p><p>The exact result depends on the data split, preprocessing, and model settings.</p><h4>13. Final Takeaway: The Key Idea Behind KNN</h4><p>K-Nearest Neighbors (KNN) follows a simple idea: <strong>To predict something unknown, look at similar things you already know.</strong></p><p>It finds the K nearest observations and uses their information to make predictions. In classification, the neighbors vote for a class. In regression, their target values are averaged to estimate a number.</p><p>But choosing the nearest neighbors matters. The value of K, feature scaling, distance metric, and quality of the features all affect the prediction. Noise and too many dimensions can make finding useful neighbors difficult.</p><p><strong>“KNN makes predictions by learning from similar examples in the data. Instead of building a complex model, it finds the nearest neighbors and uses their information to predict the outcome.”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a15d9b1adb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Data Using Pandas: A Practical Guide]]></title>
            <link>https://medium.com/@niharikaponnam80/working-with-data-using-pandas-a-practical-guide-a15809f1e02f?source=rss-fcbbf1a0596d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15809f1e02f</guid>
            <dc:creator><![CDATA[Niharikaponnam]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 13:51:24 GMT</pubDate>
            <atom:updated>2026-10-06T13:51:24.607Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>From Data Understanding and Cleaning to Exploration and Insight Generation.</strong></p><p>In real-world Data Science, data rarely arrives in a perfectly organized form.</p><p>A dataset may contain:</p><ul><li>Missing values</li><li>Duplicate records</li><li>Incorrect data types</li><li>Inconsistent values</li><li>Outliers</li><li>Unnecessary columns</li><li>Different formats</li><li>Large numbers of records</li></ul><p>Before we can analyze such data, we need to understand and prepare it.</p><p>This is where <strong>Pandas</strong> becomes extremely useful.</p><p><strong>Pandas helps us load, inspect, clean, transform, analyze, and work with structured data using Python.</strong></p><p><strong>1. What Exactly Is Pandas?</strong></p><p><strong>Pandas</strong> is an open-source Python library widely used for:</p><ul><li>Data manipulation</li><li>Data cleaning</li><li>Data analysis</li><li>Data exploration</li><li>Data preprocessing</li><li>Working with structured data</li></ul><p>The name <strong>Pandas</strong> comes from the term <strong>Panel Data</strong>, which refers to multidimensional data.</p><p>Pandas is built on top of <strong>NumPy</strong>, but it provides convenient tools specifically for working with table-like data.</p><p><strong>Think of a simple table</strong></p><p>Imagine you have a student records table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*GhPZHpfaFU7nLfnezRps-A.png" /></figure><p>Instead of manually working with this table, Pandas allows us to load and manipulate it directly in Python.</p><p><strong>2. Why Is Pandas Important in Data Science?</strong></p><p>Imagine receiving a CSV file containing <strong>50,000 student records</strong>.</p><p>You may want to:</p><ol><li>Load the file</li><li>Understand its structure</li><li>Check missing values</li><li>Find duplicate records</li><li>Correct inconsistent values</li><li>Change data types</li><li>Filter specific students</li><li>Group students by department</li><li>Calculate average marks</li><li>Combine multiple datasets</li><li>Create new columns</li><li>Prepare the data for further analysis</li></ol><p>Doing all of this manually would be difficult.</p><p>Pandas provides simple operations for these tasks.</p><p><strong>A Simple Data Analysis Journey</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*ukyTlD_IU3X_g1TvzpeyUw.png" /></figure><p><strong>3. Installing Pandas</strong></p><p>If Pandas is not already installed, we can install it using:</p><pre>pip install pandas</pre><p>Then import it:</p><pre>import pandas as pd</pre><p><strong>Why do we write pd?</strong></p><p>pd is the commonly used short name, or alias, for Pandas.</p><p>Instead of:</p><pre>pandas.DataFrame()</pre><p>we normally write:</p><pre>pd.DataFrame()</pre><p>It makes our code shorter and easier to read.</p><p><strong>4. The Two Main Pandas Data Structures</strong></p><p>Pandas mainly works with two important data structures:</p><ol><li><strong>Series</strong></li><li><strong>DataFrame</strong></li></ol><p>Understanding these two makes the rest of Pandas much easier.</p><p><strong>5. Understanding a Pandas Series</strong></p><p>A <strong>Series</strong> is a one-dimensional labeled data structure.</p><p>The easiest way to understand it is:</p><p><strong><em>Series = one column of data</em></strong></p><p>For example:</p><pre>import pandas as pd</pre><pre>marks = pd.Series([85, 72, 91, 68, 88])<br>print(marks)</pre><p>Output:</p><pre>0    85<br>1    72<br>2    91<br>3    68<br>4    88<br>dtype: int64</pre><p>Here:</p><ul><li>0, 1, 2, 3, 4 are the indexes</li><li>85, 72, 91, 68, 88 are the values</li></ul><p><strong>Another example</strong></p><pre>temperatures = pd.Series([31, 33, 30, 29])</pre><p>This represents one variable:</p><pre>Temperature<br>31<br>33<br>30<br>29</pre><p>So, whenever you see a single column of labeled values, think of a <strong>Series</strong>.</p><p><strong>6. Understanding a DataFrame</strong></p><p>A <strong>DataFrame</strong> is a two-dimensional labeled data structure.</p><p>You can think of it as a complete table.</p><p>It is similar to:</p><ul><li>An Excel table</li><li>A SQL table</li><li>A database table</li></ul><p>For example:</p><pre>data = {<br>    &quot;Student&quot;: [&quot;Anu&quot;, &quot;Rahul&quot;, &quot;Meena&quot;],<br>    &quot;Age&quot;: [20, 21, 20],<br>    &quot;Marks&quot;: [85, 78, 92]<br>}</pre><pre>df = pd.DataFrame(data)</pre><pre>print(df)</pre><p>Output:</p><pre>Student  Age  Marks<br>0     Anu   20     85<br>1   Rahul   21     78<br>2   Meena   20     92</pre><p><strong>Easy way to remember</strong></p><pre>Series     → One column<br>DataFrame  → Complete table</pre><p><strong>7. Creating a DataFrame</strong></p><p>There are different ways to create a DataFrame.</p><p><strong>From a dictionary</strong></p><pre>df = pd.DataFrame({<br>    &quot;Product&quot;: [&quot;Laptop&quot;, &quot;Phone&quot;, &quot;Tablet&quot;],<br>    &quot;Price&quot;: [55000, 30000, 22000]<br>})</pre><p><strong>From a list</strong></p><pre>df = pd.DataFrame(<br>    [<br>        [&quot;Laptop&quot;, 55000],<br>        [&quot;Phone&quot;, 30000],<br>        [&quot;Tablet&quot;, 22000]<br>    ],<br>    columns=[&quot;Product&quot;, &quot;Price&quot;]<br>)</pre><p>The important idea is that Pandas can convert structured Python data into a table.</p><p><strong>8. Loading Data into Pandas</strong></p><p>In real projects, data usually comes from external files rather than being manually created.</p><p>Pandas provides simple functions for reading common file formats.</p><p><strong>Reading a CSV file</strong></p><pre>df = pd.read_csv(&quot;sales.csv&quot;)</pre><p><strong>Reading an Excel file</strong></p><pre>df = pd.read_excel(&quot;sales.xlsx&quot;)</pre><p><strong>Reading a JSON file</strong></p><pre>df = pd.read_json(&quot;sales.json&quot;)</pre><p>Once the data is loaded, we can start understanding it.</p><p><strong>9. First Understand the Data</strong></p><p>A common mistake is to load a dataset and immediately start cleaning it.</p><p>Before changing anything, we should first understand what is actually inside the dataset.</p><p>Some useful commands are:</p><pre>df.head()</pre><pre>df.tail()</pre><pre>df.shape</pre><pre>df.columns</pre><pre>df.info()</pre><pre>df.describe()</pre><p>Each one answers a different question about our data.</p><p><strong>10. Looking at the First Rows with head()</strong></p><p>The head() function displays the first five rows by default.</p><pre>df.head()</pre><p>We can also choose how many rows we want:</p><pre>df.head(15)</pre><p>This displays the first fifteen rows.</p><p><strong>Why is this useful?</strong></p><p>It gives us a quick idea about:</p><ul><li>What the columns contain?</li><li>How the values look?</li><li>Whether the data was loaded correctly?</li></ul><p><strong>11. Looking at the Last Rows with tail()</strong></p><p>The tail() function displays the last five rows by default.</p><pre>df.tail()</pre><p>We can also specify the number of rows:</p><pre>df.tail(8)</pre><p>This displays the final eight rows.</p><p>It is useful when we want to check the end of the dataset.</p><p><strong>12. Finding the Size of the Dataset with shape</strong></p><p>The shape attribute tells us how many rows and columns are present.</p><pre>df.shape</pre><p>Suppose the result is:</p><pre>(5000, 6)</pre><p>That means:</p><pre>5000 rows<br>6 columns</pre><p><strong>Important</strong></p><p>shape is an <strong>attribute</strong>, not a function.</p><p><strong>Correct:</strong></p><pre>df.shape</pre><p>Incorrect:</p><pre>df.shape()</pre><p><strong>13. Checking Column Names</strong></p><p>To see all the column names:</p><pre>df.columns</pre><p>For example:</p><pre>Index([&#39;Product&#39;, &#39;Category&#39;, &#39;Price&#39;, &#39;Quantity&#39;], dtype=&#39;object&#39;)</pre><p>This helps us understand what information the dataset contains.</p><p><strong>14. Understanding the Structure with info()</strong></p><p>The info() function gives us important structural information.</p><pre>df.info()</pre><p>It provides details such as:</p><ul><li>Column names</li><li>Number of non-null values</li><li>Data types</li><li>Memory usage</li></ul><p>For example:</p><pre>Product      5000 non-null object<br>Price        4970 non-null float64<br>Quantity     5000 non-null int64</pre><p>Here, we can immediately notice that Price does not have values for all 5000 rows.</p><p>That tells us that missing values may exist.</p><p><strong>15. Checking Data Types with dtypes</strong></p><p>To see the data type of every column:</p><pre>df.dtypes</pre><p>Example:</p><pre>Product      object<br>Price       float64<br>Quantity      int64</pre><p><strong>info() vs dtypes</strong></p><p>dtypes mainly tells us:</p><blockquote><em>What type of data does each column contain?</em></blockquote><p>info() gives us more structural information, including:</p><ul><li>Column names</li><li>Non-null counts</li><li>Data types</li><li>Memory usage</li></ul><p><strong>16. Getting a Statistical Summary with describe()</strong></p><p>For numerical columns, describe() gives us a useful statistical summary.</p><pre>df.describe()</pre><p>It commonly provides:</p><ul><li>Count</li><li>Mean</li><li>Standard deviation</li><li>Minimum</li><li>25th percentile</li><li>Median</li><li>75th percentile</li><li>Maximum</li></ul><p>This gives us a quick overview of the numerical data without calculating every statistic separately.</p><p><strong>17. Selecting One Column</strong></p><p>Suppose our DataFrame contains:</p><pre>Product<br>Price<br>Quantity<br>Category</pre><p>To select the <strong>Price</strong> column:</p><pre>df[&quot;Price&quot;]</pre><p>This returns a <strong>Series</strong>.</p><p>We can also write:</p><pre>df.Price</pre><p>But bracket notation is generally safer and more flexible, so it is commonly preferred.</p><p><strong>18. Selecting Multiple Columns</strong></p><p>To select more than one column:</p><pre>df[[&quot;Product&quot;, &quot;Price&quot;]]</pre><p>Notice the <strong>double square brackets</strong>.</p><p>Why?</p><p>The outer brackets select from the DataFrame, while the inner brackets contain the list of columns we want.</p><p>Think of it as:</p><pre>df[<br>   [&quot;Product&quot;, &quot;Price&quot;]<br>]</pre><p><strong>19. Selecting Data with loc</strong></p><p>loc is mainly used for <strong>label-based selection</strong>.</p><p>For example:</p><pre>df.loc[0]</pre><p>This selects the row with label 0.</p><p>We can also select particular rows and columns:</p><pre>df.loc[0:3, [&quot;Product&quot;, &quot;Price&quot;]]</pre><p>This selects the specified rows and columns using their labels.</p><p><strong>20. Selecting Data with iloc</strong></p><p>iloc is used for <strong>position-based selection</strong>.</p><p>For example:</p><pre>df.iloc[0]</pre><p>This selects the first row based on its position.</p><p>We can also write:</p><pre>df.iloc[0:3]</pre><p>This selects rows from position 0 up to, but not including, position 3.</p><p><strong>Easy way to remember</strong></p><pre>loc  → labels<br>iloc → positions</pre><p><strong>21. Filtering Rows</strong></p><p>Filtering means selecting only the rows that satisfy a condition.</p><p>Suppose we want products whose price is greater than ₹20,000.</p><p>First:</p><pre>df[&quot;Price&quot;] &gt; 20000</pre><p>This produces a Boolean condition.</p><p>Then we use it to filter the DataFrame:</p><pre>df[df[&quot;Price&quot;] &gt; 20000]</pre><p>Now only products satisfying the condition are returned.</p><p><strong>Multiple conditions</strong></p><p>Suppose we want:</p><ul><li>Price greater than ₹20,000</li><li>Quantity greater than 5</li></ul><p>We can write:</p><pre>df[<br>    (df[&quot;Price&quot;] &gt; 20000) &amp;<br>    (df[&quot;Quantity&quot;] &gt; 5)<br>]</pre><p>Here &amp; means <strong>AND</strong>.</p><p>For OR:</p><pre>df[<br>    (df[&quot;Category&quot;] == &quot;Laptop&quot;) |<br>    (df[&quot;Category&quot;] == &quot;Tablet&quot;)<br>]</pre><p><strong>22. Creating a New Column</strong></p><p>Pandas makes it easy to create new columns from existing values.</p><p>Suppose we have a Price column and want to calculate the total value:</p><pre>df[&quot;Total_Value&quot;] = df[&quot;Price&quot;] * df[&quot;Quantity&quot;]</pre><p>Pandas performs the calculation for every row.</p><p>This is called a <strong>vectorized operation</strong>.</p><p>Instead of manually calculating each row, Pandas performs the operation across the entire column.</p><p><strong>23. Updating Existing Values</strong></p><p>We can also modify an existing column.</p><p>For example, suppose every product price needs to increase by ₹1,000:</p><pre>df[&quot;Price&quot;] = df[&quot;Price&quot;] + 1000</pre><p>For a 10% increase:</p><pre>df[&quot;Price&quot;] = df[&quot;Price&quot;] * 1.10</pre><p>The calculation is applied to every value in the column.</p><p><strong>24. Renaming Columns</strong></p><p>Sometimes column names are unclear or inconsistent.</p><p>We can rename them using rename().</p><pre>df.rename(<br>    columns={&quot;Price&quot;: &quot;Product_Price&quot;},<br>    inplace=True<br>)</pre><p>We can rename multiple columns at once:</p><pre>df.rename(<br>    columns={<br>        &quot;Product&quot;: &quot;Product_Name&quot;,<br>        &quot;Price&quot;: &quot;Product_Price&quot;<br>    },<br>    inplace=True<br>)</pre><p>Clear column names make the dataset easier to understand.</p><p><strong>25. Removing Unnecessary Columns</strong></p><p>If a column is not required, we can remove it.</p><pre>df.drop(&quot;Quantity&quot;, axis=1)</pre><p>Another way is:</p><pre>df.drop(columns=[&quot;Quantity&quot;])</pre><p>For multiple columns:</p><pre>df.drop(columns=[&quot;Quantity&quot;, &quot;Category&quot;])</pre><p><strong>What does axis mean?</strong></p><pre>axis=0 → rows<br>axis=1 → columns</pre><pre>axis=0 → rows<br>axis=1 → columns</pre><p><strong>26. Removing Rows</strong></p><p>We can remove a row using its index:</p><pre>df.drop(index=3)</pre><p>This removes the row whose index is 3.</p><p><strong>27. Understanding Missing Values</strong></p><p>Real-world datasets often contain missing information.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*5BXdTkqBQ46Z7oGCPDUCJg.png" /></figure><p>Here NaN represents a missing value.</p><p>Missing data needs to be identified before deciding how to handle it.</p><p><strong>28. Finding Missing Values</strong></p><p>To check where values are missing:</p><pre>df.isnull()</pre><p>This returns True wherever a value is missing.</p><p>To count missing values in each column:</p><pre>df.isnull().sum()</pre><p>We can also use:</p><pre>df.isna().sum()</pre><p>isnull() and isna() are effectively equivalent for detecting missing values.</p><p><strong>29. Removing Missing Values</strong></p><p>One option is to remove rows containing missing values:</p><pre>df.dropna()</pre><p>However, removing every row containing a missing value is not always the right decision.</p><p>Before doing so, we should consider:</p><ul><li>How much data is missing?</li><li>Which column contains the missing values?</li><li>How important that column is?</li><li>How large the dataset is?</li><li>Why the values are missing?</li></ul><p>The correct approach depends on the situation.</p><p><strong>30. Filling Missing Values</strong></p><p>Instead of removing missing values, sometimes we can replace them.</p><p>For numerical data, we can use the median:</p><pre>df[&quot;Age&quot;] = df[&quot;Age&quot;].fillna(df[&quot;Age&quot;].median())</pre><p>For categorical data, we can use the mode:</p><pre>df[&quot;Category&quot;] = df[&quot;Category&quot;].fillna(<br>    df[&quot;Category&quot;].mode()[0]<br>)</pre><p>A common starting point is:</p><pre>Numerical data   → Mean / Median<br>Categorical data → Mode</pre><p>But this is not a rule that should be blindly followed. The best choice depends on the dataset.</p><p><strong>31. Finding Duplicate Records</strong></p><p>Sometimes the same record appears more than once.</p><p>To identify duplicates:</p><pre>df.duplicated()</pre><p>To find the total number of duplicate rows:</p><pre>df.duplicated().sum()</pre><p>This helps us understand whether repeated records exist in our dataset.</p><p><strong>32. Removing Duplicate Records</strong></p><p>To remove duplicate rows:</p><pre>df.drop_duplicates()</pre><p>To modify the original DataFrame:</p><pre>df.drop_duplicates(inplace=True)</pre><p>Removing duplicates can prevent repeated records from affecting our analysis.</p><p><strong>33. Sorting Data</strong></p><p>We can sort a DataFrame using sort_values().</p><p>For example, to sort products by price:</p><pre>df.sort_values(&quot;Price&quot;)</pre><p>By default, the values are sorted in ascending order.</p><p>For descending order:</p><pre>df.sort_values(<br>    &quot;Price&quot;,<br>    ascending=False<br>)</pre><p>We can also sort using multiple columns:</p><pre>df.sort_values(<br>    [&quot;Category&quot;, &quot;Price&quot;],<br>    ascending=[True, False]<br>)</pre><p>This first sorts by category and then sorts the prices within each category in descending order.</p><p><strong>34. Finding Unique Values</strong></p><p>To see the different values present in a column:</p><pre>df[&quot;Category&quot;].unique()</pre><p>For example:</p><pre>[&#39;Laptop&#39;, &#39;Phone&#39;, &#39;Tablet&#39;, &#39;Watch&#39;]</pre><p>To find how many unique values exist:</p><pre>df[&quot;Category&quot;].nunique()</pre><p>This returns the number of distinct categories.</p><p><strong>35. Counting Categories with value_counts()</strong></p><p>value_counts() tells us how frequently each value appears.</p><p>For example:</p><pre>df[&quot;Category&quot;].value_counts()</pre><p>Output might be:</p><pre>Phone     420<br>Laptop    310<br>Tablet    180<br>Watch      90</pre><p>This tells us how many records belong to each category.</p><p>It is especially useful when analyzing categorical columns.</p><p><strong>36. Grouping Data with group by()</strong></p><p>Suppose an online store wants to know the average product price for each category.</p><p>We can use:</p><pre>df.groupby(&quot;Category&quot;)[&quot;Price&quot;].mean()</pre><p>The basic idea is:</p><pre>Group the data<br>      ↓<br>Perform a calculation<br>      ↓<br>Get a summary</pre><p>For example:</p><pre>Laptop     58000<br>Phone      29000<br>Tablet     21000</pre><p>This allows us to compare groups instead of looking at every individual record.</p><p><strong>37. Performing Multiple Aggregations</strong></p><p>We can calculate several statistics for each group.</p><pre>df.groupby(&quot;Category&quot;)[&quot;Price&quot;].agg(<br>    [&quot;mean&quot;, &quot;min&quot;, &quot;max&quot;, &quot;count&quot;]<br>)</pre><p>This gives us:</p><ul><li>Average price</li><li>Minimum price</li><li>Maximum price</li><li>Number of products</li></ul><p>for each category.</p><p><strong>38. Using agg() for Flexible Summaries</strong></p><p>The agg() function allows us to apply multiple aggregation functions.</p><p>For example:</p><pre>df[&quot;Price&quot;].agg(<br>    [&quot;mean&quot;, &quot;median&quot;, &quot;min&quot;, &quot;max&quot;]<br>)</pre><p>We can also create meaningful names for grouped results:</p><pre>df.groupby(&quot;Category&quot;).agg(<br>    Average_Price=(&quot;Price&quot;, &quot;mean&quot;),<br>    Highest_Price=(&quot;Price&quot;, &quot;max&quot;),<br>    Product_Count=(&quot;Price&quot;, &quot;count&quot;)<br>)</pre><p>This makes the resulting summary easier to understand.</p><p><strong>39. Applying Functions with apply()</strong></p><p>apply() allows us to apply a function to values.</p><p>For example:</p><pre>df[&quot;Price&quot;] = df[&quot;Price&quot;].apply(<br>    lambda x: x * 1.10<br>)</pre><p>This increases every price by 10%.</p><p>However, we should not automatically use apply() for every calculation.</p><p>When Pandas already provides a simple vectorized operation, that approach is often easier and faster.</p><p>For example:</p><pre>df[&quot;Price&quot;] = df[&quot;Price&quot;] * 1.10</pre><p>is simpler than using apply() for this particular task.</p><p><strong>40. Transforming Values with map()</strong></p><p>map() is useful when one value needs to be converted into another value.</p><p>Suppose a dataset contains:</p><pre>P<br>E<br>P<br>E</pre><p>where:</p><pre>P → Premium<br>E → Economy</pre><p>We can create a mapping:</p><pre>class_map = {<br>    &quot;P&quot;: &quot;Premium&quot;,<br>    &quot;E&quot;: &quot;Economy&quot;<br>}</pre><pre>df[&quot;Class&quot;] = df[&quot;Class&quot;].map(class_map)</pre><p>Now:</p><pre>P → Premium<br>E → Economy</pre><p>So, map() is useful when we have a direct relationship between one value and another.</p><p><strong>41. Replacing Values with replace()</strong></p><p>replace() is useful when we want to substitute specific values.</p><p>Suppose the same city appears in different forms:</p><pre>Blr<br>Blr.<br>Banglore</pre><p>We can standardize them:</p><pre>df[&quot;City&quot;] = df[&quot;City&quot;].replace({<br>    &quot;Blr&quot;: &quot;Banglore&quot;,<br>    &quot;Blr.&quot;: &quot;Banglore&quot;<br>})</pre><p>Now all three forms can be represented consistently as:</p><pre>Banglore</pre><p><strong>42. Changing Data Types</strong></p><p>Sometimes data is stored using the wrong data type.</p><p>For example, an age may be stored as text:</p><pre>&quot;21&quot;<br>&quot;25&quot;<br>&quot;30&quot;</pre><p>We can convert it into integers:</p><pre>df[&quot;Age&quot;] = df[&quot;Age&quot;].astype(int)</pre><p>For date values, we can use:</p><pre>df[&quot;Date&quot;] = pd.to_datetime(df[&quot;Date&quot;])</pre><p>Correct data types are important because they allow us to perform the appropriate operations on the values.</p><p><strong>43. Working with Date Values</strong></p><p>Once a column has been converted to datetime:</p><pre>df[&quot;Date&quot;] = pd.to_datetime(df[&quot;Date&quot;])</pre><p>we can extract useful information from it.</p><p><strong>Extract the year</strong></p><pre>df[&quot;Year&quot;] = df[&quot;Date&quot;].dt.year</pre><p><strong>Extract the month</strong></p><pre>df[&quot;Month&quot;] = df[&quot;Date&quot;].dt.month</pre><p><strong>Extract the day</strong></p><pre>df[&quot;Day&quot;] = df[&quot;Date&quot;].dt.day</pre><p><strong>Extract the day name</strong></p><pre>df[&quot;Day_Name&quot;] = df[&quot;Date&quot;].dt.day_name()</pre><p>This is useful when we want to analyze data based on time.</p><p><strong>44. Combining Multiple DataFrames</strong></p><p>In real projects, information may be stored in separate DataFrames.</p><p>For example:</p><ul><li>Customer information</li><li>Order information</li><li>Product information</li></ul><p>Pandas provides several ways to combine DataFrames:</p><ul><li>merge()</li><li>concat()</li><li>join()</li></ul><p><strong>45. Combining Related Tables with merge()</strong></p><p>merge() works similarly to a SQL JOIN.</p><p>Suppose we have two DataFrames.</p><p><strong>Customers</strong></p><pre>Customer_ID    Name<br>101            Anu<br>102            Ravi<br>103            Meena</pre><p><strong>Purchases</strong></p><pre>Customer_ID    Amount<br>101            5000<br>102            3200<br>103            4500</pre><p>We can combine them using their common column:</p><pre>result = pd.merge(<br>    customers,<br>    purchases,<br>    on=&quot;Customer_ID&quot;)</pre><p>Now the information from both DataFrames is combined.</p><p><strong>46. Different Types of merge()</strong></p><p>Pandas supports common join types:</p><pre>inner<br>left<br>right<br>outer</pre><p>For example:</p><pre>pd.merge(<br>    df1,<br>    df2,<br>    on=&quot;ID&quot;,<br>    how=&quot;inner&quot;<br>)</pre><p>The how parameter determines which matching or non-matching records are included.</p><p>If you already know SQL joins, merge() becomes much easier to understand.</p><p><strong>47. Combining DataFrames with concat()</strong></p><p>concat() is useful when we want to combine DataFrames along rows or columns.</p><p><strong>Combining rows</strong></p><p>Suppose we have:</p><pre>January sales<br>February sales<br>March sales</pre><p>We can combine them:</p><pre>result = pd.concat(<br>    [january, february, march]<br>)</pre><p>This places the rows one after another.</p><p><strong>Combining columns</strong></p><p>We can also combine DataFrames side by side:</p><pre>result = pd.concat(<br>    [df1, df2],<br>    axis=1<br>)</pre><p>So:</p><pre>axis=0 → combine vertically<br>axis=1 → combine horizontally</pre><p><strong>48. Summarizing Data with pivot_table()</strong></p><p>A pivot table helps us summarize data across categories.</p><p>Suppose we want to understand sales by city and product:</p><pre>pd.pivot_table(<br>    df,<br>    values=&quot;Sales&quot;,<br>    index=&quot;City&quot;,<br>    columns=&quot;Product&quot;,<br>    aggfunc=&quot;sum&quot;<br>)</pre><p>This creates a summary showing sales for different products across different cities.</p><p>It is similar to creating a Pivot Table in Excel.</p><p><strong>49. Comparing Categories with crosstab()</strong></p><p>pd.crosstab() is useful when we want to see the frequency relationship between two categorical variables.</p><p>For example:</p><pre>pd.crosstab(<br>    df[&quot;Membership&quot;],<br>    df[&quot;Product&quot;]<br>)</pre><p>This can tell us how many Basic, Standard, and Premium members purchased each product.</p><p>It is useful for understanding relationships between categories.</p><p><strong>50. Basic Statistical Operations</strong></p><p>Pandas provides many functions for statistical analysis.</p><p><strong>Mean</strong></p><pre>df[&quot;Marks&quot;].mean()</pre><p><strong>Median</strong></p><pre>df[&quot;Marks&quot;].median()</pre><p><strong>Mode</strong></p><pre>df[&quot;Marks&quot;].mode()</pre><p><strong>Minimum</strong></p><pre>df[&quot;Marks&quot;].min()</pre><p><strong>Maximum</strong></p><pre>df[&quot;Marks&quot;].max()</pre><p><strong>Standard deviation</strong></p><pre>df[&quot;Marks&quot;].std()</pre><p><strong>Variance</strong></p><pre>df[&quot;Marks&quot;].var()</pre><p>These functions help us understand the distribution and characteristics of numerical data.</p><p><strong>51. Understanding Correlation</strong></p><p>Correlation helps us understand the strength and direction of a linear relationship between numerical variables.</p><p>We can calculate it using:</p><pre>df.corr(numeric_only=True)</pre><p>For example, suppose we compare:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*yoqy22lEk6lMP98WB9UFeA.png" /></figure><p>If students who practice more generally score higher, the two variables may have a positive correlation.</p><p>However, an important point is:</p><p><strong>Correlation does not mean causation.</strong></p><p>A relationship between two variables does not automatically prove that one caused the other.</p><p><strong>52. Finding Outliers Using IQR</strong></p><p>An outlier is a value that is unusually far from the rest of the data.</p><p>One common way to identify outliers is the <strong>IQR method</strong>.</p><p>First calculate Q1:</p><pre>Q1 = df[&quot;Marks&quot;].quantile(0.25)</pre><p>Then Q3:</p><pre>Q3 = df[&quot;Marks&quot;].quantile(0.75)</pre><p>Calculate the IQR:</p><pre>IQR = Q3 - Q1</pre><p>Now calculate the boundaries:</p><pre>lower = Q1 - 1.5 * IQR</pre><pre>upper = Q3 + 1.5 * IQR</pre><p>Finally, identify the outliers:</p><pre>outliers = df[<br>    (df[&quot;Marks&quot;] &lt; lower) |<br>    (df[&quot;Marks&quot;] &gt; upper)]</pre><p>The values outside these boundaries are considered potential outliers.</p><p><strong>53. Should Every Outlier Be Removed?</strong></p><p>No.</p><p>An unusual value is not automatically an incorrect value.</p><p>Imagine the following delivery times:</p><pre>25 minutes<br>28 minutes<br>30 minutes<br>32 minutes<br>35 minutes<br>180 minutes</pre><p>The 180 minutes value looks unusual.</p><p>But maybe that delivery actually took longer because of a major traffic problem.</p><p>Therefore, we should investigate an outlier before deciding what to do with it.</p><p>Possible decisions include:</p><ul><li>Keep it</li><li>Remove it</li><li>Cap it</li><li>Transform it</li></ul><p>The correct decision depends on the context.</p><p><strong>54. Standardizing Inconsistent Values</strong></p><p>Real-world categorical data can contain different representations of the same value.</p><p>For example:</p><pre>Banglore<br>banglore<br>Banglore<br>blr</pre><p>These may all represent the same city.</p><p>One simple way to standardize text is:</p><pre>df[&quot;City&quot;] = df[&quot;City&quot;].str.strip().str.lower()</pre><p>Now:</p><pre>Banglore → banglore<br>BANGLORE  → banglore<br>banglore → banglore</pre><p>The values become consistent.</p><p><strong>55. Working with Text Using String Operations</strong></p><p>Pandas provides several useful string operations.</p><p><strong>Convert text to lowercase</strong></p><pre>df[&quot;Customer_Name&quot;].str.lower()</pre><p><strong>Convert text to uppercase</strong></p><pre>df[&quot;Customer_Name&quot;].str.upper()</pre><p><strong>Remove unnecessary spaces</strong></p><pre>df[&quot;Customer_Name&quot;].str.strip()</pre><p><strong>Check whether text contains a value</strong></p><pre>df[&quot;Customer_Name&quot;].str.contains(<br>    &quot;Raj&quot;,<br>    na=False<br>)</pre><p><strong>Replace text</strong></p><pre>df[&quot;Customer_Name&quot;].str.replace(<br>    &quot;Mr.&quot;,<br>    &quot;&quot;,<br>    regex=False<br>)</pre><p>These operations are useful when cleaning and standardizing text data.</p><p><strong>56. Filtering with query()</strong></p><p>There is another convenient way to filter rows.</p><p>Instead of:</p><pre>df[df[&quot;Marks&quot;] &gt; 80]</pre><p>we can write:</p><pre>df.query(&quot;Marks &gt; 80&quot;)</pre><p>For multiple conditions:</p><pre>df.query(<br>    &quot;Marks &gt; 80 and Attendance &gt; 75&quot;<br>)</pre><p>query() provides a more readable way to write certain filtering conditions.</p><p><strong>57. Working with Large Files</strong></p><p>Some datasets can contain hundreds of thousands or even millions of records.</p><p>Loading an entire large file into memory at once may consume significant memory.</p><p>Pandas allows us to read the data in smaller chunks.</p><pre>for chunk in pd.read_csv(<br>    &quot;large_sales.csv&quot;,<br>    chunksize=10000<br>):<br>    print(chunk.shape)</pre><p>Here, Pandas reads the file in groups of <strong>10,000 rows at a time</strong>.</p><p>This allows us to work with large files in smaller portions.</p><p><strong>58. Saving the Processed Data</strong></p><p>After cleaning or transforming our dataset, we may want to save the result.</p><p><strong>Save as CSV</strong></p><pre>df.to_csv(<br>    &quot;cleaned_sales.csv&quot;,<br>    index=False<br>)</pre><p><strong>Save as Excel</strong></p><pre>df.to_excel(<br>    &quot;cleaned_sales.xlsx&quot;,<br>    index=False<br>)</pre><p><strong>Save as JSON</strong></p><pre>df.to_json(&quot;sales.json&quot;)</pre><p>Why index=False ?</p><p>By default, Pandas may save the DataFrame index as an additional column.</p><p>Using:</p><pre>index=False</pre><p>prevents that index from being written into the file.</p><p><strong>59. Putting Pandas into a Real Example</strong></p><p>Let’s imagine an online bookstore wants to understand its order data.</p><p>The dataset contains information such as:</p><pre>Book<br>Category<br>Price<br>Rating<br>City</pre><p>Let’s see how Pandas can take us from raw data to a cleaned dataset.</p><p><strong>Step 1: Load the Data</strong></p><pre>import pandas as pd</pre><pre>df = pd.read_csv(&quot;book_orders.csv&quot;)</pre><p><strong>Step 2: Understand</strong></p><pre>df.head()<br>df.shape<br>df.info()<br>df.describe()</pre><p>Before making changes, we now have an idea about the structure and numerical values.</p><p><strong>Step 3: Check Missing Values</strong></p><pre>df.isnull().sum()</pre><p>Suppose Rating contains some missing values.</p><p>We can fill them using the median:</p><pre>df[&quot;Rating&quot;] = df[&quot;Rating&quot;].fillna(<br>    df[&quot;Rating&quot;].median())</pre><p><strong>Step 4: Check for Duplicate Records</strong></p><pre>df.duplicated().sum()</pre><p>Suppose we find duplicate rows.</p><p>We can remove them:</p><pre>df.drop_duplicates(inplace=True)</pre><p><strong>Step 5: Understand the Categories</strong></p><pre>df[&quot;Category&quot;].value_counts()</pre><p>This tells us which book categories occur most frequently.</p><p><strong>Step 6: Calculate Average Price by Category</strong></p><pre>df.groupby(&quot;Category&quot;)[&quot;Price&quot;].mean()</pre><p>Now we can compare the average book price across categories.</p><p><strong>Step 7: Find Highly Rated Books</strong></p><p>Suppose we want books with a rating above 4.5:</p><pre>df[df[&quot;Rating&quot;] &gt; 4.5]</pre><p>This filters the dataset according to our requirement.</p><p><strong>Step 8: Create a Discounted Price</strong></p><p>Suppose the bookstore wants to offer a 15% discount.</p><pre>df[&quot;Discounted_Price&quot;] = df[&quot;Price&quot;] * 0.85</pre><p>Pandas calculates the discounted price for every row.</p><p><strong>Step 9: Save the Cleaned Dataset</strong></p><pre>df.to_csv(<br>    &quot;cleaned_book_orders.csv&quot;,<br>    index=False<br>)</pre><p>Our cleaned and transformed data is now ready for further use.</p><p>It can be used for:</p><ul><li>Visualization</li><li>Reports</li><li>Dashboards</li><li>Business analysis</li><li>Machine Learning</li></ul><p><strong>60. Pandas and NumPy: What’s the Difference?</strong></p><p>Both Pandas and NumPy are important Python libraries, but they are commonly used for different purposes.</p><p><strong>NumPy</strong></p><p>Primarily works with:</p><ul><li>Numerical data</li><li>Arrays</li><li>Mathematical operations</li></ul><p><strong>Pandas</strong></p><p>Primarily works with:</p><ul><li>Tables</li><li>Rows and columns</li><li>Data cleaning</li><li>Data manipulation</li><li>Data analysis</li></ul><p><strong>Easy way to remember</strong></p><pre>NumPy  → Numerical arrays<br>Pandas → Structured/tabular data</pre><p>Pandas itself uses NumPy internally for many numerical operations.</p><p><strong>61. Common Mistakes to Avoid</strong></p><p><strong>Mistake 1: Forgetting double brackets</strong></p><p>Wrong:</p><pre>df[&quot;Product&quot;, &quot;Price&quot;]</pre><p>Correct:</p><pre>df[[&quot;Product&quot;, &quot;Price&quot;]]</pre><p><strong>Mistake 2: Treating shape like a function</strong></p><p>Wrong:</p><pre>df.shape()</pre><p>Correct:</p><pre>df.shape</pre><p>Mistake 3: Mixing up loc and iloc</p><p>Remember:</p><pre>loc  → label<br>iloc → position</pre><p><strong>Mistake 4: Assuming every operation changes the original DataFrame</strong></p><p>For example:</p><pre>df.drop_duplicates()</pre><p>returns a DataFrame with duplicates removed, but it does not necessarily modify the original df.</p><p>We can instead write:</p><pre>df = df.drop_duplicates()</pre><p>or:</p><pre>df.drop_duplicates(inplace=True)</pre><p><strong>Mistake 5: Treating missing values as zero</strong></p><p>A missing value does not automatically mean:</p><pre>0</pre><p>Missing means that the value is unavailable or unknown.</p><p>The correct treatment depends on what the column represents and why the value is missing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*mNV52TbaV5Y95LhqRqLPgg.png" /></figure><p>Pandas plays a major role in the early stages of this workflow.</p><p>It helps us move from a raw dataset to data that we can understand and work with.</p><p><strong>What We Learned</strong></p><p>Pandas is not simply a library for opening CSV files.</p><p>It gives us a practical way to work with real-world structured data.</p><p>We may begin with:</p><p>“I have a dataset, but I don’t know what’s inside it.”</p><p>and gradually reach:</p><p>“I understand the data, cleaned it, analyzed it, and can extract useful information from it.”</p><p>Pandas helps us make that journey.</p><p>Instead of trying to memorize every function, focus on understanding <strong>what problem each operation solves</strong>:</p><ul><li>Need to inspect the data? → head(), tail(), info(), shape, describe()</li><li>Need to select columns or rows? → [ ], loc, iloc</li><li>Need to filter records? → Boolean conditions, query()</li><li>Need to create or modify columns? → Assignment and vectorized operations</li><li>Need to rename or remove data? → rename(), drop()</li><li>Need to handle missing values? → isnull(), dropna(), fillna()</li><li>Need to find duplicates? → duplicated(), drop_duplicates()</li><li>Need category information? → unique(), nunique(), value_counts</li><li>Need group-level analysis? → groupby(), agg()</li><li>Need to transform individual values? → map(), replace()</li><li>Need to work with dates? → to_datetime(), .dt</li><li>Need to combine tables? → merge()</li><li>Need to combine datasets? → concat()</li><li>Need summary tables? →pivot_table(), crosstab()</li><li>Need statistics? → mean(), median(), mode(), std(), var(), corr()</li><li>Need to investigate unusual values? → IQR</li><li>Need to work with text? → .str</li><li>Need to handle large files? → chunksize</li><li>Need to save the result? → to_csv(), to_excel(), to_json()</li></ul><p>The goal is not to memorize Pandas.</p><p>The goal is to understand <strong>how Pandas helps us turn raw data into information we can actually use.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15809f1e02f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Preprocessing in NLP: Bag of Words (BoW) and TF-IDF]]></title>
            <link>https://medium.com/@niharikaponnam80/text-preprocessing-in-nlp-bag-of-words-bow-and-tf-idf-98567bec87d0?source=rss-fcbbf1a0596d------2</link>
            <guid isPermaLink="false">https://medium.com/p/98567bec87d0</guid>
            <dc:creator><![CDATA[Niharikaponnam]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 08:05:05 GMT</pubDate>
            <atom:updated>2026-10-03T08:05:05.322Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Imagine you are asked to read 10,000 movie reviews by tomorrow morning and sort them into “loved it” and “hated it.” You would need coffee, a free weekend and a lot of patience.</em></p><p>A computer can do it in seconds, yet it begins with a handicap. When you read “The movie was not good,” you feel the disappointment at once. The machine sees only a string of characters. It does not know that “not” flips the meaning, that “good” is praise, or that a smiley at the end means the writer enjoyed it.</p><p><strong>So how do we get from messy human language to something a machine can calculate with?</strong></p><p>The answer is a quiet, careful craft that sits behind search engines, spam filters, recommendation systems and sentiment dashboards. It starts with cleaning the text, continues by turning words into numbers, and the choices made along the way decide whether a model learns something useful or something misleading.</p><p>This article walks through that journey from start to finish, using one running example: movie reviews.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kgsCLDevwjwX-cMQw1REg.png" /></figure><h3><strong>Why machines need preprocessing?</strong></h3><p>People express opinions in text every day, and a human reader instantly feels the difference between these two reviews:</p><p><em>“The movie was an absolute masterpiece! The performances were outstanding, and I would definitely watch it again. 😊”</em></p><p><em>“The story was disappointing, and the performances were weak. I would never recommend this movie. 😞”</em></p><p>A traditional machine-learning algorithm cannot. It operates on numbers, not sentences. <strong>Text preprocessing</strong> cleans and standardizes raw text so that useful information survives the conversion, and techniques such as <strong>Bag of Words (BoW)</strong> and <strong>TF-IDF</strong> then turn the result into numeric features.</p><p>We will follow one running example, movie-review sentiment analysis, from raw sentence to numeric vector.</p><h3>What is text preprocessing?</h3><p>Raw text is messy. It can contain inconsistent capitalization, URLs, email addresses, punctuation, numbers, special characters, emojis, filler words, and many forms of the same word.</p><p>Consider:</p><p><em>“WOW!!! This movie was AMAZING!!! Watch it here: </em><a href="https://movie.example.com/"><em>https://movie.example.com</em></a><em> 😊”</em></p><p>The goal is not to delete as much as possible. The goal is to <strong>reduce meaningless variation while preserving the signal the task needs</strong>. Every transformation should have a reason.</p><p><strong>Preprocessing depends on the task</strong></p><p>There is no universal recipe. For sentiment analysis, words like <strong>excellent</strong>, <strong>masterpiece</strong> and <strong>outstanding</strong> are strong positive signals, while <strong>disappointing, weak</strong> and <strong>never </strong>point the other way. Keep what helps the model; transform what does not.</p><h3>Cleaning steps</h3><p><strong>Lowercasing</strong></p><p>Without normalization, Movie, movie and MOVIE become three vocabulary entries. Lowercasing merges them into movie. Capitalization can matter in tasks such as named-entity recognition(NER), Google being capitalized can help identify it as a company name. But for <strong>sentiment analysis</strong>, capitalization usually isn’t the main information we need, so converting everything to lowercase is generally useful.</p><p><strong>Removing URLs and email addresses</strong></p><p>A link or contact address rarely says anything about whether a review is positive. A common URL pattern is:</p><pre>r&#39;https?://\S+|www\.\S+&#39;</pre><p>Here <strong>https?</strong> matches http or https,<strong> ://</strong> is the separator, <strong>\S+</strong> matches non-whitespace characters, and <strong>www\.\S+</strong> catches addresses starting with www. If the task were detecting promotional or malicious links, however, removing URLs would destroy exactly the signal you need.</p><p><strong>Punctuation, numbers, special characters and emojis</strong></p><p>Take the review “This movie was AMAZING!!! 10/10 — absolutely loved it 😊”. Each element needs a decision:</p><ul><li><strong>Punctuation:</strong> usually removable, but repeated exclamation marks can signal emphasis.</li><li><strong>Numbers:</strong> a rating such as 10/10 may help or may be noise. In financial text, numbers are essential.</li><li><strong>Special characters</strong> (@, #, %, $, %, &amp;): evaluate whether they carry meaning in your dataset before removing them.</li><li><strong>Emojis:</strong> 😊 and 😞 communicate emotion directly. Rather than deleting them, consider keeping them or converting them into words.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slli-yPLJQ3uHADzBR8MWg.png" /><figcaption>Each cleaning step transforms the same review. The final form, “wow this movie was amazing watch it her 😊”, depends on your task.</figcaption></figure><h3>Tokenization</h3><p>After cleaning, text is split into smaller units called <strong>tokens</strong>. The sentence “The movie was a masterpiece with outstanding performances.”</p><p>becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*Me0DWpMHUCdoR-_BovJfag.png" /></figure><p>For BoW and TF-IDF, these word-level tokens form the vocabulary.</p><h3>Stop words and why negation matters</h3><p>Stop words are very frequent words such as <strong>the, is, was, a, of, to </strong>and <strong>in</strong>. Removing them can shrink the feature space with little loss. The sentence above becomes roughly <strong>movie masterpiece outstanding performances.</strong></p><p><strong>⚠️ Careful with negation.</strong> Many stop-word lists include no, not, never, neither and nor. Removing “never” from “I would never recommend this movie” gives “I would recommend this movie”. Removing “not” from “The movie is not excellent” gives “The movie is excellent”. The sentiment flips. For sentiment tasks, customize the list and keep negation words.</p><h3>Stemming and lemmatization</h3><p>Words come in many forms: perform, performed, performing, performances. Normalizing them reduces vocabulary variation.</p><p><strong>Stemming</strong> chops word endings using heuristic rules, so results need not be real words:</p><pre>playing → play<br>played  → play<br>studies → studi</pre><p><strong>Lemmatization</strong> uses linguistic knowledge to return the dictionary form:</p><pre>am, is, are → be<br>running     → run<br>better      → good</pre><p>Results depend on the tool and the grammatical context provided. You normally choose one approach, not both, and you should test the choice, because over-normalizing can erase distinctions that matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaMgi_3ljNWoyQeiID3OmQ.png" /></figure><h3>Why text must become numbers?</h3><p>After cleaning we might have movie, masterpiece, outstanding performance. An algorithm still cannot compute with words. “We need a vocabulary built from the training reviews, with each word represented as a numerical feature.” Two classical approaches do this, and they differ in how they value each word.</p><h3>1. Bag of Words (BoW)</h3><p>BoW represents a document by <strong>which words occur and how often</strong>. Imagine three reviews: “The movie was a masterpiece.” (1), “The movie was disappointing.” (2), and “The movie was a masterpiece.” (3). Each vocabulary term becomes a column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHUQufRlD8wDhxI5CzJVAg.png" /></figure><p>A word appearing once scores 1; a word appearing twice scores 2; an absent word scores 0.</p><h3>The BoW vector representation</h3><p>Each row of the table is the review’s <strong>vector representation</strong>: an ordered list of counts, one slot per vocabulary word. With the vocabulary order [the, movie, was, a, masterpiece, dissapointing]:</p><pre>Review 1 → [1, 1, 1, 1, 1, 0]<br>Review 2 → [1, 1, 1, 0, 0, 1]<br>Review 3 → [1, 1, 1, 1, 1, 0]</pre><p>Reviews 1 and 3 have identical vectors because they contain identical words. Review 2 differs in exactly the two positions that carry the sentiment. This is what a classifier actually receives: not sentences, but rows of numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7viNu6X0f-9ksi8lJHlGQA.png" /></figure><h3>Limitations of Bag of Words</h3><p><strong>Lost word order</strong></p><p>“The movie is not excellent” and “The movie is excellent” contain almost the same words, but their meanings differ because “not” modifies “excellent.” Basic BoW represents these words as separate features and does not explicitly capture this relationship between them.</p><p><strong>High dimensionality</strong></p><p>With 100,000 unique terms, every review becomes a vector of 100,000 features. That large feature space is called high dimensionality.</p><p><strong>Sparsity</strong></p><p>Dimensionality counts features; sparsity measures how many values are zero. A review with 30 distinct terms in a 100,000-term vocabulary has about 99,970 zeros.</p><pre>[0, 0, 1, 0, 0, 0, 0, 1, 0, ...]</pre><p><strong>Frequency is not importance</strong></p><p>Words like movie, film, and story may appear frequently across reviews. Basic BoW treats each word as a separate feature without giving different importance based on how common it is across reviews. <strong>TF-IDF addresses this by giving lower weight to common words and higher weight to more specific words.</strong></p><h3>TF-IDF: looking beyond counts</h3><p><strong>Term Frequency–Inverse Document Frequency </strong>weighs a word using two questions:</p><p><strong>How often does it appear in this document?</strong></p><p><strong>How common is it across the whole collection?</strong></p><p>A word that is frequent in one review but rare overall is more <em>statistically distinctive</em> for that review. For example, movie appears nearly everywhere, whereas cinematography appears in far fewer reviews.</p><h3>Term frequency (TF)</h3><p>TF measures how large a share of a document a term occupies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*MEiFstUvvzKrmV1jS0k3eA.png" /></figure><p>If a 100-term review contains “masterpiece” 3 times, TF = 3/100 = 0.03.</p><p>f(t,d)-&gt; number of times term t appears in document d<br>here t means word.</p><h3>Inverse document frequency (IDF)</h3><p>IDF measures how rare a term is across all documents:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*eeryNfhkX7I3994XCav2nw.png" /></figure><p>where N is the number of documents and df(t) is the number containing the term. With 1,000 reviews, movie in 900 gives log(1000/900), a small value. cinematography in 50 gives log(1000/50), a much larger one. Common terms get low IDF; rare terms get high IDF.</p><h3>Putting it together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*81ARgVPSS39GRKMUoh5zEQ.png" /></figure><p>A word that appears frequently within a review but is uncommon across all documents receives a higher TF-IDF score. Libraries may use variations such as smoothing and normalization, but the basic principle remains the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TmEH8opJSqMPTZUD9lcYkQ.png" /></figure><h3>BoW and TF-IDF on real reviews</h3><p><strong>Review A 😊:</strong> “The movie was a masterpiece with outstanding performances and beautiful cinematography.”<br><strong>Review B 😞:</strong> “The movie was disappointing, with weak performances and predictable writing.”</p><p>BoW records which terms occur and their counts. TF-IDF goes further: movie has high document frequency, so it is down-weighted, while cinematography is rarer, so it receives more weight in Review A. This does <em>not</em> mean TF-IDF knows that cinematography relates to filmmaking. It only flags the term as distinctive within the collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iumiH7tTGk_bweXco8SItg.png" /></figure><h3>What BoW and TF-IDF do not understand</h3><p>Both convert text into numerical features, but neither truly understands language. For example, <strong>“The movie is excellent”</strong> and <strong>“The movie is not excellent”</strong> contain similar words, but these methods do not explicitly understand the relationship between not and excellent. Similarly, <strong>“outstanding”</strong> and <strong>“exceptional”</strong> are treated as separate features even though they have similar meanings. A rare meaningless term such as <strong>excelllent</strong> can also receive a high TF-IDF weight simply because it is uncommon. BoW and TF-IDF are statistical feature-extraction methods, not methods that understand language semantics or context.</p><h3>Limitations to keep in mind</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRjBO0JG0u3q3pTlzm8RWg.png" /></figure><p>Classical text-feature methods can convert text into useful numerical features, but they have limited ability to preserve word order, understand context and semantics, handle unseen vocabulary, and distinguish meaningful information from noise.</p><h3>Common mistakes to avoid</h3><ol><li><strong>Assuming BoW understands sentences.</strong> It keeps counts, not grammar or order.</li><li><strong>Assuming TF-IDF understands meaning.</strong> A high score means distinctive, not meaningful.</li><li><strong>Treating every rare word as valuable.</strong> A typo like <strong>masterpeic</strong>e is rare, so its IDF is high, yet it is useless.</li><li><strong>Removing negation carelessly.</strong> Turning “not excellent” into “excellent” reverses the label.</li><li><strong>Fitting the vectorizer on the whole dataset.</strong> This leaks test information into your features.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oO9IQRhrKEtOm6OX-YM62w.png" /></figure><p>Data Leakage: The test data is supposed to represent completely unseen data. If we use the test data while learning the vocabulary, IDF, scaling parameters, etc., we are giving the model information about the test set before evaluating it. That is called data leakage.</p><h3>The full journey for one review</h3><p><strong>Original:</strong> “WOW!!! This movie was an absolute MASTERPIECE! The performances were outstanding, and I would definitely watch it again. 😊”</p><ol><li><strong>Lowercase and clean:</strong> “wow this movie was an absolute masterpiece the performances were outstanding and i would definitely watch it again 😊”. The emoji treatment depends on your strategy.</li><li><strong>Tokenize:</strong> wow, this, movie, was, an, absolute, masterpiece, the, performances, were, outstanding, and, i, would, definitely, watch, it, again.</li><li><strong>Task-specific stop words:</strong> keep wow movie absolute masterpiece performances outstanding definitely watch again.</li><li><strong>Normalize:</strong> lemmatization maps performances to performance; stemming may give a different form.</li><li><strong>Vectorize: </strong>BoW yields word counts, while TF-IDF weights words according to their frequency in a document and their rarity across all documents.</li></ol><h3>BoW versus TF-IDF at a glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YijgKspggFZjvqMlCo2j2Q.png" /></figure><h3>🌟 Final takeaway</h3><p>Preprocessing is the foundation of traditional NLP pipelines, but it works best when guided by purpose. In our movie-review example we considered capitalization, URLs, emails, punctuation, numbers, emojis, tokenization, stop words and word normalization before building numeric features.</p><p><strong>BoW tells you how words occur in a document. TF-IDF tells you how strongly a word characterizes a document relative to the wider collection.</strong> Neither understands language the way people do, so their results depend on preprocessing choices that preserve what your problem actually needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98567bec87d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Preprocessing: Speaking the Model’s Language]]></title>
            <link>https://medium.com/@niharikaponnam80/data-preprocessing-speaking-the-models-language-c15835bb3aae?source=rss-fcbbf1a0596d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c15835bb3aae</guid>
            <dc:creator><![CDATA[Niharikaponnam]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 08:19:49 GMT</pubDate>
            <atom:updated>2026-10-02T08:19:49.729Z</atom:updated>
            <content:encoded><![CDATA[<p>Think about the process of preparing a vegetable curry.</p><p>The ingredients may already be available: vegetables, onions, tomatoes, spices, and oil. However, having the ingredients available is not the same as having them ready for the cooking process.</p><p>The vegetables are <strong>cleaned and rinsed thoroughly</strong>, unwanted portions are <strong>trimmed</strong>, and they are <strong>chopped into appropriate sizes</strong>. Other ingredients are prepared and measured before they are added to the pan.</p><p>None of these steps represents the actual cooking process.</p><p>Yet, each step plays an important role in <strong>preparing the ingredients for what comes next</strong>.</p><p>Data in a machine learning project follows a similar principle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gyc4wgMIrbkMPdqiN3kBLQ.png" /></figure><p>A dataset may already contain valuable information, but having useful information does not automatically mean that the dataset is ready for a machine learning algorithm.</p><p>Consider a dataset containing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*y9ViNzLdJG737XznVkCTzA.png" /></figure><p>A human can interpret this information immediately.</p><p>We understand that <strong>Hyderabad, Chennai, and Mumbai</strong> represent different cities. We recognize that <strong>Bachelor’s, Master’s, and PhD</strong> represent different education levels. We can also compare an annual income of 45,000 with 1,20,000.</p><p>A machine learning algorithm, however, does not interpret these values through human understanding. It operates on numerical representations and mathematical relationships.</p><p>This creates an important question:</p><p><strong>How should the information be represented before the model learns from it?</strong></p><p>The answer begins with <strong>Data Preprocessing</strong>.</p><p>Data preprocessing is the process of transforming raw data into a form that is appropriate for analysis and machine learning. Depending on the dataset and the algorithm, this may involve handling missing values, correcting inconsistencies, encoding categorical variables, scaling numerical features, and performing other necessary transformations.</p><p>Among these steps, two important techniques for preparing features are <strong>Encoding</strong> and <strong>Feature Scaling</strong>.</p><p>Encoding addresses a question such as:</p><p><strong>How can categorical information such as a city, department, or product type be represented numerically while preserving its meaning?</strong></p><p>Feature Scaling addresses a different question:</p><p><strong>What should we do when numerical features such as age, income, and transaction amount exist on significantly different scales?</strong></p><p>These may appear to be simple transformations, but the reasoning behind them is important.</p><p>A preprocessing technique should not be applied merely because it is commonly used. We first need to understand the nature of the feature, the information it represents, and the requirements of the algorithm.</p><p>That is where effective data preprocessing begins.</p><p>In this article, we will explore <strong>Encoding and Feature Scaling</strong> step by step, using practical examples to understand not only <strong>how</strong> these techniques work, but also <strong>why, when, and where</strong> they should be applied.</p><h3><strong>Before Encoding: Understanding the Type of Feature</strong></h3><p>Before deciding which encoding technique to use, we need to understand what kind of information a feature contains.</p><p>Features are commonly divided into <strong>numerical features</strong> and <strong>categorical features</strong>.</p><p>Numerical features contain quantities that can naturally be represented using numbers.</p><p>For example:</p><p>Age → 25</p><p>Salary → ₹45,000</p><p>Experience → 3 years</p><p>Number of purchases → 12</p><p>Temperature → 32°C</p><p>These values have numerical meaning, and mathematical operations can generally be performed on them.</p><p>Categorical features, on the other hand, represent groups, labels, or categories.</p><p>For example:</p><p>City → Hyderabad, Chennai, Mumbai</p><p>Gender → Male, Female</p><p>Department → HR, Sales, IT</p><p>Payment Method → Cash, Card, UPI</p><p>The important point is that <strong>not every categorical feature behaves in the same way</strong>.</p><p>Consider:</p><p><strong>City</strong></p><p>Hyderabad, Chennai, and Mumbai are simply different categories. There is no natural order between them.</p><p>Now consider:</p><p><strong>Education Level</strong></p><p>Bachelor’s, Master’s, and PhD can have an order:</p><p><strong>Bachelor’s &lt; Master’s &lt; PhD</strong></p><p>This distinction becomes extremely important when choosing an encoding technique.</p><p><strong>What is Encoding?</strong></p><p><strong>Encoding is the process of converting categorical values into a numerical representation that can be understood and processed by a machine learning algorithm.</strong></p><p>In simple terms:</p><p>Encoding converts categorical information into a numerical representation while preserving the relevant information needed by the model.</p><p><strong>Choosing the appropriate encoding technique is important</strong>.</p><h3><strong>The Nature of the Category Determines the Encoding</strong></h3><p>At this point, we know that categorical features are not all the same.</p><p>Some categories are simply <strong>different labels</strong>, some have a <strong>meaningful order</strong>, and some contain only <strong>two possible values</strong>.</p><p>Understanding this structure helps us choose an appropriate encoding technique.</p><p><strong>1. Nominal Categorical Features — No Natural Order</strong></p><p>A <strong>nominal feature</strong> contains categories that are different from each other, but there is <strong>no meaningful order or ranking</strong> between them.</p><p>For example, consider:</p><p><strong>Transport Mode</strong></p><ul><li>Bus</li><li>Train</li><li>Car</li><li>Bike</li></ul><p>There is no meaningful statement such as:</p><p><strong>Bus &lt; Train &lt; Car &lt; Bike</strong></p><p>These are simply different categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqiQgOzomF25nQfmJ2ZqOg.png" /></figure><p>Another example is:</p><p><strong>Department</strong></p><ul><li>HR</li><li>Finance</li><li>Marketing</li><li>IT</li></ul><p>There is no natural ranking between HR, Finance, Marketing, and IT.</p><p>For such features, <strong>One-Hot Encoding</strong> is commonly used because it represents each category separately without creating a false numerical order.</p><p><strong>One-Hot Encoding: Representing Categories Without Creating an Order</strong></p><p>Imagine we have a feature called <strong>Payment Method</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*oNmCm4VW8ccU36svbghqhA.png" /></figure><p>We know that <strong>Cash, Card, and UPI are simply different categories</strong>.</p><p>There is no meaningful relationship such as:</p><p><strong>Cash &lt; Card &lt; UPI</strong></p><p>So, assigning numbers like:</p><p><strong>Cash → 1</strong><br><strong>Card → 2</strong><br><strong>UPI → 3</strong></p><p>would introduce an artificial numerical relationship.</p><p>Instead, we can create a separate binary feature for each category.</p><p>The original feature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*oNmCm4VW8ccU36svbghqhA.png" /></figure><p>can become:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*5TlBwqY-D5HtjeMFVuLr2Q.png" /></figure><p>This is called <strong>One-Hot Encoding</strong>.</p><p>Each category gets its own feature, and the corresponding category is represented by 1, while the other categories are represented by 0.</p><p>For example:</p><p><strong>Cash → [1,0,0]</strong></p><p><strong>Card → [0,1,0]</strong></p><p><strong>UPI → [0,0,1]</strong></p><p>Notice what happened.</p><p>We did not tell the model that:</p><p><strong>UPI &gt; Card &gt; Cash</strong></p><p>Instead, we represented the categories as separate possibilities.</p><p>This is the key idea behind One-Hot Encoding.</p><p><strong>Why Is It Called “One-Hot”?</strong></p><p>The name comes from the fact that, for each observation, <strong>one category is active or “hot”</strong>, while the remaining categories are 0.</p><p>For example:</p><p><strong>Card → [0,1,0]</strong></p><p>Only the <strong>Card</strong> position contains 1.</p><p>The other positions contain 0.</p><p>That is why the representation is called <strong>one-hot</strong>.</p><p><strong>2. Ordinal Categorical Features — Meaningful Order</strong></p><p>An <strong>ordinal feature</strong> contains categories that have a meaningful order or ranking.</p><p>For example, consider <strong>Customer Satisfaction</strong>:</p><ul><li>Low</li><li>Medium</li><li>High</li></ul><p>Here, the order matters:</p><p><strong>Low &lt; Medium &lt; High</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEyTq06fIY0v1YePKyEPwQ.png" /></figure><p>Another example is <strong>Job Experience Level</strong>:</p><ul><li>Fresher</li><li>Junior</li><li>Mid-Level</li><li>Senior</li></ul><p>There is a natural progression from one category to another.</p><p>In such situations, <strong>Ordinal Encoding</strong> can be appropriate because the numerical representation can preserve the underlying order.</p><p><strong>Ordinal Encoding</strong></p><p>Ordinal Encoding assigns numerical values to categories according to their <strong>meaningful order</strong>.</p><p>For example:</p><p><strong>Low → 1</strong><br><strong>Medium → 2</strong><br><strong>High → 3</strong></p><p>The numbers are not arbitrary labels here.</p><p>They represent an order that already exists in the original feature:</p><p><strong>Low &lt; Medium &lt; High</strong></p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*OnerMAntWgrO3nWhRLhweA.png" /></figure><p>The important distinction is this:</p><p>With <strong>nominal data</strong>, assigning numbers such as 1,2,3 can create a false sense of order.</p><p>With <strong>ordinal data</strong>, the order already exists, so an ordered numerical representation can preserve that information.</p><p><strong>3. Binary or Boolean Features — Only Two Possible Values</strong></p><p>Here is another special case that we commonly encounter in real-world datasets: <strong>binary features</strong>.</p><p>A binary feature contains only <strong>two possible categories</strong>.</p><p>For example:</p><p><strong>Has Digital Wellbeing Enabled</strong></p><ul><li>True</li><li>False</li></ul><p>Or:</p><p><strong>Uses Focus Apps</strong></p><ul><li>Yes</li><li>No</li></ul><p>Or:</p><p><strong>Customer Is a Member</strong></p><ul><li>1</li><li>0</li></ul><p>Since there are only two possible states, these features can often be represented using <strong>0 and 1</strong>.</p><p>For example:</p><p><strong>True → 1</strong><br><strong>False → 0</strong></p><p>Similarly:</p><p><strong>Yes → 1</strong><br><strong>No → 0</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqSeg9P0VNn6X841Lk577Q.png" /></figure><p>This is commonly referred to as <strong>binary representation</strong> or <strong>0/1 mapping</strong>.</p><p>If a Feature already contains Boolean values such as True and False, it may not require a separate encoding step in every workflow. Depending on the preprocessing pipeline and machine learning library, Boolean values can be handled directly or converted into 1 and 0.</p><p>The important point is that 1 and 0 here represent the two possible states.</p><p>We are not saying:</p><p><strong>True &gt; False</strong></p><p>The values simply provide a numerical representation of the two categories.</p><p>Once we understand the nature of the feature, choosing an encoding strategy becomes much more logical.</p><h3><strong>Feature Scaling: Bringing Numerical Features to a Comparable Scale</strong></h3><p>We have now seen how categorical information can be converted into numerical representations through <strong>encoding</strong>.</p><p>But what happens when the features are already numerical?</p><p>Consider a dataset containing information about customers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*nHylPzRZyorJBS4DPYYpDg.png" /></figure><p>All of these features are numerical.</p><p>So, encoding is not the problem anymore.</p><p>But look at their <strong>ranges</strong>.</p><p>Age may range from around <strong>18 to 70</strong>.</p><p>Experience may range from <strong>0 to 40 years</strong>.</p><p>Annual Income may range from <strong>₹2,00,000 to ₹50,00,000</strong>.</p><p>Purchase Amount may range from <strong>₹500 to ₹2,00,000</strong>.</p><p>The features are measured using very different scales.</p><p>This raises an important question:</p><p><strong>If the features are already numerical, why might we need to transform them further?</strong></p><p>The answer leads us to <strong>Feature Scaling</strong>.</p><p>What is Feature Scaling?</p><p>Feature scaling is the process of transforming numerical features to a comparable scale, so that differences in their original magnitude do not unfairly influence the model.</p><p>For example, suppose we have two features:</p><p><strong>Age</strong></p><p>10, 20, 30, 40</p><p>and</p><p><strong>Salary</strong></p><p>20,000, 40,000, 60,000, 80,000</p><p>Both features contain useful information, but their numerical ranges are very different.</p><p>A scaling technique can transform these values into a more comparable numerical range.</p><p>This can be particularly important for algorithms that are sensitive to the <strong>magnitude of feature values</strong> or rely on <strong>distances, gradients, or variance</strong>.</p><p>Examples of algorithms that are often affected by feature scale include</p><ul><li>K-Nearest Neighbors (KNN)</li><li>K-Means Clustering</li><li>Support Vector Machines (SVM)</li><li>Logistic Regression</li><li>Linear Regression</li><li>Neural Networks</li><li>Principal Component Analysis (PCA)</li></ul><p>However, feature scaling is <strong>not equally important for every algorithm</strong>.</p><p>For example, tree-based algorithms such as <strong>Decision Trees, Random Forests, and many gradient-boosted tree models</strong> generally do not require feature scaling because their splitting decisions are based on thresholds rather than distances between feature values.</p><p>So, just like encoding , scaling should be based on the characteristics of the data.</p><p>We first need to understand <strong>which scaling technique fits the data and the algorithm</strong>.</p><h3>The Main Feature Scaling Techniques</h3><p>There are several ways to scale numerical features.</p><p>The three techniques we will focus on are:</p><ol><li><strong>Standardization — StandardScaler</strong></li><li><strong>Normalization to a fixed range — MinMaxScaler</strong></li><li><strong>Robust scaling — RobustScaler</strong></li></ol><p>The important question is not simply:</p><p>“Which scaler should I use?”</p><p>Instead, we should ask:</p><p>“What does my data look like, and which representation is appropriate for it?”</p><p>Let’s understand them one by one.</p><p><strong>1. StandardScaler — Standardization</strong></p><p>Imagine a feature such as <strong>Age</strong>:</p><p>25, 30, 35, 40, 45</p><p>The values do not necessarily need to be converted into a specific range such as 0 to 1.</p><p>Instead, we may want to transform the feature so that it is centered around <strong>0</strong> and expressed in terms of its <strong>standard deviation</strong>.</p><p>This is called <strong>standardization</strong>.</p><p>In <strong>scikit-learn</strong>, this is commonly performed using:</p><p><strong>StandardScaler</strong></p><p>The standardization formula is:</p><p><strong>z = (x − μ) / σ</strong></p><p>where:</p><ul><li>x = original value</li><li>μ = mean of the feature</li><li>σ = standard deviation of the feature</li><li>z = standardized value</li></ul><p>After standardization, the transformed feature generally has:</p><ul><li>Mean approximately <strong>0</strong></li><li>Standard deviation approximately <strong>1</strong></li></ul><p>For example, suppose the mean age is <strong>30</strong> and the standard deviation is <strong>5</strong>.</p><p>For a person whose age is <strong>40</strong>:</p><p><strong>z = (40 − 30) / 5</strong></p><p><strong>z = 2</strong></p><p>This means that the value is <strong>2 standard deviations above the mean</strong>.</p><p>The important point is that StandardScaler does not simply force every value into a particular minimum and maximum range.</p><p>Instead, it describes values relative to the <strong>mean and standard deviation</strong> of the feature.</p><p><strong>When Is StandardScaler Commonly Used?</strong></p><p>StandardScaler is commonly useful when:</p><ul><li>numerical features have different units or scales</li><li>the algorithm is sensitive to feature magnitude</li><li>the data does not contain severe outliers</li><li>a standardized distribution around zero is appropriate</li></ul><p>However, there is an important limitation.</p><p>StandardScaler uses the <strong>mean and standard deviation</strong> of a feature. Therefore, <strong>extreme values can influence the scaling</strong>.</p><p>This means StandardScaler may not be the most suitable choice when a feature contains significant outliers.</p><p>But StandardScaler is not the only way to scale numerical features.</p><p><strong>What if we want to transform our values into a specific range, such as 0 to 1?</strong></p><p>This leads us to <strong>MinMaxScaler</strong>.</p><p><strong>2. MinMaxScaler — Scaling to a Fixed Range</strong></p><p>Suppose we want our numerical feature to lie within a specific range, commonly:</p><p><strong>0 to 1</strong></p><p>This is where <strong>MinMaxScaler</strong> can be useful.</p><p>Instead of centering the feature around zero, MinMaxScaler transforms the values according to the minimum and maximum values.</p><p>The commonly used formula for scaling to the range 0 to 1 is:</p><p><strong>x’= (x − x_min) / (x_max − x_min)</strong></p><p>where:</p><ul><li>x = original value</li><li>x_min = minimum value</li><li>x_max = maximum value</li><li>x’ = scaled value</li></ul><p>For example, suppose the values are:</p><p><strong>10, 20, 30, 40, 50</strong></p><p>The minimum is <strong>10</strong> and the maximum is <strong>50</strong>.</p><p>For the value <strong>30</strong>:</p><p><strong>x’= (30 − 10) / (50 − 10)</strong></p><p><strong>x’= 20 / 40</strong></p><p><strong>x’= 0.5</strong></p><p>So the value 30 becomes 0.5.</p><p>The minimum value becomes:</p><p><strong>10 → 0</strong></p><p>and the maximum becomes:</p><p><strong>50 → 1</strong></p><p>The other values are transformed proportionally between them.</p><p><strong>When Is MinMaxScaler Commonly Used?</strong></p><p>MinMaxScaler can be useful when:</p><ul><li>we want features within a defined range</li><li>the algorithm benefits from values on a bounded scale</li><li>the relative position between the minimum and maximum is useful</li><li>the data does not contain problematic outliers</li></ul><p>But there is an important consideration.</p><p>MinMaxScaler depends directly on the <strong>minimum and maximum values</strong>.</p><p>Imagine most purchase amounts are between:</p><p><strong>₹500 and ₹5,000</strong></p><p>but one unusual transaction is:</p><p><strong>₹1,00,000</strong></p><p>That extreme value becomes the <strong>maximum value</strong> in the feature.</p><p>Since MinMaxScaler uses the minimum and maximum values to determine the scaling range, the remaining observations may get <strong>compressed into a narrow portion of the 0–1 range</strong>.</p><p><strong>So, what should we use when a feature contains significant outliers?</strong><br> This is where <strong>RobustScaler</strong> becomes useful.</p><p><strong>3. RobustScaler — When Outliers Matter</strong></p><p>Consider a dataset containing employee salaries:</p><p>₹25,000, ₹30,000, ₹32,000, ₹35,000, ₹40,000, ₹5,00,000</p><p>Most employees earn somewhere between ₹25,000 and ₹40,000.</p><p>But one value, <strong>₹5,00,000</strong>, is extremely different from the others.</p><p>This type of observation can be considered an <strong>outlier</strong>.</p><p>StandardScaler can be affected by such extreme values because it uses the <strong>mean and standard deviation</strong>.</p><p>MinMaxScaler can also be strongly affected because it uses the <strong>minimum and maximum</strong>.</p><p>This is where <strong>RobustScaler</strong> can be useful.</p><p>RobustScaler uses statistics that are less sensitive to extreme values:</p><ul><li><strong>Median</strong></li><li><strong>Interquartile Range (IQR)</strong></li></ul><p>The IQR is calculated as:</p><p><strong>IQR = Q3 − Q1</strong></p><p>where:</p><ul><li>Q1= first quartile</li><li>Q3 = third quartile</li></ul><p>The basic idea behind RobustScaler is to center the data using the <strong>median</strong> and scale it using the <strong>IQR</strong>.</p><p>Conceptually:</p><p><strong>Scaled value = (x − Median) / IQR</strong></p><p>Because the median and IQR are less influenced by extreme observations than the mean and standard deviation, RobustScaler can be a useful choice when significant outliers are present.</p><p><strong>When Is RobustScaler Commonly Used?</strong></p><p>RobustScaler can be considered when:</p><ul><li>the numerical features contain significant outliers</li><li>the outliers are legitimate observations rather than data-entry errors</li><li>we want a scaling method that is less sensitive to extreme values</li></ul><p>For example, in transaction data, most purchases may be relatively small while a few legitimate purchases may be extremely large.</p><p>In such a situation, RobustScaler can provide an alternative to StandardScaler and MinMaxScaler.</p><h3>Conclusion: From Raw Data to Model-Ready Data</h3><p>A machine learning model does not see data the way we do.</p><p>We may look at a dataset and immediately understand that <strong>Hyderabad, Chennai, and Mumbai</strong> are different cities, that <strong>Bachelor’s, Master’s, and PhD</strong> represent different education levels, or that one salary is much larger than another. But for a machine learning algorithm, these values need to be represented in a way that allows mathematical operations and patterns to be learned.</p><p>That is where <strong>data preprocessing</strong> becomes important.</p><p>In this article, we explored two important parts of preparing data for machine learning: <strong>Encoding</strong> and <strong>Feature Scaling</strong>.</p><p>With <strong>Encoding</strong>, we learned that the type of categorical feature matters.</p><p>A <strong>nominal feature</strong> has categories without a natural order, making <strong>One-Hot Encoding</strong> a suitable approach in many situations.</p><p>An <strong>ordinal feature</strong> has a meaningful order, so <strong>Ordinal Encoding</strong> can represent that existing relationship.</p><p>For <strong>binary features</strong>, two possible states can often be represented using <strong>0 and 1</strong>.</p><p>Then, we moved to <strong>Feature Scaling</strong> and saw that numerical features can exist on very different scales. Depending on the data and the algorithm, scaling can help prevent differences in feature magnitude from having an unwanted influence on the learning process.</p><p>We explored three commonly used approaches:</p><ul><li><strong>StandardScaler</strong> — standardizes features using the mean and standard deviation.</li><li><strong>MinMaxScaler</strong> — transforms values into a defined range, commonly 0 to 1.</li><li><strong>RobustScaler</strong> — uses the median and IQR and can be useful when significant outliers are present.</li></ul><p>But there is one lesson that is more important than remembering the formulas:</p><p><strong>Preprocessing is not about applying every technique to every dataset. It is about understanding the data first and choosing transformations that make sense for the problem.</strong></p><p>Before encoding a feature, ask:</p><p><strong>Does it have a natural order?</strong></p><p>Before scaling a numerical feature, ask:</p><p><strong>Are the features on very different scales? Are there significant outliers? Is the algorithm sensitive to feature magnitude?</strong></p><p>These questions turn preprocessing from a collection of techniques into a <strong>reasoning process</strong>.</p><p>Just like cooking, where each ingredient is prepared differently depending on the recipe, data must also be prepared according to what the model needs.</p><p>The goal is not to change everything, but to <strong>prepare each feature in the right way for the learning process</strong>.</p><p><strong>Raw data is like the ingredients; preprocessing is the preparation that makes them ready for the model.</strong></p><p>Just as properly prepared ingredients form the foundation of a well-made dish, well-prepared data forms the foundation of effective machine learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c15835bb3aae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strings in Python: A Beginner’s Guide]]></title>
            <link>https://medium.com/@niharikaponnam80/strings-in-python-a-beginners-guide-394f3a333f4c?source=rss-fcbbf1a0596d------2</link>
            <guid isPermaLink="false">https://medium.com/p/394f3a333f4c</guid>
            <category><![CDATA[string-operations]]></category>
            <category><![CDATA[string-methods]]></category>
            <category><![CDATA[looping-in-strings]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[string-validation-methods]]></category>
            <dc:creator><![CDATA[Niharikaponnam]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 09:48:26 GMT</pubDate>
            <atom:updated>2026-06-25T09:48:26.443Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose you are building a website. To secure that website, you need to create a strong password. A strong password consists of letters, digits, and special characters, making it unique and difficult for others to guess.</p><p>Have you ever noticed that when you create a new account on a website, you are required to create a password so that only you can access your account? Passwords play a major role in protecting your account and personal information.</p><p>Is it possible to store each character of a password one by one? Yes, it is possible, but it would be difficult to manage efficiently.</p><p>Is there any other way to manage them?</p><p>Yes! This is where strings come into the picture. Strings allow us to store a sequence of characters as a single unit, making them easier to store, manage, and manipulate.</p><h3><strong>Introduction</strong></h3><p>By the end of this article, readers will be able to understand:</p><ul><li>What is a string?</li><li>Why do we use strings?</li><li>How to create strings</li><li>Whether strings are mutable or immutable</li><li>Commonly used built-in functions for strings</li><li>Common operations performed on strings</li><li>Indexing and slicing in strings</li><li>String methods for case handling, modification, splitting, and joining</li><li>String validation methods commonly used for password validation</li><li>Looping through strings</li><li>Conclusion</li></ul><h3><strong>What is a String ?</strong></h3><p>A string is a sequence of characters enclosed within quotes. It can be defined using single quotes (‘ ‘), double quotes (“ “), or triple quotes (‘’’ ‘’’ or “”” “””).</p><p><strong>Example:<br></strong>Name= ‘Krishna’<br>email= “Krishna123*@gmail.com”<br>Course= “““Data Scientist”””</p><h3><strong>Why do we use strings?</strong></h3><ul><li><strong>Storage</strong> — Strings are used to store textual data.</li><li><strong>Authentication</strong> — Strings are used for validating usernames and passwords.</li><li><strong>Searching</strong> — Strings help in searching for specific text or characters within a string.</li><li><strong>Processing</strong> — Strings are used for manipulating text data through operations such as concatenation, slicing, and more.</li><li><strong>Comparison</strong> — Strings can be compared to determine whether two strings are the same or different.</li></ul><h3><strong>How to create a String?</strong></h3><p>Strings are created by enclosing characters within quotes. In Python, strings can be defined using single quotes (‘ ‘), double quotes (“ “), or triple quotes (‘’’ ‘’’ or “”” “””).</p><ul><li><strong>Using single Quotes:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*3M3V6h7y83OWhe96SpAc6w.png" /></figure><ul><li><strong>Using Double Quotes:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*QsLRq5JW689NeCfHBEmhSg.png" /></figure><ul><li><strong>Using Multiple Quotes:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*XcT5zng1Rxob8-IVgyWF2A.png" /></figure><h3><strong>Are Strings Mutable or Immutable?</strong></h3><p>Strings are immutable, which means that once a string is created, its characters cannot be changed. If you want to modify a string, you must create a new string instead of altering the existing one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*XlHLNS0wZZmpo2EYFyy5EA.png" /></figure><p>If we try to modify a string after it has been created, Python will raise an error because strings are immutable.</p><p>Hence strings <strong>doesn’t support mutability</strong>.</p><h3><strong>Built-in functions in strings</strong></h3><ul><li><strong>len()</strong>: It is used to find the length of a string, that is, the total number of characters present in the string.</li><li><strong>sorted()</strong>: As the name suggests, this function sorts the characters in a string in alphabetical order and returns them as a list.</li><li><strong>max()</strong>: This function returns the character with the highest ASCII (or Unicode) value in the given string.</li><li><strong>ASCII (American Standard Code for Information Interchange)</strong> is a character encoding standard that assigns a unique numeric value to characters.</li></ul><p>For example:</p><ul><li>A → 65</li><li>a→ 97</li></ul><p>Since lowercase letters have higher ASCII values than uppercase letters, max() returns the character with the greatest value according to these codes.</p><ul><li><strong>min()</strong>: It is used to find and return the character with the minimum ASCII value in a string.</li><li><strong>ord()</strong>: It is used to convert a character into its ASCII value (example: ord(“A”) that is 65).</li><li><strong>chr()</strong>: It is used to convert ASCII values into character (example: chr(65) that is “A”)</li></ul><h3><strong>Common Operations in Strings</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*VMzepX8DIaqIFPmz.PNG" /></figure><ul><li><strong>Concatenation</strong>: It is used to add or combine both the strings.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*vBOlzFIJrQ_puDd2OPflCg.png" /></figure><ul><li><strong>Repetition</strong>: It is used to repeat the string n no. of times.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*BslmKHbKCjM2s5jONk9LDQ.png" /></figure><ul><li><strong>Comparison</strong>: This operator is used to compare both the strings <strong>lexicographically</strong>.</li></ul><p>It returns the bool value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*et1msTw--KZUV9eybybVdA.png" /></figure><p>The output is False because python is case sensitive, right that’s why.</p><ul><li><strong>Membership</strong>: Thsi operator is used to check whether the character is present in string or not.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*oIUKeKe3qLpXs_uW2nVR8Q.png" /></figure><p>The output is False as we have written not in but there is o in mango .</p><h3><strong>Indexing and Slicing</strong></h3><p><strong>Indexing</strong> is used to know the character is present at which place 0 or 1 or 2… by default <strong>positive </strong>indexing <strong>starts with 0 </strong>and <strong>negative </strong>indexing <strong>starts with -1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*UExSuaKXA5JqC7TYEyXS5w.png" /></figure><ul><li>it is printing l because 2 is the index of l.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*L5wBp9nPgxALlFCeQzKPog.png" /></figure><ul><li>it is printing l because -3 is the index of l.</li></ul><p><strong>Slicing</strong> is used to get the portion or part of the string you wanted .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*Q5s_n8AUkaMUYWOkIDT1bg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*eIYapiuIHEtDhfVPIV6sGw.png" /></figure><h3><strong>String Methods</strong></h3><p>These are used for manipulations and formatting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*UYFmv9UFyydU2fcg7EyaWg.png" /></figure><h4>For case handling:</h4><ul><li><strong>upper()</strong>: It converts the string into uppercase(A-Z)</li><li><strong>lower()</strong>: It converts the string into lowercase(a-z)</li><li><strong>capitalize() or title()</strong>: It converts the string into a format</li></ul><p>ex: <strong>student.capitalize()</strong> gets converted into <strong>Student</strong></p><ul><li><strong>swapcase()</strong>: converting the characters in the string from uppercase to lowercase and vice versa.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRpAF4VpzM9qyQNQhqbYmw.png" /><figcaption>These are used for Case handling</figcaption></figure><h4>For searching:</h4><ul><li><strong>index()</strong>: It is used to find the character where it is located ,at which place 0 or 1 or 2…. here if the character you entered is not present in the string it will return an error.</li><li><strong>find()</strong>: It is also used to find the character where it is located and at which place either 0 or 1 or 2… it returns -1 if the character not present in the given string.(it is used to optimize the error)</li><li><strong>starts with()</strong>: It checks whether the string starts with is same as the string given.</li><li><strong>ends -with()</strong>: It check whether the string ends with is same as the string given.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OY4tQYuIN671aRX0zRlEBg.png" /><figcaption>These are used for Searching</figcaption></figure><h4>For Modifying and Cleaning:</h4><ul><li><strong>strip()</strong>: It is used to remove the white spaces which are left side and right side of the string.</li><li><strong>lstrip()</strong>: It is used to remove the white spaces only at left side.</li><li><strong>rstrip()</strong>: It is used to remove the white spaces only at right side.</li><li><strong>replace()</strong>: It is used to replace the old string with new string.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5aNfbr4xBLR2irnF1-QiUQ.png" /><figcaption>These are used for modifying and cleaning</figcaption></figure><p>For splitting and joining:</p><ul><li><strong>split()</strong>: It is used to split the words in the string by comma(,).</li><li><strong>join()</strong>: It is used to join the words in the string.</li><li><strong>count()</strong>: It is used to count the specific character present in the string.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7AZsLHtB3KT1EvuSmvZj6A.png" /><figcaption>These are used for splitting, joining and counting the characters or words.</figcaption></figure><h3><strong>String Validation Methods</strong></h3><p>Here validating is about checking if it exists or not. These methods will return bool values.</p><ul><li><strong>is alpha()</strong>: It is used to check if all characters in the string are alphabets(A-Z),(a-z) it will return true.</li><li><strong>is digit()</strong>: It is used to check if all characters are digits in the string (1,2,3,100….)</li><li><strong>is al-num()</strong>: It is used to check if it consists of alphabets along with numbers(student12)</li><li><strong>is upper()</strong>: It is used to check if all the characters are of uppercase(A-Z)</li><li><strong>is lower()</strong>: It is used to check if all the characters are of lowercase(a-z)</li><li><strong>is space()</strong>: It is used to check if the string consists of all spaces(“ ”)</li></ul><p>Let’s see how they will work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6HUR-nidxLJiMszpV_PPFA.png" /><figcaption>Here see it is returning boolean values</figcaption></figure><h3><strong>Looping in Strings</strong></h3><p>Here if i (variable)which are apple, banana, kiwi, goa are in Fruits (iterable) then only the i (variable)is printed.</p><p>syntax: for variable in iterable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cti4jJL1T8jwLLJ8KeEd2A.png" /><figcaption>Here Fruits is iterable and i is variable which are apple, banana…</figcaption></figure><p>Let’s check how strings are used in validating a password practically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hbve6QQstCXCEXNzkaJnJw.png" /><figcaption>Here I have given Student@123 as input and it returns its a valid password</figcaption></figure><h3>Conclusion</h3><p>We can conclude that <strong>strings</strong> are one of the most important <strong>data types</strong> in Python. They are widely used for handling and processing <strong>textual data</strong> efficiently. Using various <strong>string functions</strong> and <strong>string methods</strong>, we can perform operations such as <strong>comparison</strong>, <strong>concatenation</strong>, <strong>case handling</strong>, <strong>searching</strong>, <strong>modifying</strong>, <strong>splitting</strong>, and <strong>joining</strong> strings. Additionally, <strong>string validation methods</strong> help verify whether a given <strong>username</strong> or <strong>password</strong> meets specific requirements. By understanding the concept of strings, you will be able to work with <strong>password validation</strong>, <strong>indexing</strong>, <strong>slicing</strong>, and <strong>looping through strings</strong> effectively. Mastering strings is essential because they form the foundation for many real-world applications involving text processing and data manipulation.</p><p>In practical applications, <strong>strings</strong> are used for handling and processing <strong>textual data</strong>. They play a major role in storing <strong>user information</strong>, managing <strong>file names and file paths</strong>, and enabling communication through <strong>messages (chats)</strong> and <strong>emails</strong>. Strings are also widely used in <strong>data analysis</strong> and <strong>database management</strong>. In fact, strings are an essential part of almost every <strong>software application</strong> and <strong>digital system</strong> that we use today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=394f3a333f4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>