<?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 Harimadhavkonduru on Medium]]></title>
        <description><![CDATA[Stories by Harimadhavkonduru on Medium]]></description>
        <link>https://medium.com/@harimadhavkonduru?source=rss-8831d6d3079e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HI0TO-2WA5iw_L-9</url>
            <title>Stories by Harimadhavkonduru on Medium</title>
            <link>https://medium.com/@harimadhavkonduru?source=rss-8831d6d3079e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:13:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harimadhavkonduru/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[Evaluation Metrics in Machine Learning: Regression and Classification]]></title>
            <link>https://medium.com/@harimadhavkonduru/evaluation-metrics-in-machine-learning-regression-and-classification-219a67e33e03?source=rss-8831d6d3079e------2</link>
            <guid isPermaLink="false">https://medium.com/p/219a67e33e03</guid>
            <dc:creator><![CDATA[Harimadhavkonduru]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 11:16:06 GMT</pubDate>
            <atom:updated>2026-11-18T11:16:06.028Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>Machine Learning models learn patterns from historical data and use those patterns to make predictions on new, unseen data. However, building a model is not enough. We also need to determine how well the model performs.</p><p>This is where <strong>Evaluation Metrics</strong> come into the picture.</p><p>Evaluation metrics are mathematical measures used to assess the performance of a Machine Learning model. They help us understand whether a model makes accurate predictions, how many mistakes it makes, and where it needs improvement.</p><p>For example:</p><ul><li>In a customer churn prediction system, we want to identify customers who are likely to leave a company.</li><li>In a house price prediction system, we want to predict the selling price of a house as accurately as possible.</li></ul><p>Both problems use Machine Learning, but their evaluation methods are different.</p><p>There are two major categories of Machine Learning evaluation:</p><ol><li>Classification Metrics</li><li>Regression Metrics</li></ol><h3>2. Classification Metrics</h3><h3>2.1 What is Classification?</h3><p>Classification is a type of Supervised Machine Learning in which a model predicts a category or class label.</p><p>The output is discrete rather than continuous.</p><p><strong>Examples:</strong></p><ul><li>Email classification: Spam or Not Spam.</li><li>Customer churn: Churn or Not Churn.</li><li>Medical diagnosis: Disease or No Disease.</li><li>Loan approval: Approved or Rejected.</li></ul><p>For our examples, consider a customer churn prediction model that predicts whether a customer will leave a company.</p><p>Before understanding the evaluation metrics, we need to understand the Confusion Matrix.</p><h3>2.2 Confusion Matrix</h3><p>A Confusion Matrix is a table used to evaluate a classification model by comparing actual values with predicted values.</p><p>It shows four possible outcomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obOlaUCYMs-UbBbpM5POhg.png" /></figure><p>Let’s understand each term using customer churn prediction.</p><p><strong>1. True Positive (TP)</strong></p><p>The customer actually leaves the company, and the model correctly predicts that the customer will leave.</p><p><strong>2. True Negative (TN)</strong></p><p>The customer stays with the company, and the model correctly predicts that the customer will stay.</p><p><strong>3. False Positive (FP)</strong></p><p>The customer actually stays, but the model incorrectly predicts that the customer will leave.</p><p>This is also called a Type I Error.</p><p><strong>4. False Negative (FN)</strong></p><p>The customer actually leaves, but the model incorrectly predicts that the customer will stay.</p><p>This is also called a Type II Error.</p><h3>Numerical Example</h3><p>Suppose a customer churn model is tested on 100 customers and produces these results:</p><ul><li>True Positive = 30</li><li>True Negative = 50</li><li>False Positive = 10</li><li>False Negative = 10</li></ul><p>Total predictions = 30 + 50 + 10 + 10 = 100.</p><p>The confusion matrix is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xj4Grk-LRtbyJXiDYPYR9g.png" /></figure><p>The confusion matrix helps us understand not only how many predictions are correct but also the types of mistakes made by the model.</p><h3>2.3 Accuracy</h3><p>Accuracy measures the percentage of total predictions that the model classified correctly.</p><p>In simple words, it tells us how often the model is correct.</p><p><strong>Formula:</strong></p><p>Accuracy = (TP + TN) / (TP + TN + FP + FN)</p><p>Using our example:</p><p>Accuracy = (30 + 50) / (30 + 50 + 10 + 10)</p><p>Accuracy = 80 / 100 = 0.80</p><p><strong>Accuracy = 80%</strong></p><p>This means the model correctly predicted 80 out of 100 customers.</p><p><strong>Advantages:</strong></p><ul><li>Easy to understand and calculate.</li><li>Useful when classes are reasonably balanced.</li><li>Provides an overall measure of correctness.</li></ul><p><strong>Limitations:</strong></p><ul><li>Can be misleading when the dataset is imbalanced.</li><li>Does not distinguish between different types of errors.</li><li>A model can achieve high accuracy while failing to identify the minority class.</li></ul><p><strong>Real-world application:</strong> Accuracy can be useful in classifying balanced datasets, such as distinguishing between two equally represented types of images.</p><h3>2.4 Precision</h3><p>Precision measures how many of the positive predictions made by the model were actually positive.</p><p>In simple words:</p><p>Out of all customers predicted as likely to leave, how many actually left?</p><p><strong>Formula:</strong></p><p>Precision = TP / (TP + FP)</p><p>Using our example:</p><p>Precision = 30 / (30 + 10)</p><p>Precision = 30 / 40 = 0.75</p><p><strong>Precision = 75%</strong></p><p>This means that out of 40 customers predicted to leave, 30 actually left.</p><p><strong>Advantages:</strong></p><ul><li>Helps reduce False Positives.</li><li>Useful when incorrect positive predictions are expensive.</li><li>Important when we need confidence in positive predictions.</li></ul><p><strong>Limitations:</strong></p><ul><li>Does not consider False Negatives.</li><li>A model can have high precision but miss many actual positive cases.</li></ul><p><strong>Real-world application:</strong> In spam email detection, precision is important because we do not want important genuine emails to be incorrectly classified as spam.</p><h3>2.5 Recall (Sensitivity)</h3><p>Recall measures how many actual positive cases the model correctly identifies.</p><p>In simple words:</p><p>Out of all customers who actually left, how many did the model successfully identify?</p><p><strong>Formula:</strong></p><p>Recall = TP / (TP + FN)</p><p>Using our example:</p><p>Recall = 30 / (30 + 10)</p><p>Recall = 30 / 40 = 0.75</p><p><strong>Recall = 75%</strong></p><p>This means the model successfully identified 75% of the customers who actually left.</p><p><strong>Advantages:</strong></p><ul><li>Helps reduce False Negatives.</li><li>Important when missing a positive case is costly.</li><li>Useful in medical diagnosis and fraud detection.</li></ul><p><strong>Limitations:</strong></p><ul><li>Does not consider False Positives.</li><li>Increasing recall can sometimes decrease precision.</li></ul><p><strong>Real-world application:</strong> In disease detection, recall is important because missing a patient who actually has a disease can have serious consequences.</p><h3>2.6 F1-Score</h3><p>F1-Score is the harmonic mean of Precision and Recall.</p><p>It combines both metrics into a single score.</p><p>It is particularly useful when we want a balance between identifying positive cases and avoiding incorrect positive predictions.</p><p><strong>Formula:</strong></p><p>F1-Score = 2 × (Precision × Recall) / (Precision + Recall)</p><p>Using our example:</p><p>Precision = 0.75</p><p>Recall = 0.75</p><p>F1-Score = 2 × (0.75 × 0.75) / (0.75 + 0.75)</p><p>F1-Score = 1.125 / 1.5</p><p><strong>F1-Score = 0.75 or 75%</strong></p><p><strong>Advantages:</strong></p><ul><li>Combines Precision and Recall.</li><li>Useful for imbalanced datasets.</li><li>Provides a single score when both metrics matter.</li></ul><p><strong>Limitations:</strong></p><ul><li>Does not directly consider True Negatives.</li><li>Does not reflect the cost of different types of errors.</li><li>Can hide differences between Precision and Recall.</li></ul><p><strong>Real-world application:</strong> F1-Score is useful in fraud detection, spam detection, and other classification problems where the positive class is relatively rare.</p><h3>2.8 ROC Curve and AUC</h3><h3>What is ROC Curve?</h3><p>ROC stands for Receiver Operating Characteristic.</p><p>The ROC Curve is a graphical representation used to evaluate a binary classification model at different classification thresholds.</p><p>It plots:</p><ul><li>X-axis: False Positive Rate (FPR)</li><li>Y-axis: True Positive Rate (TPR)</li></ul><p>True Positive Rate = TP / (TP + FN)</p><p>False Positive Rate = FP / (FP + TN)</p><p>The ROC Curve shows how the balance between correctly identifying positive cases and incorrectly identifying negative cases changes when we adjust the classification threshold.</p><h3>What is a Classification Threshold?</h3><p>A classification model can produce probabilities instead of directly producing class labels.</p><p>For example, a model predicts that a customer has an 80% probability of leaving.</p><p>If the threshold is 0.50:</p><ul><li>Probability &gt;= 0.50: Predict Churn.</li><li>Probability &lt; 0.50: Predict Not Churn.</li></ul><p>Changing the threshold changes the number of positive and negative predictions.</p><h3>Understanding the ROC Curve</h3><ul><li>A curve closer to the top-left corner generally indicates better classification performance.</li><li>The diagonal line represents random classification performance.</li><li>A curve below the diagonal indicates performance worse than random for the chosen positive-class orientation.</li></ul><h3>What is AUC?</h3><p>AUC stands for Area Under the Curve.</p><p>It measures the area under the ROC Curve and summarizes how well a model separates positive and negative classes.</p><p><strong>General interpretation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEVYXiPfQYtmGxNjUNoypA.png" /></figure><p>AUC can also be interpreted as the probability that the model assigns a higher score to a randomly selected positive example than to a randomly selected negative example.</p><p><strong>Advantages:</strong></p><ul><li>Evaluates model discrimination across different thresholds.</li><li>Useful when comparing binary classification models.</li><li>Does not depend on selecting one fixed threshold.</li></ul><p><strong>Limitations:</strong></p><ul><li>Does not directly tell us the best classification threshold.</li><li>Can appear optimistic on highly imbalanced datasets.</li><li>Does not measure probability calibration.</li><li>Precision-Recall AUC can be more informative when positive cases are very rare.</li></ul><p><strong>Real-world application:</strong> ROC-AUC is useful in evaluating disease prediction, credit risk classification, and customer churn models.</p><h3>3. Regression Metrics</h3><h3>3.1 What is Regression?</h3><p>Regression is a type of Supervised Machine Learning in which a model predicts a continuous numerical value.</p><p>Unlike classification, regression does not predict categories. It predicts quantities.</p><p><strong>Examples:</strong></p><ul><li>House price prediction.</li><li>Salary prediction.</li><li>Temperature forecasting.</li><li>Sales forecasting.</li><li>Predicting delivery time.</li></ul><p>For our numerical example, consider a model that predicts house prices.</p><p>Suppose we have the following actual and predicted prices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUZP9hMYfeguPvlIjLFEHA.png" /></figure><p>The difference between the actual value and predicted value is called the prediction error or residual.</p><p>Error = Actual Value − Predicted Value.</p><p>The errors are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvMRhSyER7gPz9qLdV_55w.png" /></figure><p>Now let’s understand the regression evaluation metrics.</p><h3>3.2 MAE (Mean Absolute Error)</h3><p>Mean Absolute Error measures the average absolute difference between actual and predicted values.</p><p>In simple words, it tells us how far the model’s predictions are from the actual values on average, without considering whether the prediction is higher or lower.</p><p><strong>Formula:</strong></p><p>MAE = (1/n) × Σ |Actual Value − Predicted Value|</p><p>Using our example:</p><p>Absolute errors = 2, 2, 3, 3, 2</p><p>MAE = (2 + 2 + 3 + 3 + 2) / 5</p><p>MAE = 12 / 5</p><p><strong>MAE = 2.4 Lakhs</strong></p><p>This means the model’s predictions are off by an average absolute amount of ₹2.4 lakhs.</p><p><strong>Advantages:</strong></p><ul><li>Easy to understand and interpret.</li><li>Uses the same unit as the target variable.</li><li>Less sensitive to large errors than MSE and RMSE.</li></ul><p><strong>Limitations:</strong></p><ul><li>Does not penalize large errors as strongly as MSE.</li><li>Does not indicate the direction of prediction errors.</li><li>Does not show how errors are distributed.</li></ul><p><strong>Real-world application:</strong> MAE is useful in house price prediction when we want to understand the average absolute prediction error in rupees.</p><h3>3.3 MSE (Mean Squared Error)</h3><p>Mean Squared Error measures the average of the squared differences between actual and predicted values.</p><p>In simple words, it squares each prediction error before calculating the average.</p><p><strong>Formula:</strong></p><p>MSE = (1/n) × Σ (Actual Value − Predicted Value)²</p><p>Using our example:</p><p>Squared errors = 4, 4, 9, 9, 4</p><p>MSE = (4 + 4 + 9 + 9 + 4) / 5</p><p>MSE = 30 / 5</p><p><strong>MSE = 6</strong></p><p>The unit is squared, so here it is in Lakhs squared.</p><p><strong>Why do we square errors?</strong></p><p>Squaring errors:</p><ul><li>Prevents positive and negative errors from cancelling each other.</li><li>Penalizes larger errors more heavily.</li><li>Makes the metric useful for mathematical optimization.</li></ul><p>For example:</p><ul><li>Error of 2 becomes 4.</li><li>Error of 5 becomes 25.</li><li>Error of 10 becomes 100.</li></ul><p><strong>Advantages:</strong></p><ul><li>Penalizes large prediction errors.</li><li>Useful as a loss function during model training.</li><li>Mathematically convenient for optimization.</li></ul><p><strong>Limitations:</strong></p><ul><li>Sensitive to outliers.</li><li>Expressed in squared units, making interpretation less intuitive.</li><li>A few large errors can dominate the result.</li></ul><p><strong>Real-world application:</strong> MSE is commonly used during regression model training and optimization.</p><h3>3.4 RMSE (Root Mean Squared Error)</h3><p>Root Mean Squared Error is the square root of Mean Squared Error.</p><p>It measures the typical magnitude of prediction errors while giving more weight to larger errors.</p><p><strong>Formula:</strong></p><p>RMSE = √MSE</p><p>Using our example:</p><p>MSE = 6</p><p>RMSE = √6</p><p><strong>RMSE ≈ 2.45 Lakhs</strong></p><p>This means the model has an RMSE of approximately ₹2.45 lakhs.</p><p><strong>Advantages:</strong></p><ul><li>Expressed in the same unit as the target variable.</li><li>Penalizes larger errors more strongly than MAE.</li><li>Useful when large prediction errors are particularly undesirable.</li></ul><p><strong>Limitations:</strong></p><ul><li>Sensitive to outliers.</li><li>Does not explain the direction of errors.</li><li>Can be harder to interpret when error distributions are highly skewed.</li></ul><p><strong>Real-world application:</strong> RMSE is useful in house price prediction, demand forecasting, and energy consumption forecasting when large errors need additional attention.</p><h3>3.5 R² Score (Coefficient of Determination)</h3><p>R² Score measures how well a regression model explains the variation in the target variable compared with predicting the mean of the actual values.</p><p>In simple words, it tells us how much of the variation in the target variable is explained by the model.</p><p><strong>Formula:</strong></p><p>R² = 1 − (SSres / SStot)</p><p>Where:</p><p>SSres = Sum of Squared Residuals</p><p>SStot = Total Sum of Squares</p><p>Using our example:</p><p>Actual values = 20, 30, 40, 50, 60</p><p>Mean of actual values = 40</p><p>Squared residual sum:</p><p>SSres = 4 + 4 + 9 + 9 + 4 = 30</p><p>Total sum of squares:</p><p>SStot = (20 − 40)² + (30 − 40)² + (40 − 40)² + (50 − 40)² + (60 − 40)²</p><p>SStot = 400 + 100 + 0 + 100 + 400</p><p>SStot = 1000</p><p>R² = 1 − (30 / 1000)</p><p><strong>R² = 0.97 or 97%</strong></p><p>This means the model explains 97% of the variation in house prices relative to the mean-prediction baseline on this dataset.</p><p><strong>Understanding R² values:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzBdYEWi0AlrW3zcn3avMQ.png" /></figure><p>Note: R² is not always restricted to the range 0 to 1. It can be negative, especially when the model performs poorly on evaluation data.</p><p><strong>Advantages:</strong></p><ul><li>Measures how well the model explains target variation.</li><li>Useful for comparing regression models on the same dataset.</li><li>Provides an intuitive summary of model fit.</li></ul><p><strong>Limitations:</strong></p><ul><li>Does not measure prediction error in the original unit.</li><li>A high R² does not necessarily mean low prediction error.</li><li>Does not prove that the model is appropriate or that its features cause the target.</li><li>Can increase when additional features are added, even if those features are not useful.</li></ul><p><strong>Real-world application:</strong> R² is useful in salary prediction, sales forecasting, and house price prediction.</p><h3>3.6 Adjusted R² Score</h3><p>Adjusted R² is a modified version of R² that considers the number of independent variables used in a regression model and the number of observations.</p><p>Unlike ordinary R², Adjusted R² penalizes the addition of unnecessary features.</p><p><strong>Formula:</strong></p><p>Adjusted R² = 1 − [(1 − R²) × (n − 1) / (n − p − 1)]</p><p>Where:</p><ul><li>n = Number of observations.</li><li>p = Number of independent variables.</li><li>R² = Coefficient of determination.</li></ul><h3>Numerical Example</h3><p>Suppose:</p><p>R² = 0.90</p><p>Number of observations (n) = 100</p><p>Number of independent variables (p) = 5</p><p>Adjusted R² = 1 − [(1 − 0.90) × (100 − 1) / (100 − 5 − 1)]</p><p>Adjusted R² = 1 − [0.10 × 99 / 94]</p><p>Adjusted R² = 1 − 0.1053</p><p><strong>Adjusted R² ≈ 0.8947</strong></p><p><strong>Adjusted R² = 89.47%</strong></p><p>This value is slightly lower than the ordinary R² because it accounts for the number of predictors in the model.</p><p><strong>Advantages:</strong></p><ul><li>Penalizes unnecessary independent variables.</li><li>Useful for comparing regression models with different numbers of predictors.</li><li>Helps evaluate whether additional features improve the model sufficiently.</li></ul><p><strong>Limitations:</strong></p><ul><li>Does not directly measure prediction error.</li><li>Does not automatically identify the best features.</li><li>Should not replace validation or test-set evaluation.</li><li>Assumes an appropriate regression-model setting and interpretation.</li></ul><p><strong>Real-world application:</strong> Adjusted R² is useful when comparing house price prediction models with different numbers of input features, such as area, location, number of bedrooms, age, and distance from the city.</p><h3>4. Difference Between Classification and Regression Metrics</h3><p>Classification and regression are two different Machine Learning tasks, so they require different evaluation approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpxHOWFOJL7HK2XKAAWykA.png" /></figure><p><strong>Important:</strong> Logistic Regression is used for classification despite having the word Regression in its name.</p><h3>5. Python Implementation Using Scikit-learn</h3><p>Scikit-learn provides built-in functions to calculate classification and regression evaluation metrics.</p><h3>5.1 Classification Metrics in Python</h3><pre>from sklearn.metrics import (<br>    confusion_matrix,<br>    accuracy_score,<br>    precision_score,<br>    recall_score,<br>    f1_score,<br>    classification_report,<br>    roc_auc_score,<br>    roc_curve<br>)<br><br># Actual values<br>y_true = [1, 1, 1, 1, 0, 0, 0, 0]<br><br># Predicted class labels<br>y_pred = [1, 1, 0, 1, 0, 1, 0, 0]<br><br># Predicted probabilities for positive class<br>y_prob = [0.90, 0.80, 0.40, 0.85,<br>          0.20, 0.70, 0.10, 0.30]<br><br># Confusion Matrix<br>print(&quot;Confusion Matrix:&quot;)<br>print(confusion_matrix(y_true, y_pred))<br><br># Accuracy<br>print(&quot;Accuracy:&quot;, accuracy_score(y_true, y_pred))<br><br># Precision<br>print(&quot;Precision:&quot;, precision_score(y_true, y_pred))<br><br># Recall<br>print(&quot;Recall:&quot;, recall_score(y_true, y_pred))<br><br># F1 Score<br>print(&quot;F1 Score:&quot;, f1_score(y_true, y_pred))<br><br># Complete classification report<br>print(classification_report(y_true, y_pred))<br><br># ROC-AUC<br>print(&quot;ROC-AUC:&quot;, roc_auc_score(y_true, y_prob))<br><br># ROC Curve<br>fpr, tpr, thresholds = roc_curve(y_true, y_prob)</pre><h3>5.2 Visualising the ROC Curve</h3><pre>print(&quot;Specificity:&quot;, specificity)</pre><h3>5.2 Visualizing the ROC Curve</h3><pre>import matplotlib.pyplot as plt<br>from sklearn.metrics import roc_curve, roc_auc_score</pre><pre>fpr, tpr, thresholds = roc_curve(y_true, y_prob)</pre><pre>auc_score = roc_auc_score(y_true, y_prob)</pre><pre>plt.plot(<br>    fpr,<br>    tpr,<br>    label=f&quot;ROC Curve (AUC = {auc_score:.2f})&quot;<br>)</pre><pre>plt.plot([0, 1], [0, 1], linestyle=&quot;--&quot;)</pre><pre>plt.xlabel(&quot;False Positive Rate&quot;)<br>plt.ylabel(&quot;True Positive Rate&quot;)<br>plt.title(&quot;ROC Curve&quot;)</pre><pre>plt.legend()<br>plt.grid()<br>plt.show()</pre><h3>5.3 Regression Metrics in Python</h3><pre>from sklearn.metrics import (<br>    mean_absolute_error,<br>    mean_squared_error,<br>    r2_score<br>)</pre><pre>import numpy as np</pre><pre># Actual house prices<br>y_actual = [20, 30, 40, 50, 60]</pre><pre># Predicted house prices<br>y_predicted = [22, 28, 43, 47, 62]</pre><pre># MAE<br>mae = mean_absolute_error(y_actual, y_predicted)</pre><pre># MSE<br>mse = mean_squared_error(y_actual, y_predicted)</pre><pre># RMSE<br>rmse = np.sqrt(mse)</pre><pre># R2 Score<br>r2 = r2_score(y_actual, y_predicted)</pre><pre>print(&quot;MAE:&quot;, mae)<br>print(&quot;MSE:&quot;, mse)<br>print(&quot;RMSE:&quot;, rmse)<br>print(&quot;R2 Score:&quot;, r2)</pre><h3>Calculating Adjusted R² in Python</h3><pre>n = len(y_actual)<br>p = 2  # Number of independent variables</pre><pre>adjusted_r2 = 1 - (<br>    (1 - r2) * (n - 1) / (n - p - 1)<br>)</pre><pre>print(&quot;Adjusted R2:&quot;, adjusted_r2)</pre><p>Note: The value of p must represent the actual number of predictors in the regression model. The example uses p = 2 only for illustration.</p><h3>6. When to Use Which Evaluation Metric?</h3><p>Choosing the right metric depends on the problem, dataset, and consequences of making incorrect predictions.</p><p>Evaluation MetricWhen to UseAccuracyWhen classes are balanced and different errors have similar costsPrecisionWhen False Positives are expensiveRecallWhen False Negatives are expensiveSpecificityWhen correctly identifying negative cases is importantF1-ScoreWhen both Precision and Recall matter, especially with class imbalanceROC-AUCWhen evaluating how well a binary model separates classes across thresholdsMAEWhen average absolute error and easy interpretation are importantMSEWhen large errors should receive a much higher penaltyRMSEWhen large errors matter and the error should be expressed in the target’s unitsR²When measuring how much target variation is explained by a regression modelAdjusted R²When comparing regression models with different numbers of predictors</p><h3>Practical Examples</h3><p><strong>1. Medical Disease Detection</strong></p><p>Recall is particularly important because failing to identify a patient with a disease can be dangerous.</p><p><strong>2. Spam Email Detection</strong></p><p>Precision is important because we want to avoid classifying genuine emails as spam.</p><p><strong>3. Fraud Detection</strong></p><p>Recall and Precision are both important. We want to identify fraudulent transactions while avoiding too many false alarms.</p><p><strong>4. House Price Prediction</strong></p><p>MAE and RMSE help understand the average magnitude of price prediction errors.</p><p><strong>5. Sales Forecasting</strong></p><p>MAE, RMSE, and R² can help assess how accurately a model predicts future sales.</p><h3>7. Advantages and Limitations of Evaluation Metrics</h3><p>Evaluation metrics help us understand model performance, but no single metric is suitable for every Machine Learning problem.</p><h3>Advantages</h3><ol><li>Model Comparison: They help compare multiple models and select a suitable one.</li><li>Performance Measurement: They provide measurable information about prediction quality.</li><li>Error Identification: They help identify different types of prediction mistakes.</li><li>Model Improvement: They help us understand where a model needs improvement.</li><li>Business Decisions: They help choose models according to real-world requirements.</li></ol><h3>Limitations</h3><ol><li>Metric Dependency: Different metrics can produce different conclusions about the same model.</li><li>Dataset Dependency: Performance can change depending on the dataset and its class distribution.</li><li>Imbalanced Data: Accuracy may give misleading results when one class dominates.</li><li>Overfitting: Good performance on training data does not guarantee good performance on unseen data.</li><li>Business Context: Mathematical scores do not always represent the actual cost or impact of prediction errors.</li></ol><p><strong>Important:</strong> Evaluation should be performed on validation or test data that the model has not used for training. For a reliable estimate of generalization performance, the test dataset should remain separate from model selection and tuning.</p><h3>8. Conclusion</h3><p>Evaluation metrics are an essential part of every Machine Learning project because they help us understand how well a model performs on unseen data.</p><p>Classification metrics such as Accuracy, Precision, Recall, Specificity, F1-Score, and ROC-AUC help evaluate models that predict categories.</p><p>Regression metrics such as MAE, MSE, RMSE, R², and Adjusted R² help evaluate models that predict continuous numerical values.</p><p>The most important lesson is that <strong>a good Machine Learning model is not simply the model with the highest score. It is the model that performs well according to the requirements and real-world consequences of the problem.</strong></p><p>Understanding the strengths and limitations of each evaluation metric helps us make better decisions when developing, evaluating, and improving Machine Learning models.</p><h3>9. References and Learning Resources</h3><ol><li><a href="https://scikit-learn.org/stable/modules/model_evaluation.html">Scikit-learn — Model Evaluation</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html">Scikit-learn — Classification Metrics</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html">Scikit-learn — Confusion Matrix</a></li><li><a href="https://scikit-learn.org/stable/modules/model_evaluation.html#regression-metrics">Scikit-learn — Regression Metrics</a></li><li><a href="https://developers.google.com/machine-learning/crash-course/classification">Google Machine Learning Crash Course — Classification</a></li><li><a href="https://developers.google.com/machine-learning/crash-course/linear-regression">Google Machine Learning Crash Course — Regression</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=219a67e33e03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Processing with Python: Understanding Images, Pixels, Arrays & OpenCV]]></title>
            <link>https://medium.com/@harimadhavkonduru/image-processing-with-python-understanding-images-pixels-arrays-opencv-904fda74ff90?source=rss-8831d6d3079e------2</link>
            <guid isPermaLink="false">https://medium.com/p/904fda74ff90</guid>
            <dc:creator><![CDATA[Harimadhavkonduru]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 10:36:29 GMT</pubDate>
            <atom:updated>2026-11-05T10:37:55.369Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A beginner-friendly, end-to-end guide: from what a pixel is to building your first image processing project.</em></p><p>Every time you unlock your phone with your face, scan a QR code, or see a self-driving car video, a computer is “looking” at an image. But a computer does not see a photo the way we do. It sees <strong>numbers</strong>. In this article, we will understand how images become numbers, how Python (with NumPy and OpenCV) lets us work with those numbers, and how to put it all together in a small project.</p><p><strong>What you will learn:</strong></p><ul><li>What digital images and pixels are</li><li>How images are stored as NumPy arrays</li><li>RGB, BGR and grayscale channels</li><li>What OpenCV is and the basic functions you will use daily</li><li>How to build a complete image processing mini-project</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zd__brfbjNS8LmrjHM92kw.png" /></figure><h3>1. Images: How Computers Store Pictures</h3><p>A <strong>digital image</strong> is a grid of tiny coloured squares. Zoom in on any photo far enough and you will see the squares. Each square holds one number (or a few numbers) that tells the screen how bright, or what colour, that spot should be.</p><p>There are two broad ways to store pictures:</p><ul><li><strong>Raster images</strong> (JPG, PNG, BMP): a grid of pixels. This is what OpenCV works with.</li><li><strong>Vector images</strong> (SVG): mathematical shapes such as lines and curves. They scale without losing quality, but are not used for photo analysis.</li></ul><h3>2. Pixels: The Building Blocks</h3><p>A <strong>pixel</strong> (picture element) is the smallest unit of a digital image. Three ideas matter here:</p><ul><li><strong>Dimensions:</strong> width × height in pixels. A 512 × 512 image has 262,144 pixels.</li><li><strong>Pixel value:</strong> the number stored at each pixel. For a standard 8-bit image it ranges from 0 (black) to 255 (white).</li><li><strong>Colour channels:</strong> a grayscale pixel has 1 value; a colour pixel has 3 (red, green and blue).</li></ul><p>The figure below zooms into a 12 × 12 patch of a photo. Each cell is one pixel, and the number written on it is its brightness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-xLLCevUaJ5E_Zr4haIMQ.png" /><figcaption>Zooming into 144 pixels: what the computer actually sees is a table of numbers</figcaption></figure><h3>3. Arrays: Images as NumPy Arrays</h3><p>Once an image is loaded in Python, it is simply a <strong>NumPy array</strong>. That is why NumPy is the backbone of image processing: slicing, maths, and filtering all become fast array operations.</p><ul><li>Grayscale image → 2D array: (height, width)</li><li>Colour image → 3D array: (height, width, channels)</li></ul><pre>import cv2<br>import numpy as np</pre><pre>img = cv2.imread(&quot;sample.jpg&quot;)</pre><pre>print(type(img))     # &lt;class &#39;numpy.ndarray&#39;&gt;<br>print(img.shape)     # (512, 512, 3)  -&gt; height, width, channels<br>print(img.dtype)     # uint8          -&gt; values 0 to 255<br>print(img.size)      # 786432         -&gt; 512*512*3 total values</pre><pre>print(img[100, 200])        # one pixel -&gt; [B G R] values<br>print(img[100:200, 50:150]) # a 100x100 region (slicing)</pre><p><strong>Reading the shape:</strong> (512, 512, 3) means 512 rows, 512 columns and 3 colour values per pixel. The data type uint8 means each value is an unsigned 8-bit integer (0 to 255).</p><p><strong>Tip:</strong> because images are arrays, you can edit pixels directly. For example, img[0:100, 0:100] = [0, 0, 255] paints the top-left 100 × 100 square red (in BGR order).</p><h3>4. Channels: RGB, BGR and Grayscale</h3><p>A colour image is three images stacked together, one each for <strong>Red, Green and Blue</strong>. Mixing these three intensities produces every colour on your screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-p99yDiy5N87VzyVGDQItA.png" /><figcaption>The same photo split into its Red, Green and Blue channels</figcaption></figure><h3>The BGR gotcha</h3><p>This trips up almost every beginner: <strong>OpenCV loads colour images in BGR order, not RGB.</strong> Libraries like Matplotlib expect RGB. If you display an OpenCV image directly with Matplotlib, the colours look wrong (skin turns blue, as below). Always convert first:</p><pre>img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)</pre><p>Left: BGR displayed as RGB gives strange colours. Right: after conversion it looks correct</p><h3>Grayscale</h3><p>A grayscale image has a single channel, so it is smaller and faster to process. Many tasks (edge detection, thresholding, face detection) do not need colour at all, so converting to gray first is very common. A <strong>histogram</strong> shows how many pixels exist at each brightness level, which is useful for judging contrast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfJKB6LRyqLQbvYkC_fpLA.png" /><figcaption>Colour (3 channels) vs grayscale (1 channel), with the grayscale histogram</figcaption></figure><p>5. OpenCV: The Computer Vision Toolkit</p><p><strong>OpenCV</strong> (Open Source Computer Vision Library) is a free library for real-time computer vision. It is written in C++ for speed and has a very friendly Python interface. It supports reading and writing images and video, filtering, edge and contour detection, object and face detection, camera calibration, and even deep learning models.</p><p><strong>Why it matters:</strong> OpenCV is used in medical imaging, automated quality inspection in factories, number-plate recognition, surveillance, augmented reality and robotics. It is the usual first step before moving to deep learning for vision.</p><p><strong>Installation:</strong></p><pre>pip install opencv-python numpy matplotlib</pre><h3>6. Basic OpenCV Functions with Syntax and Examples</h3><p>All examples below use the same img (loaded in BGR) from the previous sections.</p><h3>6.1 Reading, showing and saving</h3><pre>img = cv2.imread(&quot;sample.jpg&quot;)            # read (BGR array; None if path is wrong)<br>gray = cv2.imread(&quot;sample.jpg&quot;, 0)        # read directly as grayscale</pre><pre>cv2.imshow(&quot;My Image&quot;, img)               # open a window (desktop Python)<br>cv2.waitKey(0)                            # wait for a key press<br>cv2.destroyAllWindows()                   # close windows</pre><pre>cv2.imwrite(&quot;output.jpg&quot;, img)            # save to disk</pre><p><strong>Note:</strong> in Google Colab or Jupyter, cv2.imshow does not work. Use Matplotlib (plt.imshow) or from google.colab.patches import cv2_imshow.</p><h3>6.2 Colour conversion</h3><pre>gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)<br>rgb  = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>hsv  = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)</pre><h3>6.3 Resize, crop, flip and rotate</h3><pre>small = cv2.resize(img, (200, 200))              # (width, height)  - note the order!<br>crop  = img[40:260, 130:350]                      # [y1:y2, x1:x2]   - NumPy slicing<br>flip  = cv2.flip(img, 1)                          # 1 = horizontal, 0 = vertical<br>M     = cv2.getRotationMatrix2D((256, 256), 30, 1.0)   # centre, angle, scale<br>rot   = cv2.warpAffine(img, M, (512, 512))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMJWitxIxgdUPA1WP6kYvQ.png" /><figcaption>Resize, crop, flip and rotate applied to the same image</figcaption></figure><p><strong>Common mistake:</strong> cv2.resize takes (width, height), but img.shape gives (height, width). Mixing them up gives a stretched image.</p><h3>6.4 Drawing shapes and text</h3><pre>cv2.rectangle(img, (150, 30), (330, 230), (0, 255, 0), 3)   # top-left, bottom-right, colour, thickness<br>cv2.circle(img, (240, 130), 8, (0, 0, 255), -1)              # centre, radius, colour, -1 = filled<br>cv2.line(img, (0, 500), (512, 380), (255, 0, 0), 3)          # start, end, colour, thickness<br>cv2.putText(img, &quot;Astronaut&quot;, (150, 25),<br>            cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*vN3tzquxRBvccJUzR39kmw.png" /><figcaption>Drawing a rectangle, circle, line and text label on an image</figcaption></figure><h3>6.5 Blurring, thresholding and edge detection</h3><pre>blur = cv2.GaussianBlur(img, (9, 9), 0)                      # kernel size must be odd<br>_, thr = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)    # pixel &gt; 127 becomes 255, else 0<br>edges = cv2.Canny(gray, 100, 200)                            # lower and upper thresholds</pre><ul><li><strong>Gaussian blur</strong> smooths the image and reduces noise.</li><li><strong>Thresholding</strong> converts gray to pure black and white, handy for separating an object from the background.</li><li><strong>Canny</strong> finds the outlines (edges) where brightness changes sharply.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Smnt5iyqeW_NzVrIH5XIeA.png" /><figcaption>Gaussian blur, binary threshold and Canny edge detection results</figcaption></figure><h3>Quick reference</h3><p>TaskFunctionRead / savecv2.imread(), cv2.imwrite()Displaycv2.imshow() or plt.imshow()Colour changecv2.cvtColor()Size and orientationcv2.resize(), cv2.flip(), cv2.warpAffine()Drawingcv2.rectangle(), cv2.circle(), cv2.line(), cv2.putText()Filteringcv2.GaussianBlur(), cv2.threshold(), cv2.Canny()</p><h3>7. Project: Detecting Object Outlines, Step by Step</h3><p>Let us combine everything into one mini-project: <strong>find and mark the main outlines (contours) in a photo.</strong> The same process is the foundation of tasks like counting objects, measuring shapes and document scanning.</p><h3>Step 1: Set up and load the image</h3><pre>import cv2<br>import matplotlib.pyplot as plt</pre><pre>img = cv2.imread(&quot;sample.jpg&quot;)<br>if img is None:<br>    raise FileNotFoundError(&quot;Image not found. Check the file path.&quot;)<br>print(&quot;Shape:&quot;, img.shape)</pre><h3>Step 2: Pre-process (grayscale and blur)</h3><p>Colour is not needed to find edges, and blurring removes small noise that would create false edges.</p><pre>gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)<br>blur = cv2.GaussianBlur(gray, (5, 5), 0)</pre><h3>Step 3: Detect edges</h3><pre>edges = cv2.Canny(blur, 80, 160)</pre><h3>Step 4: Find and filter contours</h3><p>A contour is a continuous curve along an edge. We ignore tiny ones (noise) using a minimum area.</p><pre>contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)<br>contours = [c for c in contours if cv2.contourArea(c) &gt; 150]<br>print(&quot;Objects found:&quot;, len(contours))</pre><h3>Step 5: Draw results and visualise</h3><pre>result = img.copy()                                   # keep the original untouched<br>cv2.drawContours(result, contours, -1, (0, 255, 0), 2)</pre><pre>plt.imshow(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))   # BGR -&gt; RGB for Matplotlib<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><h3>Step 6: Save the output</h3><pre>cv2.imwrite(&quot;output_contours.jpg&quot;, result)</pre><p>Our project pipeline: load, grayscale + blur, Canny edges, contours drawn (5 objects found)</p><p><strong>Ideas to extend this project:</strong> try different Canny thresholds, draw bounding boxes with cv2.boundingRect(), apply the pipeline to your own photos, or run it on a webcam stream with cv2.VideoCapture(0).</p><h3>Common Mistakes to Avoid</h3><ul><li>Forgetting that OpenCV uses <strong>BGR</strong>, not RGB.</li><li>Wrong file path: imread does not raise an error, it silently returns None.</li><li>Mixing up (width, height) in resize with (height, width) in shape.</li><li>Even-sized blur kernels: the kernel size must be odd (3, 5, 7, 9…).</li><li>Editing the original image: use img.copy() before drawing.</li></ul><h3>Conclusion</h3><p>Images are just NumPy arrays of numbers, pixels are the cells of that array, and channels are its layers. OpenCV gives us a fast toolbox to read, transform, filter and analyse those arrays. With about ten functions you can already build useful projects, and the same ideas carry directly into machine learning and deep learning for vision.</p><p>If this helped, try the project on your own images and share what you build!</p><p><em>#Python, #OpenCV, #Computer Vision, #Image Processing, #NumPy</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=904fda74ff90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Raw Data to Reliable Predictions: A Complete Machine Learning Workflow]]></title>
            <link>https://medium.com/@harimadhavkonduru/from-raw-data-to-reliable-predictions-a-complete-machine-learning-workflow-53ead8370b32?source=rss-8831d6d3079e------2</link>
            <guid isPermaLink="false">https://medium.com/p/53ead8370b32</guid>
            <dc:creator><![CDATA[Harimadhavkonduru]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 17:39:28 GMT</pubDate>
            <atom:updated>2026-10-17T17:39:28.344Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to the ML project pipeline, data preprocessing, train-test splitting, model building, and evaluation using Python.</em></p><p>Machine Learning (ML) is more than choosing an algorithm and training it. A successful ML project requires a systematic workflow that transforms raw data into meaningful insights and reliable predictions.</p><p>Imagine building a model to predict house prices. You collect property data, explore relationships between features, handle missing values, transform the data, train a model, evaluate its predictions, and finally deploy it for real-world use.</p><p>But what happens if the dataset contains missing values, inconsistent scales, extreme observations, or an imbalanced target? What if information from the test data accidentally influences training?</p><p>These challenges are why understanding the complete ML pipeline is essential.</p><p>In this article, we will explore three important areas:</p><ul><li><strong>Part A:</strong> The end-to-end Machine Learning project pipeline.</li><li><strong>Part B:</strong> Data preprocessing techniques in detail.</li><li><strong>Part C:</strong> Train-test splitting, model building, algorithm selection, evaluation, and data leakage.</li></ul><p>Let’s break the process down step by step.</p><h3>Part A: Understanding the Machine Learning Project Pipeline</h3><h3>1. What is an ML pipeline?</h3><p>An ML pipeline is a sequence of connected steps used to develop, evaluate, deploy, and maintain a machine learning model.</p><h3>The complete workflow</h3><p><strong>Problem Definition → Data Collection → EDA → Feature Engineering → Data Preprocessing → Model Training → Model Evaluation → Model Deployment → Monitoring and maintenance</strong></p><p>Each stage contributes to the success of the final model.</p><h3>Step 1: Problem Definition</h3><p>Before writing code, understand the problem you want to solve.</p><p>For example, a real estate company wants to estimate the selling price of a property based on its location, area, number of bedrooms, and age.</p><p>Questions to consider:</p><ul><li>What problem are we solving?</li><li>What output do we want to predict?</li><li>Who will use the prediction?</li><li>How will success be measured?</li></ul><p><strong>Example:</strong> Predict the selling price of a house in rupees.</p><p>This is a regression problem because the target variable is a continuous numerical value.</p><h3>Step 2: Data Collection</h3><p>Collect relevant data from reliable sources, such as:</p><ul><li>CSV and Excel files</li><li>SQL databases</li><li>APIs</li><li>Websites through permitted web scraping</li><li>Sensors and application logs</li></ul><p>Example dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYF35j1uNoAyk5hSv7ijHQ.png" /></figure><p>The features are the inputs used to make predictions. The target is the value the model must predict.</p><h3>Step 3: Exploratory Data Analysis (EDA)</h3><p>EDA helps us understand the dataset before training a model.</p><p>Common activities include:</p><ul><li>Checking rows, columns, and data types</li><li>Identifying missing and duplicate records</li><li>Studying numerical distributions</li><li>Exploring categorical values</li><li>Finding correlations and potential outliers</li><li>Visualizing relationships between features and the target</li></ul><p>Useful Python tools include pandas, matplotlib, and seaborn.</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br><br>df = pd.read_csv(&quot;house_prices.csv&quot;)<br>print(df.head())<br>print(df.shape)<br>print(df.info())<br>print(df.isnull().sum())<br>print(df.describe())<br>print(df.duplicated().sum())<br>df[&quot;Price&quot;].hist()<br>plt.show()</pre><p><strong>Why is EDA important?</strong> It helps identify data quality problems and patterns that influence preprocessing and model selection.</p><h3>Step 4: Feature Engineering</h3><p>Feature engineering involves creating or modifying features to make useful patterns easier for a model to learn.</p><p>For example, if a dataset contains a property’s construction year, we can derive its age:</p><pre>df[&quot;Property_Age&quot;] = 2026 - df[&quot;Construction_Year&quot;]</pre><p>Other examples include:</p><ul><li>Extracting month and day from dates</li><li>Calculating price per square foot</li><li>Combining related variables</li><li>Creating meaningful interaction features</li></ul><p>Good feature engineering can improve predictive performance. However, features must only use information that would actually be available at prediction time.</p><h3>Step 5: Data Preprocessing</h3><p>Real-world data is rarely ready for immediate model training.</p><p>Preprocessing prepares data by handling missing values, encoding categories, scaling numerical features, treating outliers when appropriate, and applying other necessary transformations.</p><p>We will examine these techniques in Part B.</p><h3>Step 6: Model Training</h3><p>At this stage, we select an appropriate algorithm and train it on the prepared training data.</p><p>For example:</p><ul><li>Linear Regression for a numerical target</li><li>Logistic Regression for a classification target</li><li>Decision Trees for classification or regression</li><li>Random Forests for classification or regression</li></ul><p>The model learns patterns from the training examples.</p><h3>Step 7: Model Evaluation</h3><p>A trained model must be evaluated on data it did not use during training.</p><p>For regression, we can measure prediction errors using MAE, RMSE, (R²) and other relevant metrics.</p><p>For classification, we can use accuracy, precision, recall, F1-score, Confusion matrix, AUC-ROC and other relevant metrics.</p><p>The right metric depends on the business problem, not simply on which score looks highest.</p><h3>Step 8: Deployment</h3><p>Deployment makes the trained model available for practical use.</p><p>Common approaches include:</p><ul><li>REST APIs using FastAPI</li><li>Web applications using Streamlit</li><li>Cloud-hosted prediction services</li><li>Integration into existing business systems</li></ul><p>For example, a user enters a property’s details into a web application and receives a predicted selling price.</p><h3>Step 9: Monitoring and Maintenance</h3><p>Model performance may decline as real-world data changes.</p><p>Monitoring involves tracking:</p><ul><li>Prediction quality</li><li>Changes in input data distributions</li><li>Missing or invalid incoming values</li><li>Prediction latency and service errors</li><li>Changes in business outcomes</li></ul><p>When performance degrades, the model may require investigation, retraining, or replacement.</p><p><strong>Key takeaway:</strong> Machine Learning is a continuous process. Deployment is not the end of the project; it is the beginning of real-world operation.</p><h3>Part B: Data Preprocessing — A Deep Dive</h3><p>Data preprocessing converts raw data into a form that is suitable for machine learning.</p><p>Let’s use a simple customer dataset throughout this section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKz2zLzAQ8T0yzuyF8Up1g.png" /></figure><p>This dataset illustrates missing values, numerical features with different scales, categorical variables, and a potentially extreme income value.</p><h3>1. Missing Value Handling</h3><h4>What is it, and why is it needed?</h4><p>Missing values occur when information is unavailable or was not recorded.</p><p>For example, a customer’s monthly income may be blank because they did not provide it.</p><p>Many machine learning algorithms cannot directly handle missing values, while others have specific support for them. Appropriate handling prevents unnecessary data loss and reduces the risk of misleading patterns.</p><h4>Common techniques</h4><p><strong>A. Deletion</strong></p><p>Remove rows or columns with missing values.</p><pre>df.dropna()<br>df.dropna(axis=1)</pre><p>Use deletion when missingness is limited and removing the affected observations or columns will not significantly harm the dataset.</p><p><strong>Advantages:</strong> Simple and easy to implement.</p><p><strong>Limitations:</strong> May discard valuable information and introduce bias if the missingness is systematic.</p><p><strong>B. Mean imputation</strong></p><p>Replace missing numerical values with the mean.</p><pre>from sklearn.impute import SimpleImputer<br><br>imputer = SimpleImputer(strategy=&quot;mean&quot;)</pre><p>Suitable for numerical features when the mean is representative of the data. It can be sensitive to outliers.</p><p><strong>C. Median imputation</strong></p><p>Replace missing numerical values with the median.</p><pre>imputer = SimpleImputer(strategy=&quot;median&quot;)</pre><p>The median is generally more robust to extreme values than the mean, making it useful for skewed numerical distributions.</p><p><strong>D. Mode imputation</strong></p><p>Replace missing categorical values with the most frequent category.</p><pre>imputer = SimpleImputer(strategy=&quot;most_frequent&quot;)</pre><p>This is a simple option for categorical features, although it may overrepresent the most common category.</p><p><strong>E. Constant-value imputation</strong></p><p>Replace missing values with a fixed value or category.</p><pre>imputer = SimpleImputer(<br>    strategy=&quot;constant&quot;,<br>    fill_value=&quot;Unknown&quot;<br>)</pre><p>This can be useful when missingness itself carries information. However, an arbitrary constant may create misleading patterns if used without considering the data.</p><p><strong>F. Advanced imputation</strong></p><p>Methods such as KNN imputation and iterative imputation estimate missing values using relationships between observations or features.</p><p>They can capture more complex patterns but are more computationally expensive and require careful validation.</p><h4>How should you choose?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzyYkDho7FXMkaF6aaPS1g.png" /></figure><p><strong>Common mistake:</strong> Calculating imputation values using the complete dataset before splitting into training and test sets. This can leak information from the test set into the training process.</p><p>Fit the imputer on training data and apply the learned values to the test data.</p><h3>2. Feature Scaling</h3><h4>What is feature scaling?</h4><p>Feature scaling changes the numerical ranges of features so that variables with large magnitudes do not dominate certain algorithms.</p><p>Consider a dataset containing:</p><ul><li>Age: 18–65</li><li>Monthly income: ₹10,000–₹2,00,000</li></ul><p>Income has a much larger numerical range than age. Distance-based algorithms such as KNN and many gradient-based models can be sensitive to such differences.</p><p>Tree-based models generally do not require scaling in the same way.</p><h4>A. Min-Max Scaling</h4><p>Min-Max Scaling transforms values into a specified range, commonly 0 to 1.</p><p>[<br>x’=\frac{x-x_{\min}}{x_{\max}-x_{\min}}<br>]</p><p>Example: If ages range from 20 to 60, an age of 40 becomes:</p><p>[<br>x’=\frac{40–20}{60–20}=0.5<br>]</p><p>Python implementation:</p><pre>from sklearn.preprocessing import MinMaxScaler<br><br>scaler = MinMaxScaler()<br>X_scaled = scaler.fit_transform(X)</pre><p><strong>When to use:</strong> When a bounded range is useful, such as in some neural network workflows or distance-based methods.</p><p><strong>Advantages:</strong> Preserves relative ordering and maps observed training values to a common range.</p><p><strong>Limitations:</strong> Sensitive to outliers. An extreme value can compress most other observations into a narrow interval. New values outside the training range can transform to values below 0 or above 1.</p><h4>B. Standardization</h4><p>Standardization transforms a feature to have a mean of approximately 0 and a standard deviation of approximately 1 on the data used to fit the scaler.</p><p>[<br>z=\frac{x-\mu}{\sigma}<br>]</p><p>Where:</p><ul><li>(x) is the original value</li><li>(\mu) is the training mean</li><li>(\sigma) is the training standard deviation</li></ul><p>For an observation equal to 70, with mean 50 and standard deviation 10:</p><p>[<br>z=\frac{70–50}{10}=2<br>]</p><p>The observation is two standard deviations above the mean.</p><p>Python implementation:</p><pre>from sklearn.preprocessing import StandardScaler<br><br>scaler = StandardScaler()<br>X_scaled = scaler.fit_transform(X)</pre><p><strong>When to use:</strong> A common choice for Linear Regression with regularization, Logistic Regression, SVM, KNN, and other scale-sensitive workflows.</p><p><strong>Advantages:</strong> Centers features and puts them on a comparable scale.</p><p><strong>Limitations:</strong> Sensitive to outliers, and the transformed values are not restricted to a fixed range.</p><h4>Scaling comparison</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiF3rngEYgmIFI6HE0AhuQ.png" /></figure><p><strong>Important:</strong> Scaling is not automatically necessary for every algorithm. Choose preprocessing based on the model and data characteristics.</p><h3>3. Categorical Encoding</h3><h4>What is encoding?</h4><p>Categorical encoding converts non-numerical categories into a representation that a machine learning algorithm can process.</p><p>For example, a dataset may contain cities such as Hyderabad, Chennai, and Bengaluru.</p><p>These categories do not naturally represent numerical magnitudes.</p><h4>A. Label Encoding</h4><p>Label encoding assigns integer values to categories.</p><p>Example:</p><ul><li>Hyderabad → 0</li><li>Chennai → 1</li><li>Bengaluru → 2</li></ul><pre>from sklearn.preprocessing import LabelEncoder<br><br>encoder = LabelEncoder()<br>y_encoded = encoder.fit_transform(y)</pre><p>LabelEncoder is commonly used for target labels in classification.</p><p><strong>Advantages:</strong> Compact and straightforward.</p><p><strong>Limitations:</strong> If applied to nominal input features, the numbers may imply an artificial order. For example, Bengaluru = 2 does not mean it is greater than Hyderabad = 0.</p><p>For nominal input features, one-hot encoding is often a better choice.</p><h4>B. One-Hot Encoding</h4><p>One-hot encoding creates a separate binary feature for each category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UYP58KiqTg28m0rRnfcd5A.png" /></figure><p>Python:</p><pre>import pandas as pd<br><br>encoded = pd.get_dummies(<br>    df,<br>    columns=[&quot;City&quot;],<br>    dtype=int<br>)</pre><p>For production ML pipelines, OneHotEncoder is often preferable because it integrates with scikit-learn pipelines and supports strategies for previously unseen categories.</p><p><strong>Advantages:</strong> Avoids imposing a false numerical order.</p><p><strong>Limitations:</strong> Can create many columns when a feature has thousands of distinct categories.</p><h4>C. Ordinal Encoding</h4><p>Ordinal encoding assigns values according to a meaningful order.</p><p>For example:</p><ul><li>Undergraduate → 1</li><li>Graduate → 2</li><li>Postgraduate → 3</li></ul><pre>from sklearn.preprocessing import OrdinalEncoder<br><br>encoder = OrdinalEncoder(<br>    categories=[[<br>        &quot;Undergraduate&quot;,<br>        &quot;Graduate&quot;,<br>        &quot;Postgraduate&quot;<br>    ]]<br>)<br>encoded = encoder.fit_transform(<br>    df[[&quot;Education&quot;]]<br>)</pre><p><strong>When to use:</strong> When categories have a genuine ranking, such as education levels or satisfaction ratings.</p><p><strong>Advantages:</strong> Compact representation that preserves the specified order.</p><p><strong>Limitations:</strong> The numerical gaps may imply equal distances between categories, even when the real-world differences are not equal.</p><h4>D. Other encoding techniques</h4><ul><li><strong>Binary encoding:</strong> Represents categories using binary digits; useful for some high-cardinality features.</li><li><strong>Frequency encoding:</strong> Replaces categories with their frequency in the training data.</li><li><strong>Target encoding:</strong> Uses target statistics associated with categories. It requires careful validation and regularization to avoid overfitting and leakage.</li><li><strong>Hash encoding:</strong> Maps categories into a fixed number of numerical features, potentially causing collisions.</li></ul><h4>Which encoding should you choose?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqDm6yeXm9ogLp9ASEGWNw.png" /></figure><p><strong>Common mistake:</strong> Encoding categories in an arbitrary order and assuming the resulting numbers represent meaningful quantities.</p><h3>4. Outlier Detection and Treatment</h3><h4>What is an outlier?</h4><p>An outlier is an observation that differs substantially from the rest of the data.</p><p>In our customer dataset, a monthly income of ₹20,00,000 may be unusual compared with incomes of ₹30,000–₹90,000.</p><p>However, an unusual observation is not automatically incorrect. It may represent a legitimate high-income customer.</p><h4>A. Interquartile Range (IQR)</h4><p>The IQR measures the spread of the middle 50% of observations.</p><p>[<br>IQR=Q_3-Q_1<br>]</p><p>The common IQR rule defines the following potential outlier boundaries:</p><p>[<br>L=Q_1–1.5(IQR)<br>]</p><p>[<br>U=Q_3+1.5(IQR)<br>]</p><p>Values outside these boundaries are flagged for investigation.</p><pre>Q1 = df[&quot;Monthly_Income&quot;].quantile(0.25)<br>Q3 = df[&quot;Monthly_Income&quot;].quantile(0.75)<br><br>IQR = Q3 - Q1<br>lower = Q1 - 1.5 * IQR<br>upper = Q3 + 1.5 * IQR<br>outliers = df[<br>    (df[&quot;Monthly_Income&quot;] &lt; lower) |<br>    (df[&quot;Monthly_Income&quot;] &gt; upper)<br>]</pre><h4>B. Z-score</h4><p>A z-score measures how far a value is from the mean in standard deviation units.</p><p>[<br>z=\frac{x-\mu}{\sigma}<br>]</p><p>A value with an absolute z-score above 3 is sometimes flagged for investigation. This rule is most interpretable when the distribution is reasonably well behaved; it is not a universal outlier definition.</p><h4>C. Treatment methods</h4><ol><li><strong>Correction:</strong> Fix an invalid value using a verified source.</li></ol><p><strong>2. Removal:</strong> Remove observations confirmed to be errors or inappropriate for the intended analysis.</p><p><strong>3. Capping :</strong> Limit extreme values to selected boundaries.</p><p><strong>4. Transformation:</strong> Apply a log transformation to suitable positive, highly skewed variables.</p><p><strong>5. Robust methods:</strong> Use methods less sensitive to extreme values.</p><p>Example of capping:</p><pre>df[&quot;Monthly_Income_Capped&quot;] = (<br>    df[&quot;Monthly_Income&quot;].clip(<br>        lower=lower,<br>        upper=upper<br>    )<br>)</pre><p>In a real ML workflow, calculate the clipping boundaries using training data only.</p><p><strong>Advantages:</strong> Appropriate treatment can reduce the influence of extreme observations.</p><p><strong>Limitations:</strong> Removing valid extremes can destroy useful information. Capping also changes the original values and may reduce the model’s ability to learn genuine extreme behavior.</p><p><strong>Best practice:</strong> Investigate why a value is unusual before deciding how to treat it.</p><h3>5. Data Transformation</h3><p>Data transformation changes the representation of a variable to make it more suitable for analysis or modeling.</p><p>It is different from basic cleaning: the values may be valid, but their distribution or mathematical form may make them difficult for a particular model.</p><h4>Common transformation techniques</h4><p><strong>A. Log transformation</strong></p><p>For positive, right-skewed data, a logarithm can reduce skewness and compress large values.</p><p>[<br>x’=\log(1+x)<br>]</p><p>Python:</p><pre>import numpy as np<br><br>df[&quot;Income_Log&quot;] = np.log1p(<br>    df[&quot;Monthly_Income&quot;]<br>)</pre><p>Use it when a variable is strongly right-skewed and the transformation makes sense for the application.</p><p><strong>Advantages:</strong> Compresses large values and may improve the behavior of certain models.</p><p><strong>Limitations:</strong> Changes interpretation, and a log transformation cannot be applied directly to arbitrary negative values without a carefully considered alternative.</p><p><strong>B. Power transformations</strong></p><p>Yeo-Johnson and Box-Cox are examples of power transformations used to make numerical distributions more suitable for some models. Box-Cox requires positive input, whereas Yeo-Johnson supports zero and negative values.</p><p><strong>C. Date and time transformations</strong></p><p>A timestamp can be converted into useful features such as year, month, day of week, or hour.</p><pre>df[&quot;Order_Date&quot;] = pd.to_datetime(<br>    df[&quot;Order_Date&quot;]<br>)</pre><pre>df[&quot;Order_Month&quot;] = df[&quot;Order_Date&quot;].dt.month<br>df[&quot;Order_Day&quot;] = df[&quot;Order_Date&quot;].dt.day<br>df[&quot;Order_Weekday&quot;] = (<br>    df[&quot;Order_Date&quot;].dt.dayofweek<br>)</pre><p>For cyclical features such as hour of day or month, sine and cosine encodings can preserve their cyclical nature.</p><p><strong>D. Binning</strong></p><p>Binning converts a continuous feature into intervals, such as age groups.</p><pre>df[&quot;Age_Group&quot;] = pd.cut(<br>    df[&quot;Age&quot;],<br>    bins=[0, 25, 40, 60, 120],<br>    labels=[<br>        &quot;Young&quot;,<br>        &quot;Adult&quot;,<br>        &quot;Middle-aged&quot;,<br>        &quot;Senior&quot;<br>    ]<br>)</pre><p>Binning can improve interpretability but may discard useful numerical detail.</p><p><strong>Common mistake:</strong> Applying a transformation simply because it is available. Always check whether it is appropriate for the feature, the algorithm, and the business objective.</p><h3>6. Feature Selection</h3><h4>What is feature selection?</h4><p>Feature selection identifies a useful subset of input variables while removing irrelevant, redundant, or noisy features.</p><p>For example, a house-price model may contain property area, location, number of bedrooms, and a customer record ID.</p><p>A record ID usually does not provide meaningful predictive information and may encourage the model to learn accidental patterns.</p><h4>Common techniques</h4><p><strong>A. Filter methods</strong></p><p>Use statistical measures to assess features before fitting the final predictive model.</p><p>Examples:</p><ul><li>Correlation analysis</li><li>Chi-square tests for suitable categorical classification features</li><li>ANOVA F-tests</li><li>Variance thresholds</li></ul><p><strong>B. Wrapper methods</strong></p><p>Evaluate subsets of features using a model.</p><p>Examples include Recursive Feature Elimination (RFE) and sequential feature selection.</p><p>These can be effective but may be computationally expensive.</p><p><strong>C. Embedded methods</strong></p><p>Select or reduce features during model training.</p><p>Examples include:</p><ul><li>L1- regularized models, which can drive some coefficients to zero</li><li>Tree-based models that provide feature importance measures</li></ul><p>Feature importance does not automatically establish causation or guarantee that a feature is reliable.</p><h4>Why is feature selection useful?</h4><ul><li>Reduces the number of input features</li><li>Can improve computational efficiency</li><li>May reduce overfitting</li><li>Can make the model easier to interpret</li></ul><p>However, removing a feature solely because it has low individual correlation can be a mistake: it may still contribute useful information through nonlinear relationships or interactions.</p><p><strong>Critical rule:</strong> Feature selection must be learned using training data only. Selecting features using the full dataset can leak information from the test set.</p><h3>7. Handling Class Imbalance</h3><h4>What is class imbalance?</h4><p>Class imbalance occurs when one target class appears much more frequently than another.</p><p>Imagine a fraud detection dataset containing 99% legitimate transactions and 1% fraudulent transactions.</p><p>A model that predicts every transaction as legitimate achieves 99% accuracy but detects no fraud.</p><p>This illustrates why accuracy alone can be misleading.</p><h4>Common techniques</h4><p><strong>A. Random oversampling</strong></p><p>Increase the representation of the minority class by sampling its existing observations, potentially with replacement.</p><p><strong>Advantage:</strong> Gives the model more minority-class examples during training.</p><p><strong>Limitation:</strong> Can increase overfitting because duplicated observations provide no genuinely new information.</p><p><strong>B. Random undersampling</strong></p><p>Reduce the number of majority-class observations.</p><p><strong>Advantage:</strong> Reduces training cost and can improve class balance.</p><p><strong>Limitation:</strong> May discard useful information from the majority class.</p><p><strong>C. SMOTE</strong></p><p>Synthetic Minority Over-sampling Technique creates synthetic minority-class observations using relationships between neighboring minority-class examples.</p><p><strong>Advantage:</strong> Adds synthetic variation rather than simply duplicating existing observations.</p><p><strong>Limitation:</strong> Synthetic observations may be unrealistic, especially when classes overlap or the feature space is complex.</p><p><strong>D. Class weights</strong></p><p>Some algorithms allow higher penalties for mistakes on the minority class.</p><pre>from sklearn.linear_model import LogisticRegression<br><br>model = LogisticRegression(<br>    class_weight=&quot;balanced&quot;,<br>    max_iter=1000<br>)</pre><p>This is a useful baseline, but it does not guarantee improved performance on the metric that matters.</p><h4>How should you evaluate an imbalanced model?</h4><p>Consider:</p><ul><li>Precision</li><li>Recall</li><li>F1-score</li><li>PR-AUC or average precision</li><li>Balanced accuracy</li><li>Confusion matrix</li></ul><p>Choose the metric according to the cost of false positives and false negatives.</p><p>For example, in fraud detection, missing a fraudulent transaction may be more costly than flagging a legitimate transaction for review.</p><p><strong>Important:</strong> Apply oversampling, undersampling, or SMOTE only to the training data, preferably within each training fold during cross-validation. Keep the test set at its natural class distribution so evaluation reflects the real use case.</p><h3>Part C: Train-Test Split and Model Building</h3><h3>1. What is train-test splitting?</h3><p>Train-test splitting divides the available dataset into separate subsets with different purposes.</p><ul><li><strong>Training set:</strong> Used to learn model parameters and fit preprocessing steps.</li><li><strong>Test set:</strong> Used at the end to evaluate the final modeling workflow on unseen observations.</li></ul><p>For example, if a dataset contains 1,000 records, an 80:20 split gives approximately 800 training records and 200 test records.</p><p>The goal is to estimate how well the model generalizes to new data.</p><h3>2. Choosing the split ratio</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQrMqKdfW7BdZPDG57zxVQ.png" /></figure><p>There is no universally best ratio. The appropriate choice depends on dataset size, variability, class balance, and the evaluation requirements.</p><p>For classification, stratified splitting can help preserve the class proportions in both subsets.</p><pre>from sklearn.model_selection import train_test_split<br><br>X = df.drop(columns=[&quot;Purchased&quot;])<br>y = df[&quot;Purchased&quot;]<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.20,<br>    random_state=42,<br>    stratify=y<br>)</pre><p>Use stratify=y for suitable classification tasks. Do not apply it indiscriminately to regression problems.</p><p><strong>Special cases:</strong></p><ul><li><strong>Time-series data:</strong> Split chronologically when future predictions are the goal.</li><li><strong>Grouped observations:</strong> Keep related records, such as multiple rows from the same customer, together where necessary.</li><li><strong>Small datasets:</strong> Cross-validation can help make better use of the available training data.</li></ul><h3>3. What is model building and training?</h3><p>Model building is the process of choosing an algorithm, preparing its inputs, fitting it to training data, and assessing its behavior.</p><p>For a supervised learning task, we typically provide:</p><ul><li>(X): input features</li><li>(y): target values</li></ul><p>The model learns a function that maps the input features to predictions:</p><p>[<br>\hat{y}=f(X)<br>]</p><p>Here, (\hat{y}) represents the predicted target.</p><p>For Linear Regression, the relationship can be expressed as:</p><p>[<br>\hat{y}=b_0+b_1x_1+b_2x_2+\cdots+b_nx_n<br>]</p><p>The model estimates coefficients that help predict the target from the input features.</p><p>For classification, models learn patterns that distinguish classes and may produce either class predictions or class probabilities.</p><h3>4. Selecting a suitable ML algorithm</h3><p>The first decision is to identify the problem type.</p><h4>Regression vs. classification</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmqfhmIfHKuaCE0_gjvgrQ.png" /></figure><h4>A practical algorithm-selection guide</h4><p><strong>Linear Regression</strong></p><p>Start with Linear Regression for a numerical target when a linear relationship is a reasonable initial assumption.</p><ul><li>Easy to interpret</li><li>Useful baseline for regression</li><li>Can struggle with nonlinear relationships and influential outliers</li></ul><p><strong>Logistic Regression</strong></p><p>A useful baseline for binary or multiclass classification.</p><ul><li>Interpretable coefficients in suitable settings</li><li>Can produce probabilities</li><li>May underfit complex nonlinear patterns without feature engineering</li></ul><p><strong>K-Nearest Neighbors (KNN)</strong></p><p>Predicts using nearby observations.</p><ul><li>Simple and intuitive</li><li>Often sensitive to feature scales and irrelevant features</li><li>Prediction can be computationally expensive on large datasets</li></ul><p><strong>Decision Tree</strong></p><p>Learns decision rules from features.</p><ul><li>Captures non linear relationships</li><li>Easy to visualise for smaller trees</li><li>Can overfit if not appropriately constrained</li></ul><p><strong>Random Forest</strong></p><p>Combines multiple decision trees.</p><ul><li>Often performs well on tabular datasets</li><li>Captures complex interactions</li><li>Can be less interpretable than a single tree and may require more computational resources</li></ul><p><strong>Support Vector Machine (SVM)</strong></p><p>Can be useful for classification and regression, particularly on appropriately scaled datasets.</p><ul><li>Can model non linear boundaries with suitable kernels</li><li>May work well in high-dimensional feature spaces</li><li>Kernel SVMs can become expensive on large datasets</li></ul><p><strong>My approach:</strong> Begin with a simple baseline, compare suitable algorithms using consistent validation data and metrics, tune promising candidates, and select the model based on generalization, interpretability, and operational requirements.</p><p>There is no single algorithm that performs best on every dataset.</p><h3>5. Model Evaluation: Choosing the Right Metrics</h3><p>A model is only as useful as its performance on the task it is designed to solve.</p><p>Different metrics measure different aspects of predictive quality.</p><h4>A. Classification metrics</h4><p>Consider the following terms:</p><ul><li><strong>True Positive (TP):</strong> Correctly predicted positive case.</li><li><strong>True Negative (TN):</strong> Correctly predicted negative case.</li><li><strong>False Positive (FP):</strong> Negative case incorrectly predicted positive.</li><li><strong>False Negative (FN):</strong> Positive case incorrectly predicted negative.</li></ul><p><strong>Accuracy</strong></p><p>The proportion of all predictions that are correct.</p><p>[<br>Accuracy=\frac{TP+TN}{TP+TN+FP+FN}<br>]</p><p>Useful when class distribution and error costs make overall correctness meaningful. It can be misleading on imbalanced datasets.</p><p><strong>Precision</strong></p><p>The proportion of predicted positive cases that are actually positive.</p><p>[<br>Precision=\frac{TP}{TP+FP}<br>]</p><p>Useful when false positives are costly.</p><p><strong>Recall</strong></p><p>The proportion of actual positive cases that the model successfully identifies.</p><p>[<br>Recall=\frac{TP}{TP+FN}<br>]</p><p>Useful when missing positive cases is costly.</p><p><strong>F1-score</strong></p><p>The harmonic mean of precision and recall.</p><p>[<br>F1=2\cdot\frac{Precision\cdot Recall}{Precision+Recall}<br>]</p><p>Useful when both precision and recall matter. It does not account for true negatives directly.</p><p><strong>ROC-AUC</strong></p><p>Measures how well a classifier ranks positive cases above negative cases across different decision thresholds. It can be less informative than precision-recall analysis when the positive class is extremely rare.</p><p>For multiclass classification, choose appropriate averaging strategies such as macro, micro, or weighted averages.</p><h4>B. Regression metrics</h4><p><strong>Mean Absolute Error (MAE)</strong></p><p>The average absolute difference between actual and predicted values.</p><p>[<br>MAE=\frac{1}{n}\sum_{i=1}^{n}|y_i-\hat{y}_i|<br>]</p><p>Easy to interpret in the target’s original units.</p><p><strong>Mean Squared Error (MSE)</strong></p><p>The average squared prediction error.</p><p>[<br>MSE=\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y}_i)²<br>]</p><p>Penalizes large errors more heavily than MAE.</p><p><strong>Root Mean Squared Error (RMSE)</strong></p><p>The square root of MSE.</p><p>[<br>RMSE=\sqrt{\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y}_i)²}<br>]</p><p>Expressed in the target’s units and more sensitive to large errors than MAE.</p><p><strong>R-squared ((R²))</strong></p><p>Measures performance relative to a baseline that predicts the mean target value.</p><p>[<br>R²=1-\frac{\sum_i(y_i-\hat{y}_i)²}{\sum_i(y_i-\bar{y})²}<br>]</p><p>An (R²) of 1 indicates perfect predictions on the evaluated data; 0 indicates performance equivalent to the mean-prediction baseline under this definition. It can be negative when the model performs worse than that baseline.</p><h4>Classification vs. regression metrics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSJ9v4O9gzWx82RWjxh_7g.png" /></figure><p>Always choose metrics based on the real objective. A lower RMSE is not automatically more valuable than a lower MAE, and a high accuracy score does not necessarily mean a classifier is useful.</p><h3>6. Why must preprocessing be fitted only on training data?</h3><p>This is one of the most important concepts in an ML workflow: <strong>data leakage</strong>.</p><p>Data leakage occurs when information that would not legitimately be available during training influences model development or evaluation. It can make test performance appear better than the model’s true generalization performance.</p><p>Imagine splitting a dataset into training and test sets. If you calculate the mean and standard deviation using the entire dataset before splitting, information from the test set influences the preprocessing parameters.</p><p>The model has not directly trained on the test labels, but the evaluation process is no longer fully independent.</p><h4>The correct workflow</h4><p>&lt;CodeBlock language=”mermaid” editable={true}&gt;flowchart TD<br>A[“Raw dataset”] → B[“Split into train and test”]<br>B → C[“Fit preprocessing on training data”]<br>C → D[“Transform training data”]<br>B → E[“Transform test data using fitted preprocessing”]<br>D → F[“Train model”]<br>F → G[“Predict on transformed test data”]<br>E → G<br>G → H[“Evaluate final performance”]&lt;/CodeBlock&gt;</p><h4>Incorrect approach</h4><pre># Incorrect: learns preprocessing statistics<br># from both training and test data.<br>X_scaled = scaler.fit_transform(X)<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    X_scaled, y, test_size=0.2, random_state=42<br>)</pre><h4>Correct approach</h4><pre>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br>X_test_scaled = scaler.transform(X_test)<br></pre><p>Notice the difference:</p><ul><li>fit_transform() learns the preprocessing parameters from the training data and transforms it.</li><li>transform() applies those already-learned parameters to the test data without refitting.</li></ul><p>The same principle applies to imputation, feature selection, outlier thresholds, target encoding, and other learned preprocessing steps.</p><h4>A better solution: scikit-learn pipelines</h4><p>Pipelines help keep preprocessing and model training together, reducing the risk of inconsistent transformations and data leakage.</p><p>The following example creates a regression workflow with missing-value imputation, scaling, and Linear Regression.</p><pre>from sklearn.pipeline import Pipeline<br>from sklearn.impute import SimpleImputer<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.linear_model import LinearRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_absolute_error<br><br>X = df[[&quot;Area&quot;, &quot;Bedrooms&quot;, &quot;Property_Age&quot;]]<br>y = df[&quot;Price&quot;]<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br>model = Pipeline([<br>    (&quot;imputer&quot;, SimpleImputer(strategy=&quot;median&quot;)),<br>    (&quot;scaler&quot;, StandardScaler()),<br>    (&quot;regressor&quot;, LinearRegression())<br>])<br>model.fit(X_train, y_train)<br>predictions = model.predict(X_test)<br>print(&quot;MAE:&quot;, mean_absolute_error(y_test, predictions))</pre><p>This is a basic regression example; it assumes the selected features are numerical and the target is available. Categorical columns would require appropriate encoding, often through a ColumnTransformer.</p><p>The pipeline learns the imputation values and scaling parameters from the training data. At prediction time, the same fitted transformations are applied automatically.</p><p>For cross-validation and hyperparameter tuning, putting preprocessing inside the pipeline is particularly valuable because each training fold learns its own preprocessing parameters.</p><p>For further reading, see the scikit-learn documentation on <a href="https://scikit-learn.org/stable/common_pitfalls.html">common pitfalls and data leakage</a>.</p><h3>Final Revision: The Complete ML Workflow at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVfDf1gxPZKNj7nDX5h0fQ.png" /></figure><h3>Quick comparison: preprocessing techniques</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qu_KLZn8Ycvpn5tWXRijAg.png" /></figure><h3>My key takeaways</h3><ol><li>A successful ML project starts with a clearly defined problem, not an algorithm.</li><li>EDA helps uncover data-quality issues before modeling.</li><li>Preprocessing should be selected according to the data and the algorithm.</li><li>Regression and classification require different evaluation approaches.</li><li>Train-test splitting helps estimate generalisation to unseen observations.</li><li>Fitting preprocessing on the complete dataset can cause data leakage.</li><li>A scikit- learn pipeline makes the workflow more consistent and reproducible.</li><li>Deployment and monitoring are essential parts of the ML lifecycle.</li></ol><h3>Conclusion</h3><p>Machine Learning is not just about training a model and checking its accuracy. It is about building a reliable process that turns raw data into useful predictions.</p><p>Understanding preprocessing, choosing appropriate algorithms, evaluating with meaningful metrics, and preventing data leakage are fundamental skills for anyone learning Data Science.</p><p>As I continue learning Machine Learning, I am focusing on understanding not only <em>how</em> to implement each technique, but also <em>why</em> and <em>when</em> to use it.</p><p>The goal is simple: build models that work not just on training data, but on real-world, unseen data.</p><p><strong>What preprocessing technique do you find most challenging — feature scaling, categorical encoding, outlier treatment, or class imbalance handling? Share your thoughts in the comments!</strong></p><h3>References and Further Reading</h3><ol><li><a href="https://scikit-learn.org/stable/common_pitfalls.html">Scikit-learn — Common Pitfalls and Recommended Practices</a></li><li><a href="https://scikit-learn.org/stable/modules/preprocessing.html">Scikit-learn — Preprocessing Data</a></li><li><a href="https://scikit-learn.org/stable/modules/model_evaluation.html">Scikit-learn — Model Evaluation</a></li><li><a href="https://scikit-learn.org/stable/modules/feature_selection.html">Scikit-learn — Feature Selection</a></li><li><a href="https://imbalanced-learn.org/stable/common_pitfalls.html">Imbalanced-learn — Common Pitfalls and Recommended Practices</a></li></ol><p><em>Disclaimer: The examples are educational demonstrations. Actual preprocessing and model choices should be validated against the dataset, task requirements, and real-world evaluation criteria.</em></p><p>#Machine Learning #Data Science #Python #Artificial Intelligence #Data Preprocessing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ead8370b32" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>