<?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 Sharanya on Medium]]></title>
        <description><![CDATA[Stories by Sharanya on Medium]]></description>
        <link>https://medium.com/@shannuvemula07?source=rss-cababb162495------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Ryi5L4g9-pwTjzpk</url>
            <title>Stories by Sharanya on Medium</title>
            <link>https://medium.com/@shannuvemula07?source=rss-cababb162495------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:27:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shannuvemula07/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[Judging the Machine: A Beginner’s Guide to Evaluation Metrics in Machine Learning]]></title>
            <link>https://medium.com/@shannuvemula07/judging-the-machine-a-beginners-guide-to-evaluation-metrics-in-machine-learning-2484285d4544?source=rss-cababb162495------2</link>
            <guid isPermaLink="false">https://medium.com/p/2484285d4544</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sharanya]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 11:15:40 GMT</pubDate>
            <atom:updated>2026-11-15T11:15:40.321Z</atom:updated>
            <content:encoded><![CDATA[<p>Regression and Classification Metrics Explained with Formulas, Examples and Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*kMVCtjFSpD3kA3WOHM00GA.png" /></figure><h3>1. Introduction to Model Evaluation</h3><p>Imagine two students who both claim to have studied for an exam. One scores 92 and the other scores 41. Nobody needs to ask who prepared better, because the marks tell the story. A Machine Learning model also needs its “marks”, and <strong>evaluation metrics</strong> are exactly that: numbers that tell us how good (or bad) a model’s predictions are.</p><h3>1.1 What are evaluation metrics?</h3><p>An evaluation metric is a mathematical formula that compares what the model <strong>predicted</strong> with what actually <strong>happened</strong> (the true label or value) and summarises the gap into one or a few numbers. A lower error or a higher score generally means a better model, depending on the metric.</p><h3>1.2 Why is model evaluation important?</h3><ul><li><strong>Trust:</strong> A model used in hospitals, banks or weather offices must be proven reliable before anyone depends on it.</li><li><strong>Comparison:</strong> We usually try many algorithms (Linear Regression, Random Forest, XGBoost, …). Metrics let us pick the best one fairly.</li><li><strong>Improvement:</strong> Metrics show <em>where</em> a model fails, for example missing too many sick patients, so we know what to fix.</li><li><strong>Detecting overfitting:</strong> A model may look perfect on data it has seen but fail on new data. Evaluation on unseen data exposes this.</li><li><strong>Business alignment:</strong> The metric connects model behaviour to real-world cost, such as a missed fraud case versus an annoyed customer.</li></ul><h3>1.3 Training vs Evaluation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xszYNg6VPCUWyKEqq9PVjA.png" /></figure><p>A key rule: <strong>never evaluate a model only on its training data.</strong> That is like giving students the exact exam questions beforehand and then praising their marks. We therefore split the data, commonly 80% for training and 20% for testing, or use cross-validation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v18QCqTwEOkS2fdyn8jkew.png" /><figcaption>Data is split so the model is evaluated on examples it has never seen.</figcaption></figure><h3>1.4 Why do we need different metrics?</h3><p>There is no single “best” metric because problems differ:</p><ol><li><strong>Type of output:</strong> Predicting a category (spam / not spam) needs classification metrics. Predicting a number (a house price) needs regression metrics.</li><li><strong>Cost of mistakes:</strong> Missing a cancer case is far worse than a false alarm, while in spam filtering the reverse can be true.</li><li><strong>Class imbalance:</strong> When 99% of cases are “normal”, a lazy model that always says “normal” gets 99% accuracy but is useless.</li><li><strong>Outliers and scale:</strong> Some regression metrics punish big errors heavily, others treat all errors equally.</li></ol><p>Choosing the metric is therefore a <em>design decision</em>, not an afterthought.</p><h3>2. Evaluation Metrics for Classification</h3><p>Classification models predict a <strong>class label</strong>: spam or not spam, disease or healthy, fraud or genuine. We will use one running example throughout this section.</p><blockquote><strong><em>Running example (spam filter):</em></strong><em> We test a spam classifier on 100 emails. 50 are truly spam (positive class) and 50 are genuine (negative class). The model’s results are shown in the confusion matrix below.</em></blockquote><h3>2.1 Confusion Matrix</h3><p><strong>Definition:</strong> A confusion matrix is a table that counts how many predictions fell into each combination of <em>actual</em> and <em>predicted</em> class. Almost every other classification metric is calculated from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGBjPp8nk7F-DjtsQZOyDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*y-eqMUaVXoj0mmR7GdL1YA.png" /><figcaption>The spam-filter confusion matrix as a heatmap (darker blue = more emails).</figcaption></figure><p>The four cells mean:</p><ul><li><strong>TP (True Positive):</strong> spam correctly caught as spam.</li><li><strong>TN (True Negative):</strong> genuine email correctly left in the inbox.</li><li><strong>FP (False Positive, Type I error):</strong> genuine email wrongly sent to spam (a “false alarm”).</li><li><strong>FN (False Negative, Type II error):</strong> spam that slipped through to the inbox (a “miss”).</li></ul><p><strong>Real-world use:</strong> Doctors, banks and engineers read this matrix first because it shows <em>what kind</em> of mistakes the model makes, not just how many.</p><p><strong>Python:</strong></p><pre>from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay<br>import matplotlib.pyplot as plt<br><br>y_true = [1]*50 + [0]*50                      # 1 = spam, 0 = not spam<br>y_pred = [1]*40 + [0]*10 + [1]*5 + [0]*45     # matches our table<br>cm = confusion_matrix(y_true, y_pred)<br>print(cm)                                     # [[45  5]<br>                                              #  [10 40]]<br>ConfusionMatrixDisplay(cm, display_labels=[&quot;Not Spam&quot;, &quot;Spam&quot;]).plot(cmap=&quot;Blues&quot;)<br>plt.title(&quot;Confusion Matrix - Spam Filter&quot;)<br>plt.show()</pre><p>Note that scikit-learn orders rows and columns by label value (0 first, then 1), so the printed matrix looks “flipped” compared with the table above. The numbers are the same.</p><h3>2.2 Accuracy</h3><p><strong>Definition:</strong> The fraction of all predictions that were correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*FfKtDzK8RQ_e0UyqqG4HCA.png" /></figure><p><strong>Example:</strong> (40 + 45) / 100 = <strong>0.85 (85%)</strong>.</p><p><strong>Advantages:</strong> Simple, intuitive, easy to explain to non-technical people.</p><p><strong>Limitations:</strong> It is misleading on <strong>imbalanced data</strong>. Suppose a bank has 1,000 transactions and only 10 are fraud. A model that labels <em>everything</em> as genuine is right 990 times, giving <strong>99% accuracy</strong>, yet it catches <strong>zero</strong> fraud. Accuracy also treats all errors as equally costly, which is rarely true.</p><p><strong>Use when:</strong> Classes are roughly balanced and all errors cost about the same.</p><h3>2.3 Precision</h3><p><strong>Definition:</strong> Of everything the model <em>labelled positive</em>, how much was truly positive? It answers: <em>“When the model raises an alarm, how often is it right?”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*N9tbTUqPfJcIDEk6MZOfwA.png" /></figure><p><strong>Example:</strong> 40 / (40 + 5) = 40/45 = <strong>0.889</strong>. When the filter says “spam”, it is right about 89% of the time.</p><p><strong>Real-world use:</strong> Spam filtering, where wrongly moving an important email (such as a job offer) to the spam folder is costly. Also recommendation systems and legal document review.</p><p><strong>Limitation:</strong> Precision ignores the positives the model failed to find. A model that flags only one email, correctly, has 100% precision but is practically useless.</p><h3>2.4 Recall (Sensitivity / True Positive Rate)</h3><p><strong>Definition:</strong> Of all the <em>actual positives</em>, how many did the model find? It answers: <em>“How many of the real cases did we catch?”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*_UiZr-bWSIDgDSzYCFf5yQ.png" /></figure><p><strong>Example:</strong> 40 / (40 + 10) = <strong>0.80</strong>. The filter catches 80% of all spam.</p><p><strong>Real-world use:</strong> Medical screening (missing a sick patient is dangerous), fraud detection and security threat detection, where missed positives are expensive.</p><p><strong>Limitation:</strong> A model that labels <em>everything</em> positive gets 100% recall but terrible precision.</p><h3>2.5 Specificity (True Negative Rate)</h3><p><strong>Definition:</strong> Of all the <em>actual negatives</em>, how many did the model correctly identify as negative? It is the “recall of the negative class”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*Vl9jaqOG7QpQdVJGELVW0w.png" /></figure><p><strong>Example:</strong> 45 / (45 + 5) = <strong>0.90</strong>. The filter leaves 90% of genuine emails alone.</p><p><strong>Real-world use:</strong> Medical tests, where high specificity means few healthy people are wrongly told they are sick. Specificity is also linked to the False Positive Rate: <strong>FPR = 1 − Specificity = 0.10</strong>.</p><h3>2.6 F1-Score</h3><p><strong>Definition:</strong> The <strong>harmonic mean</strong> of precision and recall. It gives a single number that is high only when <em>both</em> are reasonably high.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*1DpQkeyIviySOk7SeDKJqA.png" /></figure><p><strong>Example:</strong> F1 = 2 × (0.889 × 0.80) / (0.889 + 0.80) = 1.4222 / 1.6889 = <strong>0.842</strong>.</p><p>Why a harmonic mean and not a simple average? If precision = 1.0 and recall = 0.01, the simple average is a flattering 0.505, but the F1 is only about 0.02. The harmonic mean punishes lopsided models.</p><p><strong>Advantages:</strong> Works well on imbalanced data, balances false alarms and misses.</p><p><strong>Limitations:</strong> It gives equal weight to precision and recall (use the <strong>F-beta score</strong> to favour one), and it ignores true negatives.</p><p><strong>Python (all metrics together):</strong></p><pre>from sklearn.metrics import (accuracy_score, precision_score,<br>                             recall_score, f1_score, classification_report)<br><br>print(&quot;Accuracy :&quot;, accuracy_score(y_true, y_pred))    # 0.85<br>print(&quot;Precision:&quot;, precision_score(y_true, y_pred))   # 0.8889<br>print(&quot;Recall   :&quot;, recall_score(y_true, y_pred))      # 0.80<br>print(&quot;F1-score :&quot;, f1_score(y_true, y_pred))          # 0.8421<br><br># Specificity = recall of the negative class<br>print(&quot;Specificity:&quot;, recall_score(y_true, y_pred, pos_label=0))  # 0.90<br><br>print(classification_report(y_true, y_pred, target_names=[&quot;Not Spam&quot;, &quot;Spam&quot;]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*Gtwbe8p6lCK5oCdRtMqw1A.png" /><figcaption>Accuracy, precision, recall, specificity and F1 for the same model, side by side.</figcaption></figure><h3>2.7 The Precision–Recall Trade-off</h3><p>Most classifiers output a <strong>probability</strong>, and we pick a <strong>threshold</strong> (commonly 0.5) to convert it to a label.</p><ul><li><strong>Lower the threshold</strong> (e.g., 0.3): more items are flagged positive, so recall goes up but precision goes down.</li><li><strong>Raise the threshold</strong> (e.g., 0.8): the model flags only when very sure, so precision goes up but recall goes down.</li></ul><p>You cannot usually maximise both at once, so the right balance depends on the cost of each error type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*gYyIFhVEUMO36GGBktKepg.png" /><figcaption>Raising the threshold lifts precision and lowers recall (shape is illustrative).</figcaption></figure><h3>2.8 ROC Curve and AUC Score</h3><p><strong>ROC (Receiver Operating Characteristic) curve:</strong> A graph that shows how a classifier performs across <strong>all possible thresholds</strong>. It plots:</p><ul><li><strong>Y-axis:</strong> True Positive Rate (TPR = Recall)</li><li><strong>X-axis:</strong> False Positive Rate (FPR = 1 − Specificity)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*w0SAKOwbxP12WGuiRy-BVw.png" /></figure><p><strong>Illustrative numbers for our spam filter</strong> at different thresholds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*wtY_yn2_kv5cf3bVSbYjAw.png" /></figure><p>Each row is one point on the curve. Joining the points gives the ROC curve, which bends toward the <strong>top-left corner</strong> for a good model. The diagonal line from (0,0) to (1,1) represents random guessing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*ed2h-IGWOOXTqH45b3ohow.png" /><figcaption>ROC curve drawn from the threshold table. The dashed line is random guessing.</figcaption></figure><p><strong>AUC (Area Under the Curve):</strong> The area under the ROC curve, a single number between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*FVvh_SwGGcOBqmH2zeBKpw.png" /></figure><p><strong>Intuitive meaning:</strong> AUC is the probability that the model ranks a randomly chosen positive example higher than a randomly chosen negative one. An AUC of 0.90 means that in 90% of such pairs, the positive gets the higher score.</p><p><strong>Advantages:</strong> Independent of any single threshold, good for comparing models, and insensitive to the choice of 0.5 as cutoff.</p><p><strong>Limitations:</strong> On highly imbalanced data, ROC-AUC can look optimistic because the huge number of true negatives keeps FPR small. In such cases, the <strong>Precision–Recall curve</strong> is often more informative.</p><p><strong>Python:</strong></p><pre>import matplotlib.pyplot as plt<br>from sklearn.datasets import make_classification<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import roc_curve, roc_auc_score<br><br>X, y = make_classification(n_samples=1000, n_features=10, random_state=42)<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, stratify=y, random_state=42)<br><br>model = LogisticRegression(max_iter=1000).fit(X_train, y_train)<br>probs = model.predict_proba(X_test)[:, 1]          # probability of class 1<br><br>fpr, tpr, thresholds = roc_curve(y_test, probs)<br>auc = roc_auc_score(y_test, probs)<br><br>plt.plot(fpr, tpr, label=f&quot;Model (AUC = {auc:.2f})&quot;)<br>plt.plot([0, 1], [0, 1], &quot;k--&quot;, label=&quot;Random guess&quot;)<br>plt.xlabel(&quot;False Positive Rate&quot;)<br>plt.ylabel(&quot;True Positive Rate (Recall)&quot;)<br>plt.title(&quot;ROC Curve&quot;)<br>plt.legend()<br>plt.grid(alpha=0.3)<br>plt.show()</pre><h3>2.9 Classification Metrics at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*mwzks5fDzytgydPZ84gjLg.png" /></figure><h3>3. Evaluation Metrics for Regression</h3><p>Regression models predict a <strong>continuous number</strong>: a price, a temperature, a sales figure. Here we measure <em>how far</em> the predictions are from the truth. Let:</p><ul><li><em>yᵢ</em> = actual value, <em>ŷᵢ</em> = predicted value, <em>n</em> = number of samples, <em>ȳ</em> = mean of actual values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*gC3z-VIZlE6Im8ZTyL1WcQ.png" /></figure><h3>3.1 Mean Absolute Error (MAE)</h3><p><strong>Definition:</strong> The average of the absolute differences between actual and predicted values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*I9nlS3eKfzpNfMlfEDIjVQ.png" /></figure><p><strong>Example:</strong> (0.5 + 0.5 + 2 + 1) / 4 = 4 / 4 = <strong>1.0</strong>. On average the predictions are off by 1 unit.</p><p><strong>Advantages:</strong> Easy to interpret, in the <strong>same unit</strong> as the target (if predicting price in ₹, MAE is in ₹), and robust to outliers because large errors are not squared.</p><p><strong>Limitations:</strong> Treats all errors equally, so it will not strongly penalise a few huge mistakes. It is also not smooth at zero, which makes it slightly less convenient as an optimisation target.</p><p><strong>Real-world use:</strong> Sales forecasting and delivery-time estimation, where “typical error” matters to business users.</p><h3>3.2 Mean Squared Error (MSE)</h3><p><strong>Definition:</strong> The average of the <em>squared</em> errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*4zhTrzRUf6TMmRYtlk_-nw.png" /></figure><p><strong>Example:</strong> (0.25 + 0.25 + 4 + 1) / 4 = 5.5 / 4 = <strong>1.375</strong>.</p><p><strong>Advantages:</strong> Large errors are penalised heavily, which is good when big mistakes are unacceptable. It is smooth and differentiable, so it is the standard training loss for linear regression and neural-network regressors.</p><p><strong>Limitations:</strong> The unit is squared (₹² or °C²), which is hard to interpret, and it is very sensitive to outliers. One bad prediction can dominate the score.</p><h3>3.3 Root Mean Squared Error (RMSE)</h3><p><strong>Definition:</strong> The square root of MSE, which brings the error back to the original unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*1MSnxXnOeA8nBLqgQB-kGQ.png" /></figure><p><strong>Example:</strong> √1.375 ≈ <strong>1.173</strong>.</p><p><strong>MAE vs RMSE, a quick illustration:</strong> Consider two models, each with four predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*AqjZ_chnNFIQu2bE6FB8cg.png" /></figure><p>Both have the same MAE, but RMSE reveals that Model B makes one large error. RMSE is <em>always greater than or equal to</em> MAE, and the bigger the gap, the more uneven the errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*uuqT6s7PxqzE1rx5Rgi7Lg.png" /><figcaption>Same MAE, different RMSE: RMSE exposes the single large error in Model B.</figcaption></figure><p><strong>Real-world use:</strong> House price prediction and weather forecasting, where large misses are especially harmful.</p><h3>3.4 R² Score (Coefficient of Determination)</h3><p><strong>Definition:</strong> The proportion of the variation in the target that the model explains. It compares the model against a naive baseline that always predicts the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*prB7CTHcQ2JfbzaYnouzAg.png" /></figure><p><strong>Example:</strong> The mean of actual values is ȳ = (3+5+2+7)/4 = 4.25.</p><ul><li>SS_res = 5.5 (sum of squared errors from above)</li><li>SS_tot = (3−4.25)² + (5−4.25)² + (2−4.25)² + (7−4.25)² = 1.5625 + 0.5625 + 5.0625 + 7.5625 = 14.75</li><li>R² = 1 − 5.5/14.75 = 1 − 0.373 = <strong>0.627</strong></li></ul><p>The model explains about 63% of the variation in the data.</p><p><strong>Interpretation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*vza5gKDvYOOSbaQ5vyD3Ww.png" /></figure><p><strong>Advantages:</strong> Scale-free, so you can compare across datasets, and it is easy to communicate as “percentage of variance explained”.</p><p><strong>Limitations:</strong> R² <strong>never decreases</strong> when you add more features (for a least-squares fit on the same data), even useless ones, so it can reward over-complicated models. A high R² also does not prove the model is correct or unbiased.</p><h3>3.5 Adjusted R² Score</h3><p><strong>Definition:</strong> A version of R² that <strong>penalises unnecessary features</strong>. It increases only if a new feature improves the model more than would be expected by chance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*hsK_GHYbIADYYnHTldIXBw.png" /></figure><p>where <em>n</em> is the number of samples and <em>p</em> is the number of features (predictors).</p><p><strong>Example:</strong> Suppose R² = 0.85 with n = 100 samples.</p><ul><li>With <strong>p = 5</strong> features: Adj. R² = 1 − 0.15 × (99/94) = 1 − 0.158 = <strong>0.842</strong></li><li>If we add 15 useless features (<strong>p = 20</strong>) and R² creeps up to only 0.852: Adj. R² = 1 − 0.148 × (99/79) = 1 − 0.185 = <strong>0.815</strong></li></ul><p>Plain R² went <em>up</em> (0.85 → 0.852), but Adjusted R² went <em>down</em> (0.842 → 0.815), correctly warning us that the extra features did not help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*1GjIJewhTLvcXeNQggOy_A.png" /><figcaption>R-squared keeps rising as features are added, while Adjusted R-squared peaks and then falls (illustrative curve).</figcaption></figure><p><strong>Limitation:</strong> It still measures fit on the data given, so it does not replace evaluation on a separate test set. It is mainly meaningful for linear models.</p><p><strong>Python (all regression metrics):</strong></p><pre>import numpy as np<br>from sklearn.metrics import (mean_absolute_error, mean_squared_error,<br>                             r2_score)<br><br>y_true = np.array([3, 5, 2, 7])<br>y_pred = np.array([2.5, 5.5, 4.0, 6.0])<br><br>mae  = mean_absolute_error(y_true, y_pred)       # 1.0<br>mse  = mean_squared_error(y_true, y_pred)        # 1.375<br>rmse = np.sqrt(mse)                              # 1.1726<br>r2   = r2_score(y_true, y_pred)                  # 0.6271<br><br># Adjusted R2 (scikit-learn has no built-in function)<br>def adjusted_r2(r2, n, p):<br>    return 1 - (1 - r2) * (n - 1) / (n - p - 1)<br><br>print(f&quot;MAE={mae:.3f}  MSE={mse:.3f}  RMSE={rmse:.3f}  R2={r2:.3f}&quot;)<br>print(&quot;Adjusted R2 (n=100, p=5, R2=0.85):&quot;, round(adjusted_r2(0.85, 100, 5), 3))</pre><p><strong>A useful graph:</strong> plot actual vs predicted values. Points close to the diagonal line mean good predictions.</p><pre>import matplotlib.pyplot as plt<br>plt.scatter(y_true, y_pred)<br>plt.plot([min(y_true), max(y_true)], [min(y_true), max(y_true)], &quot;r--&quot;)<br>plt.xlabel(&quot;Actual&quot;); plt.ylabel(&quot;Predicted&quot;)<br>plt.title(&quot;Actual vs Predicted&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*4Ynef3y6ET-OqzYtzmTg3A.png" /><figcaption>Actual vs predicted for the four-sample example. Red lines are the errors.</figcaption></figure><h3>3.6 Regression Metrics at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*CcuBGX4v0CGm2ERMfX6WTA.png" /></figure><h3>4. Comparison and Practical Understanding</h3><h3>4.1 Regression vs Classification metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*KDqrVqgISk6G_bAJ6W39mg.png" /></figure><p>One important warning: you cannot use accuracy for regression, because predicting exactly 250000.00 is practically impossible, and you should not use MAE for classification labels, because the “distance” between class 0 and class 1 has no real meaning.</p><h3>4.2 When should we use each metric?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*95IRPN1YuyADUcq2cafVFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*5USJi_kTJXbQM2QPj30ufQ.png" /><figcaption>A quick guide to picking a metric.</figcaption></figure><h3>4.3 Advantages and limitations summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*4kud7-jVpHWvRG2HOG12iw.png" /></figure><h3>4.4 Examples of choosing the right metric</h3><ol><li><strong>Cancer screening:</strong> Only 2% of patients have the disease. Accuracy would be 98% for a model that predicts “healthy” for everyone. We prioritise <strong>Recall</strong> (catch every real case) and monitor <strong>Specificity</strong> and <strong>Precision</strong> to limit unnecessary biopsies.</li><li><strong>Email spam filter:</strong> Losing a genuine email is painful, so we care about <strong>Precision</strong>, while keeping <strong>Recall</strong> reasonable so the inbox stays clean.</li><li><strong>Credit card fraud:</strong> Fraud may be 0.1% of transactions. Use <strong>Recall, Precision, F1 and the PR curve</strong>, never accuracy alone.</li><li><strong>Predicting delivery time in minutes:</strong> Customers understand “off by about 6 minutes”, so <strong>MAE</strong> is a natural reporting metric.</li><li><strong>Predicting house prices:</strong> A very wrong estimate harms a buyer or seller, so we use <strong>RMSE</strong> and <strong>R²</strong>, and check <strong>Adjusted R²</strong> when comparing models with different features.</li></ol><h3>5. Real-World Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*gALqNXDGM0M26Nnehr9umg.png" /></figure><h3>Mini case study: Medical diagnosis</h3><p>A test is run on 1,000 people, of whom 50 truly have a disease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*NRmQznS7-_OTmiG5hf_mcw.png" /></figure><ul><li>Accuracy = (45 + 855)/1000 = <strong>90%</strong></li><li>Recall = 45/50 = <strong>90%</strong></li><li>Specificity = 855/950 = <strong>90%</strong></li><li>Precision = 45/(45 + 95) = 45/140 = <strong>32%</strong></li></ul><p>Even though accuracy, recall and specificity all look great, only about <strong>1 in 3</strong> positive results is a true case, because the disease is rare. This is exactly why one metric alone can hide important truths, and why doctors follow a positive screening result with a confirmatory test.</p><h3>6. Conclusion</h3><p>Evaluation metrics are the report card of a Machine Learning model. Without them we cannot know whether a model is learning real patterns or just memorising , whether one algorithm beats another, or whether a system is safe to deploy.</p><p>The key lessons from this blog are:</p><ul><li><strong>Classification</strong> models are judged with the confusion matrix and the metrics derived from it: Accuracy, Precision, Recall, Specificity, F1-Score, and ROC-AUC.</li><li><strong>Regression</strong> models are judged by the size of their errors: MAE, MSE, RMSE, along with R² and Adjusted R² for overall fit.</li><li><strong>No single metric is perfect.</strong> Accuracy fails on imbalanced data, RMSE is sensitive to outliers, and R² can be inflated by extra features.</li><li><strong>The right metric depends on the problem</strong>, specifically on which mistakes are most costly in the real world.</li><li><strong>Always evaluate on unseen data</strong>, and look at several metrics together rather than trusting just one.</li></ul><p>Selecting the right evaluation metric is therefore as important as selecting the right algorithm. A model that scores well on the wrong metric is a model that quietly fails in the real world. As beginners, the best habit we can build is to ask, before training anything: <em>“What does a mistake cost, and which number will tell me honestly how often I make it?”</em></p><h3>References</h3><ol><li>Scikit-learn Documentation, <em>Metrics and scoring: quantifying the quality of predictions</em>. <a href="https://scikit-learn.org/stable/modules/model_evaluation.html">https://scikit-learn.org/stable/modules/model_evaluation.html</a></li><li>Scikit-learn Documentation, <em>Receiver Operating Characteristic (ROC) example</em>. <a href="https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html">https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html</a></li><li>Google for Developers, <em>Machine Learning Crash Course: Classification</em>. <a href="https://developers.google.com/machine-learning/crash-course/classification">https://developers.google.com/machine-learning/crash-course/classification</a></li><li>Fawcett, T. (2006). <em>An introduction to ROC analysis.</em> Pattern Recognition Letters, 27(8), 861–874.</li><li>Géron, A. <em>Hands-On Machine Learning with Scikit-Learn, Keras and TensorFlow</em> (O’Reilly), Chapter 3: Classification.</li><li>James, G., Witten, D., Hastie, T., Tibshirani, R. <em>An Introduction to Statistical Learning.</em> <a href="https://www.statlearning.com/">https://www.statlearning.com/</a></li></ol><p><em>Note: Numerical examples in this blog are illustrative and were calculated by hand, then cross-checked with the Python snippets provided.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2484285d4544" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seeing Like a Computer: Image Processing with Python, NumPy & OpenCV]]></title>
            <link>https://medium.com/@shannuvemula07/seeing-like-a-computer-image-processing-with-python-numpy-opencv-8f3622bc6641?source=rss-cababb162495------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f3622bc6641</guid>
            <dc:creator><![CDATA[Sharanya]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 12:04:22 GMT</pubDate>
            <atom:updated>2026-11-03T12:04:22.394Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A beginner-friendly walkthrough of images, pixels, arrays, channels and your first OpenCV project</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y36BE0CdzTnwZFZteiIrtw.png" /></figure><p><strong>Reading time:</strong> ~10 minutes | <strong>Level:</strong> Beginner | <strong>Tools:</strong> Python, NumPy, OpenCV</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpSk0VthWvoMFfZvQq3EtQ.png" /></figure><p><em>Left: the picture we see. Right: the same region as a grid of numbers (0 = black, 255 = white).</em></p><h3>Introduction: What does a computer actually see?</h3><p>When you look at a photo of a sunset, you see colors, shapes and a mood. A computer sees none of that. It sees <strong>numbers</strong>. Thousands, sometimes millions, of them.</p><p>In our class, we explored how those numbers are organized and how we can use Python to read, change and understand them. In this article I’ll walk you through everything I learned: images, pixels, arrays, channels, the OpenCV library, its basic functions, and finally how to put it all together into a small project.</p><p>By the end, you’ll be able to load an image, inspect it, edit it and save it using only a few lines of code. Let’s get started.</p><h3>1. Images: How a computer stores a picture</h3><p>A <strong>digital image</strong> is a grid of tiny squares, each holding a number that describes its color or brightness. Think of a mosaic made of thousands of tiles: from far away you see a picture, but up close it is just small blocks of color.</p><p>Two big ideas to remember:</p><ul><li>An image is <strong>not</strong> stored as a drawing. It is stored as <strong>data</strong> arranged in rows and columns.</li><li>Once an image is data, we can use math and code to modify it, which is the whole idea behind image processing.</li></ul><p>Common formats you will meet are JPG, PNG and BMP. They differ in how they compress the data, but once loaded into Python they all become the same thing: a grid of numbers.</p><p><strong>Quick question for you:</strong> if an image is just numbers, what do you think happens when we add 50 to every number? Hold that thought, we will test it later.</p><h3>2. Pixels: The building blocks</h3><p>A <strong>pixel</strong> (short for <em>picture element</em>) is the smallest unit of an image. Each pixel stores a value that tells the screen how bright or what color to display.</p><h3>Pixel values</h3><p>In most images, each pixel value is an integer between <strong>0 and 255</strong> (8 bits):</p><ul><li>0 means no intensity (black)</li><li>255 means full intensity (white, or the brightest form of a color)</li></ul><p>Why 255? Because 8 bits can represent 2⁸ = 256 different values (0 to 255).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mwgs1eqs79qRQfg_IgkTtQ.png" /></figure><p><em>The 0 to 255 intensity scale: every pixel value sits somewhere on this bar.</em></p><h3>Image dimensions</h3><p>The size of an image is written as <strong>height x width</strong> (rows x columns). An image of 480 x 640 has 480 rows and 640 columns, so it contains 480 x 640 = <strong>307,200 pixels</strong>.</p><h3>Color channels</h3><p>A color pixel is not just one number. It holds several, one for each color channel. In a standard color image, every pixel has three values: how much Red, Green and Blue it contains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tR_LFjvGh20nlXYcGE8hGA.png" /></figure><p><em>Zooming into a 4 x 4 block: every pixel is stored as three numbers, one per color channel.</em></p><h3>3. Arrays: Images as NumPy arrays</h3><p>Since an image is a grid of numbers, the natural way to hold it in Python is an <strong>array</strong>. This is where <strong>NumPy</strong> comes in.</p><p>NumPy is Python’s core library for numerical computing. It gives us the ndarray, a fast, memory-efficient, multi-dimensional array. OpenCV loads every image as a NumPy array, so everything NumPy can do, we can do to our images.</p><ul><li>A <strong>grayscale</strong> image is a <strong>2D array</strong>: (height, width)</li><li>A <strong>color</strong> image is a <strong>3D array</strong>: (height, width, channels)</li></ul><pre>import numpy as np<br>A tiny 3x3 grayscale &#39;image&#39;<br>img = np.array([[  0, 128, 255],<br>                [ 64, 192,  32],<br>                [255,   0, 100]], dtype=np.uint8)<br>print(img.shape)   # (3, 3)<br>print(img.dtype)   # uint8<br>print(img[0, 2])   # 255 -&gt; row 0, column 2</pre><p>Note the data type uint8: it means <em>unsigned 8-bit integer</em>, which holds exactly the range 0 to 255. This is the standard type for images.</p><p><strong>Why NumPy matters for images:</strong></p><ol><li><strong>Speed:</strong> operations run on the whole array at once, with no slow Python loops.</li><li><strong>Slicing:</strong> cropping an image is as easy as slicing an array.</li><li><strong>Math:</strong> brightness changes, masks and filters are simple array operations.</li></ol><h3>4. Channels: RGB, Grayscale and beyond</h3><p>A <strong>channel</strong> is one layer of color information. Stack the layers together and you get the full-color picture.</p><h3>RGB</h3><p>In the RGB model, three channels (Red, Green, Blue) combine to produce any color:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WTH8F0OD466KtRLju6Mqg.png" /></figure><h3>Grayscale</h3><p>A grayscale image has only <strong>one channel</strong>. Each pixel is a single number showing brightness, from black (0) to white (255). It is smaller, faster to process, and often enough when color doesn’t matter, for example in edge detection.</p><h3>The OpenCV twist: BGR, not RGB</h3><p>Here is a detail that surprises almost every beginner. <strong>OpenCV stores color channels in the order Blue, Green, Red (BGR)</strong>, not RGB. Most other libraries, like Matplotlib, expect RGB. If you display an OpenCV image with Matplotlib without converting, the colors will look strange. We will see how to fix this shortly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HseMkk_hX1T8jd-Q9IGxLQ.png" /></figure><p><em>Left: an OpenCV (BGR) image shown directly with Matplotlib. Right: the same image after converting to RGB.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xioQFPyKtC9Az30UXrlPw.png" /></figure><p><em>The same image split into its Red, Green and Blue channels, plus its single-channel grayscale version.</em></p><h3>5. OpenCV: Giving computers the power to see</h3><p><strong>OpenCV</strong> (Open Source Computer Vision Library) is one of the most popular libraries for image processing and computer vision. It was originally written in C++, and has Python bindings that make it easy to use.</p><p><strong>Why is it so important?</strong></p><ul><li>It has <strong>2,500+ optimized algorithms</strong> for image and video tasks.</li><li>It powers real-world applications: face detection, self-driving car perception, medical image analysis, document scanners, and AR filters.</li><li>It’s <strong>free and open source</strong>, with a huge community.</li><li>It works hand in hand with NumPy.</li></ul><p>Install it with:</p><pre>pip install opencv-python numpy matplotlib</pre><p>And import it:</p><pre>import cv2<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><h3>6. Basic OpenCV functions (with syntax and examples)</h3><p>This is the toolkit we used in class. For each function I’ll show the syntax and a small example. Use any image of your own, named photo.jpg.</p><h3>6.1 cv2.imread(): load an image</h3><p><strong>Syntax:</strong> cv2.imread(path, flag)</p><pre>img = cv2.imread(&#39;photo.jpg&#39;)                        # color (default)<br>gray = cv2.imread(&#39;photo.jpg&#39;, cv2.IMREAD_GRAYSCALE) # grayscale</pre><p>Flags: cv2.IMREAD_COLOR (1), cv2.IMREAD_GRAYSCALE (0), cv2.IMREAD_UNCHANGED (-1). If the path is wrong, imread does <strong>not</strong> raise an error. It quietly returns None, so always check:</p><pre>if img is None:<br>    print(&#39;Image not found. Check the file path!&#39;)</pre><h3>6.2 cv2.imshow(), cv2.waitKey() and cv2.destroyAllWindows(): display an image</h3><p><strong>Syntax:</strong> cv2.imshow(window_name, image)</p><pre>cv2.imshow(&#39;My Image&#39;, img)<br>cv2.waitKey(0)            # wait until any key is pressed<br>cv2.destroyAllWindows()   # close all windows</pre><p>waitKey(0) pauses the program. Without it, the window would flash and vanish instantly.</p><blockquote><strong><em>Using Google Colab or Jupyter?</em></strong><em> </em><em>cv2.imshow doesn&#39;t work there. Use </em><em>from google.colab.patches import cv2_imshow and call </em><em>cv2_imshow(img), or use Matplotlib (shown in 6.4).</em></blockquote><h3>6.3 img.shape, img.size and img.dtype: inspect an image</h3><pre>print(img.shape)   # e.g. (480, 640, 3) -&gt; height, width, channels<br>print(img.size)    # total number of values (480*640*3)<br>print(img.dtype)   # uint8</pre><p>The shape attribute is the first thing I check on any new image. Grayscale images return only two values, (height, width).</p><h3>6.4 Matplotlib display with BGR to RGB conversion</h3><pre>rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>plt.imshow(rgb)<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><h3>6.5 cv2.cvtColor(): convert color spaces</h3><p><strong>Syntax:</strong> cv2.cvtColor(image, conversion_code)</p><pre>gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)<br>hsv  = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)</pre><p>Grayscale conversion reduces three channels to one. HSV (Hue, Saturation, Value) is helpful when you want to detect colors, since hue separates color from brightness.</p><h3>6.6 Accessing and modifying pixels</h3><p>Because the image is a NumPy array, we use indexing:</p><pre>pixel = img[100, 50]        # [B, G, R] values at row 100, column 50<br>blue  = img[100, 50, 0]     # just the blue value</pre><pre>img[100, 50] = [0, 0, 255]  # make that pixel pure red (BGR order!)</pre><h3>6.7 Cropping with slicing (ROI)</h3><p>A <strong>Region of Interest (ROI)</strong> is simply a slice of the array: img[y1:y2, x1:x2]</p><pre>roi = img[50:250, 100:400]   # rows 50-250, columns 100-400<br>cv2.imshow(&#39;Cropped&#39;, roi)<br>cv2.waitKey(0)</pre><p>Remember the order: <strong>rows (y) first, then columns (x)</strong>.</p><h3>6.8 cv2.resize(): change the size</h3><p><strong>Syntax:</strong> cv2.resize(image, (width, height))</p><pre>resized = cv2.resize(img, (300, 200))             # exact size<br>half    = cv2.resize(img, None, fx=0.5, fy=0.5)   # scale by factor</pre><p>Watch out: resize takes <strong>(width, height)</strong>, while shape gives <strong>(height, width)</strong>. This mismatch trips up lots of beginners.</p><h3>6.9 cv2.flip() and cv2.rotate(): change orientation</h3><pre>flipped_h = cv2.flip(img, 1)    # 1 = horizontal, 0 = vertical, -1 = both<br>rotated   = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)</pre><h3>6.10 cv2.GaussianBlur(): smooth an image</h3><p><strong>Syntax:</strong> cv2.GaussianBlur(image, (kernel_w, kernel_h), sigmaX)</p><pre>blur = cv2.GaussianBlur(img, (7, 7), 0)</pre><p>The kernel size must be odd. A larger kernel means a stronger blur. Blurring reduces noise, which is why it is often used before edge detection.</p><h3>6.11 cv2.Canny(): detect edges</h3><p><strong>Syntax:</strong> cv2.Canny(image, threshold1, threshold2)</p><pre>edges = cv2.Canny(gray, 100, 200)</pre><p>Pixels with a strong change in brightness are marked white; everything else is black. Try different thresholds and watch how the result changes.</p><h3>6.12 Drawing: rectangle, circle, line, putText</h3><pre>cv2.rectangle(img, (50, 50), (250, 200), (0, 255, 0), 3)   # green box<br>cv2.circle(img, (150, 125), 40, (255, 0, 0), -1)            # filled blue circle<br>cv2.line(img, (0, 0), (300, 300), (0, 0, 255), 2)           # red line<br>cv2.putText(img, &#39;Hello CV!&#39;, (60, 40),<br>            cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)</pre><p>Colors are in <strong>BGR</strong>. A thickness of -1 fills the shape.</p><h3>6.13 cv2.imwrite(): save an image</h3><p><strong>Syntax:</strong> cv2.imwrite(filename, image)</p><pre>cv2.imwrite(&#39;output.jpg&#39;, img)</pre><h3>Quick cheat sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozKkB2CvioDIbLfCV7obzQ.png" /></figure><h3>Remember the question from earlier?</h3><p>What happens if we add 50 to every pixel? Let’s try it:</p><pre>bright = cv2.add(img, np.full(img.shape, 50, dtype=np.uint8))</pre><p>The picture gets <strong>brighter</strong>. We use cv2.add rather than img + 50 because uint8 values wrap around in NumPy (250 + 10 becomes 4), while OpenCV <em>saturates</em> at 255, which is what we want.</p><h3>7. Building a basic image processing project, step by step</h3><p>Now let’s combine everything into a mini project: <strong>an Image Analyzer &amp; Enhancer</strong> that loads a photo, inspects it, creates several versions, annotates it and saves the results.</p><h3>Step 1: Define the goal</h3><p>Take any input image and automatically produce: a grayscale version, a blurred version, an edge map, and an annotated copy.</p><h3>Step 2: Set up the environment</h3><pre>pip install opencv-python numpy matplotlib</pre><p>Create a folder with your image (input.jpg) and an output/ folder.</p><h3>Step 3: Load and validate the image</h3><pre>import cv2<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import os<br><br>img = cv2.imread(&#39;input.jpg&#39;)<br>if img is None:<br>    raise FileNotFoundError(&#39;Could not load input.jpg&#39;)<br>h, w, c = img.shape<br>print(f&#39;Height: {h}, Width: {w}, Channels: {c}&#39;)</pre><h3>Step 4: Preprocess</h3><p>Resize large images so the processing stays fast, and convert to grayscale.</p><pre>img = cv2.resize(img, (640, 480))<br>gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)</pre><h3>Step 5: Apply the processing</h3><pre>blur  = cv2.GaussianBlur(gray, (5, 5), 0)<br>edges = cv2.Canny(blur, 80, 180)<br>flipped = cv2.flip(img, 1)</pre><h3>Step 6: Annotate</h3><pre>annotated = img.copy()   # always work on a copy to keep the original safe<br>cv2.rectangle(annotated, (20, 20), (620, 460), (0, 255, 0), 3)<br>cv2.putText(annotated, &#39;Processed with OpenCV&#39;, (30, 55),<br>            cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 255), 2)</pre><h3>Step 7: Visualize the results together</h3><pre>titles = [&#39;Original&#39;, &#39;Grayscale&#39;, &#39;Blurred&#39;, &#39;Edges&#39;, &#39;Flipped&#39;, &#39;Annotated&#39;]<br>images = [cv2.cvtColor(img, cv2.COLOR_BGR2RGB), gray, blur, edges,<br>          cv2.cvtColor(flipped, cv2.COLOR_BGR2RGB),<br>          cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB)]<br><br>plt.figure(figsize=(12, 7))<br>for i in range(6):<br>    plt.subplot(2, 3, i + 1)<br>    plt.imshow(images[i], cmap=&#39;gray&#39; if images[i].ndim == 2 else None)<br>    plt.title(titles[i])<br>    plt.axis(&#39;off&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zNF0yybAAspgyIfVl32Ylw.png" /></figure><p><em>Final output of the project: original, grayscale, blurred, edges, flipped and annotated versions.</em></p><h3>Step 8: Save the outputs</h3><pre>os.makedirs(&#39;output&#39;, exist_ok=True)<br>cv2.imwrite(&#39;output/gray.jpg&#39;, gray)<br>cv2.imwrite(&#39;output/edges.jpg&#39;, edges)<br>cv2.imwrite(&#39;output/annotated.jpg&#39;, annotated)<br>print(&#39;All results saved!&#39;)</pre><h3>Step 9: Test, tweak and extend</h3><p>Change the blur kernel, try different Canny thresholds, test on different images. Then challenge yourself:</p><ul><li>Add a brightness slider using cv2.createTrackbar.</li><li>Detect faces using OpenCV’s Haar cascades and draw boxes around them.</li><li>Process a webcam feed with cv2.VideoCapture(0).</li></ul><h3>Common mistakes to avoid</h3><ol><li><strong>Forgetting </strong><strong>cv2.waitKey():</strong> the window closes instantly.</li><li><strong>Wrong file path:</strong> imread returns None silently.</li><li><strong>BGR vs RGB:</strong> convert before using Matplotlib.</li><li><strong>(width, height) vs (height, width):</strong> resize and shape use opposite orders.</li><li><strong>Editing the original:</strong> use .copy() when you need to keep it.</li></ol><h3>Key takeaways</h3><ul><li>An image is a <strong>grid of numbers</strong>; each cell is a <strong>pixel</strong>, usually 0 to 255.</li><li>Grayscale images are <strong>2D arrays</strong>; color images are <strong>3D arrays</strong> with 3 channels.</li><li><strong>NumPy</strong> makes images fast and easy to manipulate.</li><li>OpenCV reads color in <strong>BGR</strong> order.</li><li>A handful of functions (imread, imshow, cvtColor, resize, GaussianBlur, Canny, imwrite) can already take you a long way.</li></ul><h3>Conclusion</h3><p>Learning image processing changed the way I look at pictures. Every photo on my phone is really a big table of numbers that I can read, edit and analyze with a few lines of Python. This is only the beginning: from here you can move into face detection, object tracking and even deep learning-based vision.</p><p><strong>Your turn:</strong> pick any image, run the project above, and see what your computer sees. If you build something fun with it, I’d love to hear about it in the comments.</p><p>Thanks for reading! If you found this helpful, give it a clap and follow for more posts from my learning journey.</p><p><em>#Python #OpenCV #ImageProcessing #ComputerVision #NumPy #LearningInPublic</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f3622bc6641" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Warehouse, Lake, or Lakehouse? How Databricks Turns Raw E-Commerce Data into Business Insights]]></title>
            <link>https://medium.com/@shannuvemula07/warehouse-lake-or-lakehouse-how-databricks-turns-raw-e-commerce-data-into-business-insights-f516d03f5833?source=rss-cababb162495------2</link>
            <guid isPermaLink="false">https://medium.com/p/f516d03f5833</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Sharanya]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 11:02:25 GMT</pubDate>
            <atom:updated>2026-10-31T11:02:25.416Z</atom:updated>
            <content:encoded><![CDATA[<p>A beginner-friendly guide to data storage architectures, Unity Catalog, and the Bronze–Silver–Gold pattern</p><h3>The Problem: Data Everywhere, Insight Nowhere</h3><p>Imagine you’re the first data engineer at a fast-growing e-commerce company. Every day it produces customer registrations in a database, orders and payments as CSV exports, website clickstreams as JSON, reviews as free text, and delivery updates from logistics partners.</p><p>Leadership wants sales dashboards, customer behavior analysis, and eventually machine learning models for recommendations. You need to decide where all this data lives and how it becomes trustworthy. That decision leads to three architectures: the <strong>Data Warehouse</strong>, the <strong>Data Lake</strong>, and the <strong>Lakehouse</strong>. I’ll use this one company as the example throughout.</p><h3>Understanding Data Warehouses</h3><p>A <strong>Data Warehouse</strong> is a central system that stores cleaned, structured data, organized for reporting and analytics. Data is extracted from source systems, transformed to fit a predefined schema, and loaded into tables (<strong>schema-on-write</strong>). Only data that fits the model gets in.</p><p><strong>E-commerce example:</strong> The finance team wants monthly revenue, regional sales, and product performance. The warehouse holds standardized tables such as orders, customers, and products. “Revenue” means the same thing in every report, and BI tools like Power BI query it quickly.</p><p><strong>Advantages:</strong> consistent, trusted numbers; fast SQL; a strong fit for BI.<br><strong>Limitations:</strong> it’s less flexible with raw, semi-structured, or unstructured data (JSON logs, images, reviews), changing the schema takes effort, and storing everything can get expensive.</p><h3>Understanding Data Lakes</h3><p>A <strong>Data Lake</strong> stores data in its original format on low-cost storage: structured, semi-structured, and unstructured. You don’t need to define a schema up front. Instead you apply it when you read the data (<strong>schema-on-read</strong>).</p><p><strong>E-commerce example:</strong> Transactions, website logs, JSON events, and customer feedback all land in the lake untouched. Raw storage matters because you can reprocess it later for new questions, such as training a sentiment model on years of reviews.</p><p><strong>Advantages:</strong> flexibility, scale, low cost, and support for data science.<br><strong>Limitations:</strong> without discipline, a lake can become a “data swamp.” Plain files have no built-in transactions, quality checks, or consistent access control, so two jobs writing at once can leave corrupted or half-written data. <strong>Data quality, security, and governance</strong> have to be added deliberately.</p><h3>Understanding Lakehouses</h3><p>A <strong>Lakehouse</strong> combines the low-cost, flexible storage of a lake with the reliability and management features of a warehouse. It addresses the old pattern of keeping a lake for data science <em>and</em> a separate warehouse for BI, with copies and pipelines between them.</p><ul><li><strong>Reliable tables on lake storage:</strong> tables get <strong>ACID transactions</strong> (writes either fully succeed or don’t happen), so readers always see a consistent state.</li><li><strong>Metadata and governance:</strong> a metadata layer tracks schemas, versions, and permissions.</li><li><strong>One platform, many workloads:</strong> BI, SQL analytics, streaming, and machine learning work on the same data.</li></ul><p><strong>Delta Lake</strong> is an open-source storage layer that provides these capabilities (ACID transactions, schema enforcement, time travel) for data stored in supported cloud storage. Databricks tables use Delta Lake by default.</p><p>A Lakehouse is an <strong>architectural approach</strong>, not a product name. You could implement it with different technologies; what makes it a Lakehouse is the combination of open, low-cost storage, reliable table management, and unified governance.</p><p><strong>Limitations:</strong> it needs thoughtful design (layers, governance, and cost control), and teams must learn new concepts.</p><h3>Warehouse vs. Lake vs. Lakehouse</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5BymgU_IFtLaNvLSuQ_mg.png" /><figcaption>Figure 1: The three architectures side by side</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORDZpKm30C-Q02Ry35KhEA.png" /><figcaption>Table 1: Trade-offs, using the same e-commerce example</figcaption></figure><p>No architecture is universally best. A small company with only structured sales data and BI needs may be well served by a warehouse. A research-heavy team with massive unstructured data might start with a lake. When you need both reliable BI and ML on diverse data, a Lakehouse fits.</p><p><strong>My recommendation:</strong> For our e-commerce company, I’d choose a <strong>Lakehouse on Databricks</strong>. The data is mixed (CSV, JSON, text, tables), the business needs both dashboards and ML, and a single governed copy of the data avoids duplicate pipelines.</p><h3>How Databricks Uses the Lakehouse Architecture</h3><p>Databricks implements the Lakehouse approach with <strong>Delta Lake</strong> for reliable tables, <strong>Unity Catalog</strong> for governance, and a platform where data engineers (notebooks, jobs), analysts (Databricks SQL, BI tools), and ML practitioners work on the same data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ehE9XBFvaNF9IkuUA8WGQ.png" /><figcaption>Figure 2: Databricks Lakehouse architecture for our e-commerce data</figcaption></figure><h3>Unity Catalog: Catalog → Schema → Table</h3><p>Unity Catalog organizes and governs data in a three-level hierarchy:</p><ul><li><strong>Catalog:</strong> the top-level container, often per business domain or environment.</li><li><strong>Schema:</strong> a grouping inside a catalog (like a database).</li><li><strong>Table:</strong> the structured dataset you query.</li></ul><p>Example: ecommerce.sales.gold_sales, where ecommerce is the catalog, sales is the schema, and gold_sales is the table.</p><pre>SELECT * FROM ecommerce.sales.gold_sales;</pre><p>Permissions are managed centrally. For example, analysts can be granted read access to the gold table without seeing raw data:</p><pre>GRANT SELECT ON TABLE ecommerce.sales.gold_sales TO `analysts`;</pre><h3>Volumes vs. Tables</h3><ul><li><strong>Unity Catalog Volume:</strong> organizes and accesses <em>files</em> (CSV, JSON, images, documents). Used for source files and file-based workflows. Accessed through file paths.</li><li><strong>Databricks Table:</strong> stores and queries <em>structured data</em> (customers, products, sales). Used for SQL analytics and transformations. Accessed with SQL or DataFrame APIs.</li></ul><p>So the raw sales.csv lands in a <strong>Volume</strong>, while cleaned data lives in <strong>tables</strong>.</p><p><strong>Managed vs. external tables (beginner view):</strong> For a <em>managed</em> table, Databricks manages the storage location and lifecycle, and dropping the table removes the underlying data. For an <em>external</em> table, you point to a storage location you control, and dropping the table doesn’t delete that data. Exact behavior depends on configuration.</p><h3>Where Is the Data Physically Stored?</h3><p>Not inside the workspace itself. The <strong>workspace</strong> is where you work with notebooks, SQL, and jobs. <strong>Unity Catalog</strong> is the governance and organization layer. <strong>Volumes</strong> give governed access to files, and <strong>tables</strong> give a structured interface for querying. The underlying data lives in the <strong>configured cloud storage location</strong>, and Databricks manages or accesses it depending on the resource type and configuration.</p><h3>Bronze, Silver, Gold: The Medallion Architecture</h3><p>Say sales.csv arrives with order IDs, categories, quantities, prices, and amounts.</p><p><strong>Source CSV → Bronze → Silver → Gold → Power BI / SQL Analytics / AI</strong></p><ul><li><strong>Bronze (</strong><strong>bronze_sales):</strong> raw ingested data with minimal changes, plus source metadata (file name, load time) for traceability and reprocessing.</li><li><strong>Silver (</strong><strong>silver_sales):</strong> cleaned and validated. Remove duplicates, handle missing values, standardize text (e.g., “electronics” vs “Electronics”), enforce data types, and filter invalid records such as negative quantities.</li><li><strong>Gold (</strong><strong>gold_sales):</strong> business-ready aggregates, such as sales by product, category, region, and month, feeding Power BI, SQL analytics, and ML features.</li></ul><pre>CREATE OR REPLACE TABLE ecommerce.sales.gold_sales AS<br>SELECT category,<br>       date_trunc(&#39;month&#39;, order_date) AS month,<br>       SUM(quantity * price) AS total_sales<br>FROM ecommerce.sales.silver_sales<br>GROUP BY category, date_trunc(&#39;month&#39;, order_date);</pre><p>Bronze, Silver, and Gold are <strong>logical layers</strong>, not necessarily separate physical systems. In Databricks, they’re typically Delta tables governed through Unity Catalog. The layers improve organization (everyone knows where to look), quality (data gets progressively more trustworthy), and usability (consumers use Gold and don’t re-clean data).</p><h3>Key Takeaways</h3><ol><li><strong>Warehouses, lakes, and Lakehouses solve different problems.</strong> Choose based on your data types and workloads, not hype.</li><li><strong>Databricks organizes data with Unity Catalog</strong> (Catalog → Schema → Table), keeping files in Volumes and structured data in tables, all under central governance.</li><li><strong>Medallion layers turn raw data into trusted insights.</strong> Bronze preserves, Silver cleans, and Gold serves the business.</li></ol><h3>References</h3><ul><li><a href="https://www.databricks.com/glossary/data-lakehouse">Databricks: What is a Data Lakehouse?</a></li><li><a href="https://docs.databricks.com/">Databricks Documentation</a></li><li><a href="https://docs.databricks.com/aws/en/data-governance/unity-catalog/">Unity Catalog documentation</a></li><li><a href="https://docs.databricks.com/aws/en/volumes/">Unity Catalog Volumes</a></li><li><a href="https://docs.delta.io/">Delta Lake documentation</a></li><li><a href="https://learn.microsoft.com/en-us/azure/architecture/data-guide/relational-data/data-warehousing">Microsoft Learn: Data warehousing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f516d03f5833" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Databricks in Action: From Unity Catalog to Business Insights with SQL, Genie & AI/BI Dashboards]]></title>
            <link>https://medium.com/@shannuvemula07/databricks-in-action-from-unity-catalog-to-business-insights-with-sql-genie-ai-bi-dashboards-a8f8edefcddc?source=rss-cababb162495------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8f8edefcddc</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sharanya]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 11:05:17 GMT</pubDate>
            <atom:updated>2026-10-29T11:05:17.977Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Retail Sales Analytics solution end to end, entirely inside Databricks</h3><p>Imagine you have just joined a retail company as a Data Analyst. The business collects sales data across products, regions, sales representatives, customer types and channels, and management wants simple answers: How much have we sold? Which products and regions lead? How do sales change over time? Which categories matter most? Can AI help us find insights faster?</p><p>In this article I answer those questions using only Databricks: <strong>Unity Catalog</strong> to organize the data, <strong>Databricks SQL</strong> to analyze it, <strong>Genie</strong> for AI-assisted analysis, and <strong>AI/BI Dashboards</strong> to present the results.</p><blockquote><strong><em>Note on the data:</em></strong><em> This walkthrough uses a 2,000-row retail sales dataset with the same 13 columns as the course dataset. It is a practice dataset generated for this exercise, so the figures describe this sample and not a real company.</em></blockquote><p>The workflow: from raw CSV to a dashboard</p><h3>The Dataset</h3><p>The table has 13 columns: Product_ID, Sale_Date, Sales_Rep, Region, Sales_Amount, Quantity_Sold, Product_Category, Unit_Cost, Unit_Price, Customer_Type, Discount, Payment_Method and Sales_Channel.</p><p><strong>A note on accuracy:</strong> I used Sales_Amount as the recorded sales amount. I did not recalculate it from Quantity_Sold * Unit_Price, because discounts and other rules may affect the recorded value and I had not verified the calculation logic.</p><h3>Part 1: Organizing Data with Unity Catalog</h3><h3>Catalog, Schema and Table</h3><p>Unity Catalog organizes data in three levels. A <strong>catalog</strong> is the top-level container, a <strong>schema</strong> groups related tables inside a catalog, and a <strong>table</strong> holds the actual rows and columns. Every table is referenced as catalog.schema.table.</p><p>Innomatics → default → sales_dataset</p><p>Why does this matter? Organized data is easy to find, access can be controlled in one place, teams follow one naming standard, and nobody has to hunt for the right copy of a file.</p><h3>Creating the table</h3><ol><li>Open <strong>Catalog</strong> from the left sidebar.</li><li>Select the <strong>Innomatics</strong> catalog and its <strong>default</strong> schema.</li><li>Click <strong>Create → Table</strong>, upload the CSV and name the table sales_dataset.</li><li>Confirm that Sale_Date and the numeric columns have sensible data types, then create the table.</li></ol><h3>Verifying the table</h3><pre>DESCRIBE TABLE innomatics.default.sales_dataset;</pre><pre>SELECT COUNT(*) AS total_records<br>FROM innomatics.default.sales_dataset;</pre><pre>SELECT *<br>FROM innomatics.default.sales_dataset<br>LIMIT 10;</pre><p>The table has 13 columns and 2,000 records, which matches the source file.</p><h3>Part 2: Five Business Questions with Databricks SQL</h3><h3>Task 1: Overall Sales Performance</h3><p><strong>Business question:</strong> What is the overall scale of recorded sales?</p><pre>SELECT<br>  SUM(Sales_Amount)          AS total_sales_revenue,<br>  SUM(Quantity_Sold)         AS total_quantity_sold,<br>  COUNT(*)                   AS total_sales_records,<br>  COUNT(DISTINCT Product_ID) AS distinct_products<br>FROM innomatics.default.sales_dataset;</pre><p><strong>How it works:</strong> One pass over the table. SUM adds values, COUNT(*) counts rows and COUNT(DISTINCT …) counts unique products.</p><pre>total_sales_revenue  total_quantity_sold  total_sales_records  distinct_products<br>          4519933.45                14964                 2000                 30</pre><p><strong>Interpretation:</strong> The business recorded about 4.52 million in sales from 2,000 transactions covering 30 products. The record count matches the table check, so nothing was lost when loading.</p><h3>Task 2: Top Five Products</h3><p><strong>Business question:</strong> Which products contribute the most to recorded sales?</p><pre>SELECT<br>  Product_ID,<br>  SUM(Sales_Amount)  AS total_sales_revenue,<br>  SUM(Quantity_Sold) AS total_quantity_sold<br>FROM innomatics.default.sales_dataset<br>GROUP BY Product_ID<br>ORDER BY total_sales_revenue DESC<br>LIMIT 5;</pre><p><strong>How it works:</strong> Rows are grouped by product, totaled, sorted from highest to lowest revenue, and LIMIT 5 keeps the top five.</p><pre>Product_ID  total_sales_revenue  total_quantity_sold<br>      P102            795835.35                 1044<br>      P101            605282.26                  860<br>      P105            494183.63                 1890<br>      P103            412393.05                 1743<br>      P110            396215.39                  740</pre><p>Top 5 products by sales revenue</p><p><strong>Interpretation:</strong> P102 leads with 17.6% of all revenue. The top five products together account for about 60% of recorded sales, so revenue is concentrated in a few products. Note that P105 sold more units (1,890) than P101 but earned less, which suggests a lower price point.</p><h3>Task 3: Regional Performance</h3><p><strong>Business question:</strong> Which regions perform best, and which may need investigation?</p><pre>SELECT<br>  Region,<br>  SUM(Sales_Amount)  AS total_sales_revenue,<br>  SUM(Quantity_Sold) AS total_quantity_sold<br>FROM innomatics.default.sales_dataset<br>GROUP BY Region<br>ORDER BY total_sales_revenue DESC;</pre><p><strong>How it works:</strong> Same grouping pattern as Task 2, but by region and without a limit, so every region appears.</p><pre>Region  total_sales_revenue  total_quantity_sold<br>  South           1393217.18                 4591<br>   West           1138539.50                 3767<br>  North            778730.54                 2571<br>   East            736685.76                 2455<br>Central            472760.47                 1580</pre><p>Sales revenue by region</p><p><strong>Interpretation:</strong> South is the strongest region with about 31% of revenue, followed by West. Central contributes only about 10%, which makes it the region worth investigating further. The cause could be fewer sales reps, a smaller customer base or a different product mix, and this data alone cannot tell us which.</p><h3>Task 4: Monthly Sales Trend</h3><p><strong>Business question:</strong> How does recorded sales revenue change over time?</p><p>First I checked the data type of Sale_Date. If it is stored as text, it must be converted to a real date, otherwise months may sort alphabetically instead of chronologically.</p><pre>SELECT<br>  date_trunc(&#39;MONTH&#39;, try_to_date(Sale_Date)) AS sales_month,<br>  SUM(Sales_Amount)                           AS total_sales_revenue<br>FROM innomatics.default.sales_dataset<br>GROUP BY date_trunc(&#39;MONTH&#39;, try_to_date(Sale_Date))<br>ORDER BY sales_month;</pre><p><strong>How it works:</strong> try_to_date converts the text into a date (returning NULL instead of an error for a bad value). date_trunc(‘MONTH’, …) maps every date to the first day of its month so I can group by month, and sorting by that date gives chronological order. If Sale_Date is already a DATE column, the conversion is not needed.</p><pre>sales_month  total_sales_revenue<br> 2024-01-01            275958.00<br> 2024-02-01            295047.56<br> 2024-03-01            337186.77<br> 2024-04-01            303534.06<br> 2024-05-01            414111.56<br> 2024-06-01            374179.88<br> 2024-07-01            406111.22<br> 2024-08-01            334724.66<br> 2024-09-01            351722.77<br> 2024-10-01            345562.37<br> 2024-11-01            537091.37<br> 2024-12-01            544703.23</pre><p>Monthly sales revenue trend</p><p><strong>Interpretation:</strong> Revenue rises through the year, with a sharp jump in November and December. Those two months together make up about 24% of annual sales, which points to strong year-end demand. Monthly totals add up to the same overall revenue as Task 1, which is a good sanity check.</p><h3>Task 5: Product Category Contribution</h3><p><strong>Business question:</strong> Which categories contribute the most to recorded sales?</p><pre>SELECT<br>  Product_Category,<br>  SUM(Sales_Amount) AS total_sales_revenue,<br>  ROUND(100.0 * SUM(Sales_Amount) / SUM(SUM(Sales_Amount)) OVER (), 2) AS pct_of_total_sales<br>FROM innomatics.default.sales_dataset<br>GROUP BY Product_Category<br>ORDER BY total_sales_revenue DESC;</pre><p><strong>How it works:</strong> SUM(Sales_Amount) gives each category’s total. The window expression SUM(SUM(Sales_Amount)) OVER () adds up all category totals to get the grand total, so each category’s share is its total divided by the grand total.</p><pre>Product_Category  total_sales_revenue  pct_of_total_sales<br>     Electronics           2484432.75               54.97<br>       Furniture            976949.05               21.61<br> Home Appliances            772239.60               17.09<br>          Sports            143722.38                3.18<br>        Clothing            103783.54                2.30<br> Office Supplies             38806.13                0.86</pre><p>Sales revenue by product category</p><p><strong>Interpretation:</strong> Electronics alone brings in about 55% of revenue, and the top three categories together exceed 93%. Office Supplies contributes under 1%. The percentages add up to 100 (the extra 0.01 is rounding).</p><p><strong>Reasonableness check:</strong> The region totals (Task 3), monthly totals (Task 4) and category totals (Task 5) all add up to the Task 1 total of 4,519,933.45.</p><h3>Part 3: AI-Assisted Analysis with Genie</h3><p>Genie lets you ask questions in plain English and generates SQL behind the scenes. I created a Genie space on innomatics.default.sales_dataset and asked:</p><ol><li>Which five products generated the highest total sales revenue?</li><li>Which region generated the highest recorded sales revenue?</li><li>Which product category contributed the most to total sales?</li><li>Which sales channel generated the highest recorded sales revenue?</li></ol><h3>Validating Genie against my own SQL</h3><p>I never assume AI-generated SQL is correct, so for the first three questions I compared Genie’s answer with my manual queries. These are the results Genie’s answers needed to match:</p><pre>Question                        My SQL result<br>------------------------------  -------------------------------------------<br>Top 5 products                  P102, P101, P105, P103, P110<br>Highest revenue region          South (1,393,217.18)<br>Top product category            Electronics (2,484,432.75, 54.97%)<br>Top sales channel               Retail (2,478,535.31) vs Online (2,041,398.14)</pre><p><strong>Comparison:</strong> [Write one or two lines here from your own Genie run: did the answers match? If they differed, the most common reasons are that Genie used a different column (for example Quantity_Sold * Unit_Price instead of Sales_Amount), applied a different sort order or limit, or handled text dates differently.]</p><p><strong>Verified vs. AI-suggested:</strong> A Genie answer is only a suggestion until it has been matched against a query I wrote and understood. Only then do I treat it as a verified finding.</p><p>Sales revenue by channel</p><h3>Business insights</h3><ul><li><strong>Revenue is concentrated.</strong> Electronics makes up about 55% of sales and the top five products about 60%. A stock shortage or price change in a few items could move overall revenue a lot.</li><li><strong>Regional gap.</strong> South generates about 31% of revenue while Central generates about 10%, so Central deserves a closer look.</li><li><strong>Year-end surge.</strong> November and December contribute about 24% of annual revenue, so inventory and staffing should be planned for that period.</li><li><strong>Channels.</strong> Retail brings in about 55% of revenue and Online the rest, so both channels matter.</li></ul><h3>Part 4: Building the AI/BI Dashboard</h3><h3>Step 1: Dataset</h3><p>In <strong>Dashboards → Create dashboard → Data</strong>, I added a dataset that converts the date once so every chart and the date filter can use it:</p><pre>SELECT<br>  Product_ID,<br>  try_to_date(Sale_Date)                      AS Sale_Date,<br>  date_trunc(&#39;MONTH&#39;, try_to_date(Sale_Date)) AS Sale_Month,<br>  Sales_Rep,<br>  Region,<br>  Sales_Amount,<br>  Quantity_Sold,<br>  Product_Category,<br>  Customer_Type,<br>  Payment_Method,<br>  Sales_Channel<br>FROM innomatics.default.sales_dataset;</pre><h3>Step 2: KPI cards (Counter visualizations)</h3><ul><li>Total Sales Revenue: SUM(Sales_Amount)</li><li>Total Quantity Sold: SUM(Quantity_Sold)</li><li>Distinct Products: COUNT_DISTINCT(Product_ID)</li><li>Total Sales Records (challenge): COUNT(*)</li></ul><h3>Step 3: Charts</h3><ul><li><strong>Sales by Region:</strong> bar chart, X = Region, Y = SUM(Sales_Amount), sorted descending.</li><li><strong>Top Five Products:</strong> horizontal bar chart, Product_ID by SUM(Sales_Amount), sorted descending, limited to 5.</li><li><strong>Monthly Sales Trend:</strong> line chart, X = Sale_Month, Y = SUM(Sales_Amount), in chronological order.</li><li><strong>Sales by Product Category (challenge):</strong> bar chart sorted descending.</li></ul><p>I used a line chart for time because it shows direction, and bar charts for comparing categories because bar lengths are easy to compare.</p><h3>Step 4: Interactive filters</h3><p>I added filters for <strong>Region</strong>, <strong>Product_Category</strong> and, as the challenge, <strong>Sales_Channel</strong>. Each filter is applied to all visualizations that use the dataset.</p><p><strong>Testing:</strong> Selecting one region updated the KPI cards, the top products and the monthly trend. Combining Region with Sales_Channel narrowed the results further, because filters work together. Selecting Central, for example, made the KPI total drop sharply compared with South, matching the Task 3 table.</p><p>Dashboard layout: KPIs, charts and filters</p><h3>Challenges and Lessons Learned</h3><ul><li><strong>Text dates:</strong> Converting Sale_Date to a real date is essential for a correct monthly trend.</li><li><strong>Trust but verify:</strong> AI-generated SQL can look right and still use different logic.</li><li><strong>Use recorded values:</strong> I used Sales_Amount as given instead of recalculating revenue.</li><li><strong>Reconcile totals:</strong> Checking that region, month and category totals match the overall total catches data problems early.</li><li><strong>Structure helps:</strong> A clear Catalog → Schema → Table layout made every query simple to write and share.</li></ul><h3>Conclusion</h3><p>I took raw sales data and built a complete analytics solution without leaving Databricks: organized in Unity Catalog, analyzed with SQL, explored with Genie and presented in an interactive dashboard. My biggest takeaway is that AI speeds up analysis, but validation is what makes an insight trustworthy. Next, I would use Unit_Cost to analyze profit margins and study how discounts affect revenue.</p><p><em>Thanks for reading! Feel free to connect and share your feedback.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8f8edefcddc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind Every Dashboard Is a Data Engineer: What Really Happens to Data Before It Becomes an Insight]]></title>
            <link>https://medium.com/@shannuvemula07/behind-every-dashboard-is-a-data-engineer-what-really-happens-to-data-before-it-becomes-an-insight-e26381355158?source=rss-cababb162495------2</link>
            <guid isPermaLink="false">https://medium.com/p/e26381355158</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Sharanya]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 10:28:49 GMT</pubDate>
            <atom:updated>2026-10-29T10:28:49.614Z</atom:updated>
            <content:encoded><![CDATA[<p>Last Sunday, I ordered biryani from a food delivery app. I tapped “Order,” paid through UPI, and 35 minutes later, dinner arrived. Simple, right?</p><p>Behind that one order, the platform recorded my click, my location, the restaurant’s acceptance, the payment status, the rider’s live GPS and my rating. Multiply that by millions of customers every day. Later, a manager will open a dashboard and ask, <em>“Why did deliveries slow down in Hyderabad last Friday?”</em></p><p>The dashboard answers in seconds. But who made sure that data was collected, cleaned, and ready? That’s where <strong>Data Engineering</strong> comes in, and in this article I’ll explain it the way I wish someone had explained it to me.</p><h3>1. What Is Data Engineering?</h3><p>In my own words: <strong>Data Engineering is the practice of building the systems that collect, move, clean, and organize data, so that anyone in the company can trust and use it.</strong></p><p>Think of a city’s water supply. Water starts in a river or reservoir (the source), travels through pipes, gets filtered at treatment plants, and finally reaches your tap clean and ready to drink. You never think about the plumbing until it breaks. Data Engineers are the <strong>plumbers and architects of the data world</strong>.</p><p><strong>Where does data come from?</strong></p><ul><li>Mobile apps and websites (clicks, searches, orders)</li><li>Transaction systems (payments, bookings, bank transfers)</li><li>Logs and sensors (app logs, GPS, IoT devices)</li><li>Third-party sources (partner APIs, CSV and Excel files)</li></ul><p><strong>What does a Data Engineer do?</strong></p><ul><li><strong>Collects (ingests)</strong> data from many sources, in batches (for example, every night) or as a stream (in real time)</li><li><strong>Processes</strong> it: removes duplicates, fixes formats, handles missing values</li><li><strong>Organizes</strong> it into well-structured tables and data models</li><li><strong>Delivers</strong> it to analysts, dashboards, and machine learning models</li><li><strong>Monitors</strong> the pipelines so they run on time, every time</li></ul><p><strong>Example (food delivery):</strong> Orders arrive from the app, payments from the payment gateway, and rider locations from GPS. A data pipeline joins them, removes duplicate or test orders, converts timestamps to one timezone, and produces a clean daily_delivery_performance table. This is what the manager’s dashboard reads from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_OJaLmL1Zoo_pV6vFykYw.png" /><figcaption><strong>data_pipeline</strong></figcaption></figure><p><em>How data travels from raw sources to business insights. Image created by me.</em></p><p>A popular way to organize this journey is the <strong>Medallion architecture</strong>: <strong>Bronze</strong> (raw data, stored exactly as received), <strong>Silver</strong> (cleaned and validated), and <strong>Gold</strong> (business-ready tables). Each layer improves the data’s quality a little more.</p><h3>2. Why Do We Need Data Engineering?</h3><p>Imagine a retail company with millions of records spread across the billing system, the website, the warehouse software, and a few Excel sheets. Customer names are spelled three different ways. Some orders appear twice. Some have no price. Dates are written as 12/03/2026 in one system and 2026-03-12 in another.</p><p>Now someone asks: <em>“What was our revenue last quarter?”</em> Three teams give three different answers. Sound familiar?</p><p><strong>Problems when data is not managed properly:</strong></p><ul><li><strong>Duplicate records</strong> inflate sales and customer counts</li><li><strong>Missing values</strong> skew averages and hide trends</li><li><strong>Inconsistent formats</strong> make it impossible to combine sources</li><li><strong>Siloed systems</strong> mean no one has the full picture</li><li><strong>Slow, manual reporting</strong>, where analysts spend most of their time cleaning data instead of analyzing it</li></ul><p><strong>Why data quality matters:</strong> “Garbage in, garbage out” is very real. If a bank’s data wrongly shows customers as inactive, it might cancel offers for loyal customers. If an e-commerce company counts duplicate orders, it might over-stock a product and lose money. A decision is only as good as the data behind it.</p><p><strong>What messy data looks like.</strong> Here is a tiny orders dataset I created on purpose with typical problems: a duplicate order (1003), a missing price (1004), and the same city written three ways (Hyderabad, hyderabad, HYDERABAD).</p><p>python</p><pre>from pyspark.sql import functions as F</pre><pre>data = [<br>    (1001, &quot;C01&quot;, &quot;Biryani&quot;,       &quot;Food&quot;,        2, 250.0,  &quot;2026-03-01&quot;, &quot;Hyderabad&quot;),<br>    (1002, &quot;C02&quot;, &quot;Pizza&quot;,         &quot;Food&quot;,        1, 399.0,  &quot;2026-03-01&quot;, &quot;hyderabad&quot;),<br>    (1003, &quot;C03&quot;, &quot;Headphones&quot;,    &quot;Electronics&quot;, 1, 1999.0, &quot;2026-03-02&quot;, &quot;Bengaluru&quot;),<br>    (1003, &quot;C03&quot;, &quot;Headphones&quot;,    &quot;Electronics&quot;, 1, 1999.0, &quot;2026-03-02&quot;, &quot;Bengaluru&quot;),<br>    (1004, &quot;C04&quot;, &quot;Running Shoes&quot;, &quot;Fashion&quot;,     1, None,   &quot;2026-03-02&quot;, &quot;Chennai&quot;),<br>    (1005, &quot;C05&quot;, &quot;Biryani&quot;,       &quot;Food&quot;,        3, 250.0,  &quot;2026-03-03&quot;, &quot;HYDERABAD&quot;),<br>    (1006, &quot;C06&quot;, &quot;Smartwatch&quot;,    &quot;Electronics&quot;, 1, 4999.0, &quot;2026-03-03&quot;, &quot;Mumbai&quot;),<br>    (1007, &quot;C01&quot;, &quot;Pizza&quot;,         &quot;Food&quot;,        2, 399.0,  &quot;2026-03-04&quot;, &quot;Hyderabad&quot;),<br>    (1008, &quot;C07&quot;, &quot;T-Shirt&quot;,       &quot;Fashion&quot;,     4, 499.0,  &quot;2026-03-04&quot;, &quot;Bengaluru&quot;),<br>    (1009, &quot;C08&quot;, &quot;Headphones&quot;,    &quot;Electronics&quot;, 2, 1999.0, &quot;2026-03-05&quot;, &quot;Chennai&quot;),<br>    (1010, &quot;C02&quot;, &quot;Biryani&quot;,       &quot;Food&quot;,        1, 250.0,  &quot;2026-03-05&quot;, &quot;Hyderabad&quot;),<br>]</pre><pre>schema = (&quot;order_id INT, customer_id STRING, product STRING, category STRING, &quot;<br>          &quot;quantity INT, price DOUBLE, order_date STRING, city STRING&quot;)</pre><pre>raw_df = spark.createDataFrame(data, schema)<br>display(raw_df)</pre><p><strong>Spotting bad data with code:</strong> A Data Engineer’s first job is often to measure how bad the data is.</p><p>python</p><pre>total_rows     = raw_df.count()<br>duplicate_rows = total_rows - raw_df.dropDuplicates([&quot;order_id&quot;]).count()<br>missing_price  = raw_df.filter(F.col(&quot;price&quot;).isNull()).count()</pre><pre>print(f&quot;Total rows      : {total_rows}&quot;)<br>print(f&quot;Duplicate orders: {duplicate_rows}&quot;)<br>print(f&quot;Missing prices  : {missing_price}&quot;)</pre><p>Output:</p><pre>Total rows      : 11<br>Duplicate orders: 1<br>Missing prices  : 1</pre><p>Now imagine this at the scale of 10 million rows. Nobody can spot that by eye, which is exactly why automated checks matter.</p><p><strong>How Data Engineering helps:</strong></p><ul><li><strong>Reliable:</strong> automated quality checks catch bad data early</li><li><strong>Accessible:</strong> data from many systems lands in one trusted place</li><li><strong>Timely:</strong> pipelines refresh data on schedule, or in real time</li><li><strong>Reusable:</strong> one clean table can serve ten different reports</li></ul><p><strong>The cleaning process as a flowchart:</strong> This is the logic a pipeline follows to turn raw (Bronze) data into clean (Silver) data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DFpamitmB-K7R2IZ5GdNg.png" /><figcaption><strong>data_cleaning_flowchart</strong></figcaption></figure><p><strong>Data pipelines and business reporting:</strong> A pipeline is an automated assembly line. Every morning, it pulls yesterday’s data, cleans it, and refreshes the dashboards, so leaders start their day with fresh and consistent numbers instead of waiting for someone to prepare a spreadsheet.</p><h4>OLTP vs. OLAP</h4><p>Companies use two very different kinds of systems:</p><ul><li><strong>OLTP (Online Transaction Processing)</strong> systems run the business: placing an order, transferring money, booking a ticket. They handle many small, fast operations.</li><li><strong>OLAP (Online Analytical Processing)</strong> systems analyze the business: monthly sales by region, customer trends over three years. They handle fewer but much heavier queries over historical data.</li></ul><p>You don’t want a giant analytical query slowing down a customer’s payment. So Data Engineers copy data from OLTP systems into analytical systems (a warehouse or lakehouse) through pipelines. Here is the difference in SQL:</p><p>sql</p><pre>-- OLTP: a small, fast transaction (one customer places one order)<br>INSERT INTO orders (order_id, customer_id, product, quantity, price)<br>VALUES (1011, &#39;C09&#39;, &#39;Biryani&#39;, 2, 250);</pre><pre>-- OLAP: a heavy analytical question over lots of history<br>SELECT city, category, SUM(revenue) AS total_revenue<br>FROM orders_clean<br>GROUP BY city, category<br>ORDER BY total_revenue DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXK7pLrr6mnTlV5sJE_Q_Q.png" /><figcaption><strong>oltp_vs_olap</strong></figcaption></figure><h3>3. Data Engineer vs. Data Analyst</h3><p>Let’s say a retail company notices its sales have dropped. Who does what?</p><p><strong>The Data Engineer</strong> makes sure sales, inventory, customer, and marketing data from all stores and the website flows into one clean, trusted, up-to-date table.</p><p><strong>The Data Analyst</strong> then uses that table to dig in: <em>Which region declined? Which product category? Is it new customers or repeat customers? Did it start after a price change?</em> They build the dashboard and tell the story to leadership.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjkYCoN_50wQX4jXdcTf9A.png" /><figcaption><strong>data_engineer_vs_data_analyst</strong></figcaption></figure><p><strong>How they collaborate:</strong> The analyst might notice that “North region sales dropped 40% overnight.” Instead of a business crisis, the engineer discovers that one store’s data feed broke. Without the engineer, the analyst might have reported a false crisis. Without the analyst, the engineer’s clean data would never turn into a decision. The best results come when both talk to each other early and often.</p><p><strong>What each role’s work looks like in code:</strong></p><p>sql</p><pre>-- DATA ENGINEER: build a trusted daily sales table (scheduled to run every day)<br>CREATE OR REPLACE TABLE daily_sales AS<br>SELECT order_date, city, category,<br>       SUM(revenue)             AS total_revenue,<br>       COUNT(DISTINCT order_id) AS total_orders<br>FROM orders_silver<br>GROUP BY order_date, city, category;</pre><pre>-- DATA ANALYST: use that table to investigate the sales trend<br>SELECT city, SUM(total_revenue) AS revenue<br>FROM daily_sales<br>WHERE order_date BETWEEN &#39;2026-03-01&#39; AND &#39;2026-03-05&#39;<br>GROUP BY city<br>ORDER BY revenue ASC;</pre><h3>4. Getting Started with Databricks</h3><p>Databricks is a unified platform where teams can build data pipelines, run analytics, and develop AI applications in one place. As a beginner, three concepts matter most.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euQIe9v1NznE5T7YPbwKSg.png" /><figcaption><strong>databricks_workspace_notebook_compute</strong></figcaption></figure><h4>A. Databricks Workspace</h4><p>A <strong>workspace</strong> is your team’s online project office. It’s the environment where you organize and access everything you need for your data work. It keeps related work together in folders, controls who can see or edit what, and lets people collaborate in the same place.</p><p><strong>Resources inside a workspace include:</strong></p><ul><li>Notebooks and folders</li><li>Compute resources (clusters, SQL warehouses)</li><li>Jobs and pipelines (automated workflows)</li><li>Queries and dashboards</li><li>Data and tables, managed through the catalog</li></ul><h4>B. Compute</h4><p><strong>Compute</strong> is the processing power (CPU, memory, and the Spark engine) that actually runs your code and data tasks in Databricks.</p><p><strong>Writing code vs. executing code:</strong> Writing code is like writing a recipe on paper. It doesn’t cook anything. Executing code is cooking the dish, and that needs a kitchen, a stove, and ingredients. A notebook holds your recipe, and <strong>compute is the kitchen</strong>.</p><p>That’s why a notebook needs to be attached to compute before it can run. Processing a million rows takes real computing resources. And just like a restaurant kitchen, you can make it bigger for a busy day, and switch it off when it isn’t needed to save cost.</p><p>python</p><pre># Writing code = the recipe (nothing happens yet)<br>row_count = raw_df.count()</pre><pre># Executing code = cooking (compute processes the data and returns the answer)<br>print(row_count)</pre><h4>C. Notebooks</h4><p>A <strong>Databricks Notebook</strong> is an interactive document where you can write code, add explanations, run it, and see the results all in one place.</p><p><strong>Cells:</strong> A notebook is divided into cells. Each cell can hold a <strong>Markdown</strong> explanation, <strong>Python or SQL</strong> code, or an <strong>output</strong> (a table or chart) shown right below it. You can mix languages too: Python to load and clean data, SQL to analyze it.</p><p><strong>A beginner walkthrough using the orders data:</strong></p><p><strong>Cell 1 (Markdown):</strong> describe the goal.</p><pre>%md<br># Orders Analysis<br>Goal: find the top-selling products after cleaning the data.</pre><p><strong>Cell 2 (Python):</strong> create and view the raw data (the code from Section 2).</p><p><strong>Cell 3 (Python):</strong> clean the data.</p><p>python</p><pre>clean_df = (<br>    raw_df<br>    .dropDuplicates([&quot;order_id&quot;])                       # remove duplicate orders<br>    .dropna(subset=[&quot;price&quot;])                           # remove rows with no price<br>    .withColumn(&quot;city&quot;, F.initcap(F.trim(&quot;city&quot;)))      # hyderabad / HYDERABAD -&gt; Hyderabad<br>    .withColumn(&quot;order_date&quot;, F.to_date(&quot;order_date&quot;))  # text -&gt; real date<br>    .withColumn(&quot;revenue&quot;, F.col(&quot;quantity&quot;) * F.col(&quot;price&quot;))<br>)</pre><pre>clean_df.createOrReplaceTempView(&quot;orders_clean&quot;)<br>display(clean_df)</pre><p><strong>Cell 4 (SQL):</strong> analyze the data.</p><p>sql</p><pre>%sql<br>SELECT product, SUM(revenue) AS total_revenue<br>FROM orders_clean<br>GROUP BY product<br>ORDER BY total_revenue DESC</pre><p>Result:</p><pre>Headphones   5997<br>Smartwatch   4999<br>T-Shirt      1996<br>Biryani      1500<br>Pizza        1197</pre><p><strong>Cell 5:</strong> click the chart icon under the result to turn the table into a bar chart.</p><p>In a few small cells, I went from a messy dataset to a clear business insight: headphones are the top revenue driver. Every step is visible and repeatable.</p><p><strong>Bronze, Silver and Gold in code:</strong> Once the cleaning works, a Data Engineer saves each stage as a table so others can reuse it.</p><p>python</p><pre># BRONZE: raw data, stored as received<br>raw_df.write.mode(&quot;overwrite&quot;).saveAsTable(&quot;orders_bronze&quot;)</pre><pre># SILVER: cleaned and validated data<br>clean_df.write.mode(&quot;overwrite&quot;).saveAsTable(&quot;orders_silver&quot;)</pre><pre># GOLD: business-ready summary for dashboards<br>gold_df = (<br>    clean_df.groupBy(&quot;city&quot;, &quot;category&quot;)<br>    .agg(F.sum(&quot;revenue&quot;).alias(&quot;total_revenue&quot;),<br>         F.countDistinct(&quot;order_id&quot;).alias(&quot;total_orders&quot;))<br>)<br>gold_df.write.mode(&quot;overwrite&quot;).saveAsTable(&quot;sales_by_city_category&quot;)</pre><h3>How It All Connects in a Real Business</h3><p>Back to my biryani order. The app, payments, and GPS generate raw data (<strong>sources</strong>). The <strong>Data Engineer</strong> builds pipelines in Databricks that ingest this data into Bronze, clean it into Silver, and shape it into Gold, running on <strong>compute</strong> and organized in the <strong>workspace</strong>. The <strong>Data Analyst</strong> opens a <strong>notebook</strong> or dashboard, queries the Gold tables, and discovers that Friday-evening delays were caused by rider shortages in one area. The business acts on it, and the next Friday, my biryani arrives in 25 minutes.</p><h3>What I Learned</h3><p>Before this, I thought data work was mostly about charts and dashboards. Now I see those are just the tip of the iceberg. The real foundation is trustworthy, well-organized data. Three things stood out to me:</p><ol><li><strong>Data quality is a business problem, not just a technical one.</strong> Bad data leads to bad decisions.</li><li><strong>Engineers and analysts need each other.</strong> One builds the road, the other drives on it.</li><li><strong>Tools like Databricks make this hands-on.</strong> Workspace, compute, and notebooks gave me a place to actually start practicing.</li></ol><p>This is only my first step, and I’ll be sharing more as I learn.</p><h3>References</h3><ul><li>Databricks Glossary, What is Data Engineering: <a href="https://www.databricks.com/glossary/data-engineering">https://www.databricks.com/glossary/data-engineering</a></li><li>Databricks Documentation, Introduction to Databricks concepts: <a href="https://docs.databricks.com/aws/en/getting-started/concepts">https://docs.databricks.com/aws/en/getting-started/concepts</a></li><li>Databricks Documentation, Notebooks: <a href="https://docs.databricks.com/aws/en/notebooks/">https://docs.databricks.com/aws/en/notebooks/</a></li><li>Databricks Documentation, Compute: <a href="https://docs.databricks.com/aws/en/compute/">https://docs.databricks.com/aws/en/compute/</a></li><li>Databricks Glossary, Medallion Architecture: <a href="https://www.databricks.com/glossary/medallion-architecture">https://www.databricks.com/glossary/medallion-architecture</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e26381355158" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Raw Data to Reliable Predictions: A Practical Guide to the Machine Learning Pipeline]]></title>
            <link>https://medium.com/@shannuvemula07/from-raw-data-to-reliable-predictions-a-practical-guide-to-the-machine-learning-pipeline-8c508c368644?source=rss-cababb162495------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c508c368644</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sharanya]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 09:48:30 GMT</pubDate>
            <atom:updated>2026-10-23T09:48:30.220Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Machine learning is more than choosing an algorithm. The quality of the data, the way it is prepared, and the way a model is evaluated all shape whether it works in the real world.</em></p><p>A model can be mathematically sophisticated and still perform poorly if its input data is incomplete, inconsistent, biased, or prepared incorrectly. A reliable machine learning project therefore follows a repeatable workflow: define the problem, understand the data, prepare useful features, train a model, evaluate it honestly, and keep monitoring it after deployment.</p><p>This guide walks through that workflow, explains the most common preprocessing techniques, and shows how to avoid one of the most damaging mistakes in machine learning: <strong>data leakage</strong>.</p><h3>1. The End-to-End Machine Learning Pipeline</h3><p>Machine learning is an iterative process rather than a one-way checklist. If evaluation reveals weak performance, we may need to revisit the features, preprocessing, data collection, or even the original problem definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jdp9lSoVgrvPt5H0rJdQgA.png" /><figcaption><em>Figure 1: A practical machine learning workflow, from defining the problem to monitoring a deployed model.</em></figcaption></figure><p>A useful principle: <strong>better data and better validation often matter more than choosing a more complicated algorithm.</strong></p><h3>2. Data Preprocessing: Turning Raw Data into Model-Ready Data</h3><p>Real-world datasets commonly contain missing entries, inconsistent units, text categories, extreme values, skewed distributions, irrelevant columns, or imbalanced target classes. Preprocessing addresses these issues in ways that are appropriate for the dataset and the algorithm.</p><p>Not every dataset needs every technique. The goal is not to apply as many transformations as possible; it is to make the data reliable without introducing bias or losing useful information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2CCMTST1OTypUvcZfH3Uw.png" /><figcaption><em>Figure 2: Choose preprocessing methods based on the issues actually present in the dataset.</em></figcaption></figure><h3>2.1 Missing Value Handling</h3><p>Missing values may appear because of data-entry errors, sensor failures, unanswered questions, or limitations in data collection. Many machine learning algorithms cannot accept missing values directly, and careless handling can introduce bias.</p><h4>Understand why values are missing</h4><ul><li><strong>MCAR (Missing Completely At Random):</strong> missingness is unrelated to observed or unobserved data.</li><li><strong>MAR (Missing At Random):</strong> missingness is associated with other observed variables.</li><li><strong>MNAR (Missing Not At Random):</strong> missingness is related to the missing value itself or to an unobserved factor. For example, a person may avoid reporting a particularly high income.</li></ul><p>These mechanisms are useful concepts, but they cannot always be identified from the dataset alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGhkaLqmZoVc1xPrSV8zww.png" /><figcaption><em>Figure 3: A practical starting point for choosing a missing-value strategy.</em></figcaption></figure><h4>Common techniques</h4><p>Technique How it works When it may be appropriate Limitation Row or column deletion Removes observations or features with missing values.Missingness is limited and removal is defensible. Can discard information or create bias.Mean imputation Replaces missing numeric values with the mean.Numeric data is reasonably symmetric and has no severe outliers.Reduces variance and can distort relationships.Median imputation Uses the median of a numeric feature.Data is skewed or contains outliers.Does not account for relationships among features.Mode imputationUses the most frequent category.Categorical features.Can overrepresent the most common category.Constant or “Unknown” Uses a fixed value or an explicit missing category.Missingness itself may carry information.A chosen value can be misleading if used without thought.Forward/backward fill Uses a neighbouring observation.Ordered time-series data where this is meaningful.Can be inappropriate across large gaps or abrupt changes.KNN imputation Uses similar observations to estimate missing values.Features have meaningful similarity and the dataset is manageable.Can be computationally expensive and scale-sensitive.Iterative imputation Predicts missing values from other features.Relationships among features may help estimate missing values.More complex and dependent on modelling assumptions.Missingness indicator Adds a flag showing whether a value was missing.Missingness may be predictive.Does not replace the need to impute when the model requires complete data.</p><h4>Python example</h4><pre>from sklearn.impute import SimpleImputer</pre><pre># Fit the imputer using training data only<br>imputer = SimpleImputer(strategy=&quot;median&quot;)<br>X_train[[&quot;age&quot;, &quot;income&quot;]] = imputer.fit_transform(<br>    X_train[[&quot;age&quot;, &quot;income&quot;]]<br>)</pre><pre># Apply the same learned medians to test data<br>X_test[[&quot;age&quot;, &quot;income&quot;]] = imputer.transform(<br>    X_test[[&quot;age&quot;, &quot;income&quot;]]<br>)</pre><p><strong>Common mistake:</strong> imputing the entire dataset before splitting it. The test data would influence the imputation statistics, causing data leakage.</p><h3>2.2 Feature Scaling</h3><p>Features can use very different units. For example, age might range from 18 to 70, while annual income might range from 200,000 to 2,000,000. Distance-based algorithms and many optimisation methods can be dominated by features with larger numeric scales.</p><p>Scaling changes the numeric range or distribution of features while preserving their relative information in a form useful to the algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YA6B4QmBHXzW50RXk-oAQ.png" /><figcaption><em>Figure 4: Min-Max, standard, and robust scaling use different statistics and are useful in different situations.</em></figcaption></figure><h4>Main scaling methods</h4><p><strong>Min-Max scaling</strong></p><p>Maps values to a chosen range, commonly [0, 1].</p><p><strong>Formula:</strong></p><p><strong>x_scaled = (x — x_min) / (x_max — x_min)</strong></p><p>It is useful when a bounded range is desirable, but extreme values can compress most observations into a narrow interval.</p><p><strong>Standardization (Z-score scaling)</strong></p><p>Centres a feature around zero and scales it by its standard deviation.</p><p><strong>Formula:</strong></p><p><strong>z = (x — μ) / σ</strong></p><p>It is often useful for SVM, KNN, PCA, and linear or logistic models with regularisation. It does not guarantee that values fall between zero and one.</p><p><strong>Robust scaling</strong></p><p>Uses the median and interquartile range (IQR).</p><p><strong>Formula:</strong></p><p><strong>x_robust = (x — median(x)) / IQR(x)</strong></p><p>It is less sensitive to extreme values than mean-and-standard-deviation scaling.</p><p><strong>Max-Abs scaling</strong></p><p>Divides each value by the maximum absolute value of its feature. It can be useful for sparse data because it preserves zeros.</p><h4>Python example</h4><pre>from sklearn.preprocessing import StandardScaler</pre><pre>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br>X_test_scaled = scaler.transform(X_test)</pre><p>Scaling is generally important for KNN, K-Means, SVM, PCA, neural networks, and many linear models. Tree-based models such as Decision Trees and Random Forests usually do not require it.</p><p><strong>Common mistakes:</strong> fitting the scaler on the full dataset, scaling the target accidentally, and assuming every algorithm needs scaling.</p><h3>2.3 Categorical Encoding</h3><p>Many datasets contain categories such as city, product type, education level, or customer segment. Most traditional scikit-learn estimators expect numeric inputs, so categories must be represented appropriately.</p><p>The key question is whether the categories have a meaningful order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQEn4y-kN3TCYzgdN3Kydw.png" /><figcaption><em>Figure 5: Select an encoding method based on category meaning and the number of unique values.</em></figcaption></figure><p>Method How it works Suitable use Main caution Label encoding Assigns an integer to each class label.Often used for target labels.Arbitrary integers can imply a false order when used for nominal input features.Ordinal encoding Maps categories to integers in a specified order.Low &lt; Medium &lt; High, when this order is meaningful.Define the order explicitly.One-hot encoding Creates a binary column for each category.Nominal categories with a manageable number of levels.Can create many columns for high-cardinality features.Dummy encoding Uses one fewer binary column than the number of categories.Some linear-model designs where a reference category is useful.Interpret coefficients relative to the omitted category.Binary encoding Represents category codes through binary digits across columns.Some medium- or high-cardinality features.Less directly interpretable.Frequency/count encodingReplaces categories with their occurrence counts or frequencies.High-cardinality categories in some settings.Different categories may receive the same value.Target/mean encoding Uses a target statistic for each category.High-cardinality features when implemented carefully.Can leak target information; use smoothing and leakage-safe cross-validation.</p><h4>Python example</h4><pre>from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder</pre><pre># Nominal feature<br>encoder = OneHotEncoder(handle_unknown=&quot;ignore&quot;)<br>city_train = encoder.fit_transform(X_train[[&quot;city&quot;]])<br>city_test = encoder.transform(X_test[[&quot;city&quot;]])</pre><pre># Ordered feature<br>ordinal_encoder = OrdinalEncoder(<br>    categories=[[&quot;Low&quot;, &quot;Medium&quot;, &quot;High&quot;]]<br>)<br>risk_train = ordinal_encoder.fit_transform(X_train[[&quot;risk&quot;]])</pre><p><strong>Rule of thumb:</strong> use one-hot encoding for nominal features with relatively few categories, ordinal encoding for genuinely ordered categories, and carefully validated alternatives for high-cardinality features.</p><h3>2.4 Outlier Detection and Treatment</h3><p>An outlier is an observation that lies unusually far from the bulk of the data. It may be an error, such as an impossible age, or a legitimate rare event, such as a very high transaction value.</p><p>Outliers can strongly affect means, standard deviations, and some algorithms — especially methods that rely on distances or squared errors. However, unusual does not automatically mean incorrect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E2aLQP54OwKUtL_wFPVGMg.png" /><figcaption><em>Figure 6: Detect potential outliers, investigate their meaning, and then choose a treatment.</em></figcaption></figure><h4>Common detection methods</h4><p><strong>Visual methods:</strong> histograms, box plots, and scatter plots help reveal extreme values and unusual patterns.</p><p><strong>Z-score method:</strong> flags values far from the mean in standard-deviation units. A common heuristic is \(|z| &gt; 3\), although this can be unreliable for heavily skewed data.</p><p><strong>Interquartile Range (IQR) Method</strong></p><p><strong>1. Interquartile Range:</strong></p><p>IQR = Q3 — Q1</p><p><strong>2. Lower Fence:</strong></p><p>Lower Fence = Q1–1.5 × IQR</p><p><strong>3. Upper Fence:</strong></p><p>Upper Fence = Q3 + 1.5 × IQR</p><p>Values beyond these fences are flagged for investigation; they are not automatically errors.</p><pre>q1, q3 = df[&quot;salary&quot;].quantile([0.25, 0.75])<br>iqr = q3 - q1</pre><pre>lower = q1 - 1.5 * iqr<br>upper = q3 + 1.5 * iqr</pre><pre>outliers = df[<br>    (df[&quot;salary&quot;] &lt; lower) | (df[&quot;salary&quot;] &gt; upper)<br>]</pre><pre># Example of capping rather than deleting rows<br>df[&quot;salary_capped&quot;] = df[&quot;salary&quot;].clip(lower, upper)</pre><h4>What should you do with outliers?</h4><ul><li><strong>Correct or remove</strong> confirmed data errors when justified.</li><li><strong>Cap (winsorize)</strong> extreme values if preserving the row is important and capping is appropriate.</li><li><strong>Transform</strong> highly skewed features when a transformation suits the data.</li><li><strong>Keep</strong> valid extreme observations when they represent important real-world cases.</li><li><strong>Treat as missing</strong> only when there is a defensible reason to regard the value as invalid.</li></ul><p>Outlier thresholds should be learned from training data in a predictive workflow. Automatically deleting all outliers can remove valuable information.</p><h3>2.5 Data Transformation</h3><p>Transformation changes a feature’s representation to make patterns easier for a model to learn. It may reduce skewness, stabilise variance, or help a model represent nonlinear relationships.</p><p>TransformationTypical useCautionLog / log1pStrong right skew in positive values; log1p also handles zero.Ordinary log is not defined for zero or negative values.Square rootModerate right skew or some count features.Only appropriate for values in its valid domain.ReciprocalSome heavily skewed positive data.Undefined at zero and changes interpretation substantially.Box-CoxFinds a power transformation for strictly positive data.Requires positive inputs.Yeo-JohnsonPower transformation that can handle zero and negative values.Still changes the feature scale and interpretation.Quantile transformationMaps a feature toward a uniform or normal distribution.Can distort distances and relationships.BinningGroups continuous values into intervals.Loses detail and depends on bin boundaries.Polynomial featuresAdds terms such as \(x^2\) or interactions to capture nonlinear patterns.Increases feature count and can increase overfitting.</p><pre>import numpy as np</pre><pre># Useful for non-negative values, including zero<br>df[&quot;income_log&quot;] = np.log1p(df[&quot;income&quot;])</pre><p>Transformations should be selected based on data characteristics and model assumptions — not applied automatically. If the target is transformed, predictions may need to be converted back to the original scale before interpretation.</p><h3>2.6 Feature Selection</h3><p>Feature selection keeps the predictors that are useful for the task and removes irrelevant or redundant ones. It can reduce training time, simplify a model, and sometimes improve generalisation.</p><p>Family How it works Examples Trade-off Filter methods Rank features using statistical criteria before model fitting.Correlation, chi-square, ANOVA F-test, mutual information, variance threshold.Fast, but may miss interactions.Wrapper methods Compare candidate feature subsets by repeatedly training a model.Forward selection, backward elimination, recursive feature elimination (RFE).Can be computationally expensive.Embedded methodsSelect or prioritise features as part of model training.Lasso regularisation, tree-based feature importance.Selection depends on the model and data.</p><p>Feature selection must be performed using training data only. A feature with low linear correlation may still contain nonlinear or interaction-based information, so do not remove features based on one statistic alone.</p><h3>2.7 Handling Class Imbalance</h3><p>Classification datasets are often imbalanced. For example, a fraud dataset might contain 99% legitimate transactions and 1% fraudulent transactions. A model that always predicts “legitimate” could achieve 99% accuracy while failing to identify any fraud.</p><h4>Common strategies</h4><ul><li><strong>Random oversampling:</strong> duplicates minority-class examples; may increase overfitting.</li><li><strong>Random undersampling:</strong> removes majority-class examples; may discard useful information.</li><li><strong>SMOTE:</strong> generates synthetic minority-class examples using neighbouring observations.</li><li><strong>Class weights:</strong> assigns a larger penalty to errors on the minority class.</li><li><strong>Threshold tuning:</strong> changes the probability threshold to adjust the precision-recall trade-off.</li><li><strong>Better evaluation metrics:</strong> use precision, recall, F1-score, and often PR-AUC instead of relying on accuracy alone.</li></ul><p>Resampling must happen <strong>only within the training data</strong>. Keep validation and test data at their natural class distribution so evaluation reflects the real problem.</p><pre>from imblearn.over_sampling import SMOTE</pre><pre>smote = SMOTE(random_state=42)<br>X_train_balanced, y_train_balanced = smote.fit_resample(<br>    X_train, y_train<br>)</pre><p>SMOTE is not suitable for every feature representation or dataset. For mixed numeric and categorical features, use a method designed for that data type and place resampling inside a leakage-safe training pipeline.</p><h3>3. Train-Test Split: Can the Model Generalise?</h3><p>A model may perform extremely well on the data it has already seen but fail on new examples. This is called <strong>overfitting</strong>. To estimate generalisation, we hold back data that is not used to fit the model.</p><ul><li><strong>Training set:</strong> used to learn model parameters and fit preprocessing.</li><li><strong>Validation set:</strong> used for model selection and hyperparameter tuning, when a separate validation set is used.</li><li><strong>Test set:</strong> held back until final evaluation to estimate performance on unseen data.</li></ul><h3>Choosing a split ratio</h3><p>SplitTypical situation 80/20 A common starting point for many datasets.70/30 Can be useful when a larger test sample is needed.90/10 Can work for large datasets where 10% still provides enough test examples.Train/validation/test, such as 60/20/20 Useful when separate sets are needed for training, tuning, and final evaluation.</p><p>There is no universally perfect ratio. The choice depends on dataset size, class distribution, data structure, and the reliability required from evaluation.</p><p>For classification, stratify=y can preserve class proportions in the split. random_state makes a random split reproducible. For time-series data, use a chronological split rather than randomly shuffling observations.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y,<br>    test_size=0.2,<br>    random_state=42,<br>    stratify=y  # use for classification when appropriate<br>)</pre><p>Remove stratify=y for regression unless you have a specifically justified stratification strategy.</p><h3>4. Model Building and Algorithm Selection</h3><p>Model building involves choosing an algorithm, defining its settings, and training it. During training, the algorithm learns parameters from the training data by optimising an objective or loss function.</p><p>The first decision is often determined by the target variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oh02wG5o8aSWTsmgchKRGg.png" /><figcaption><em>Figure 7: Start with the task type, build a baseline, compare suitable models, and choose metrics that match the problem.</em></figcaption></figure><h3>Regression: predicting a numeric value</h3><p>Examples include house price, delivery time, demand, and temperature.</p><p>Algorithm When to consider it Caution Linear Regression A simple, interpretable baseline when relationships are approximately linear.Sensitive to outliers and multicollinearity.Ridge / Lasso Many features or a need for regularisation; Lasso can shrink some coefficients to zero.Scaling is often important.Decision Tree / Random ForestNonlinear patterns and interactions in tabular data.Trees and ensembles can be less interpretable.Gradient BoostingStrong performance on many structured/tabular datasets.Requires careful tuning and validation.</p><h3>Classification: predicting a category</h3><p>Examples include spam detection, customer churn, and fraud detection.</p><p>Algorithm When to consider it Caution Logistic Regression Strong baseline with interpretable coefficients and probability estimates.May struggle with complex decision boundaries without feature engineering.K-Nearest Neighbours (KNN) Simple local patterns and smaller datasets.Needs scaling and can be slow on large datasets.Decision TreeRules that are relatively easy to explain.Can overfit without constraints.Random Forest A robust starting point for many tabular classification tasks.Less interpretable than a single tree.Support Vector Machine (SVM)Useful for some medium-sized datasets with clear separation.Scaling is important; training can be expensive on large datasets.Naive BayesFast baseline, especially for many text-classification tasks.Makes simplifying conditional-independence assumptions.</p><p>A practical approach is to train a simple baseline first, compare alternatives using validation or cross-validation, and select the simplest model that meets the performance requirements. Watch for <strong>overfitting</strong> (training performance much better than validation/test performance) and <strong>underfitting</strong> (poor performance on both).</p><h3>5. Evaluating Model Performance</h3><p>A metric should reflect both the prediction task and the cost of different mistakes. No single metric is best for every problem.</p><h3>Regression metrics</h3><p>Metric Meaning How to interpret it MAE Mean absolute error.Average absolute error in the target’s units; lower is better.MSE Mean squared error.Penalises large errors more heavily; lower is better.RMSE Square root of MSE. Expressed in the target’s units; lower is better.R² Proportion of target variation explained relative to a mean baseline.Higher is generally better; it can be negative on test data. Adjusted R²R² adjusted for the number of predictors.Often used when comparing regression models with different feature counts.</p><h3>Classification metrics</h3><p>A confusion matrix separates predictions into true positives (TP), true negatives (TN), false positives (FP), and false negatives (FN).</p><p>MetricFormulaUseful when Accuracy <strong>[(TP + TN) / Total]</strong> Classes are reasonably balanced and error costs are similar.Precision <strong>[TP / (TP + FP) ] </strong>False positives are costly.Recall (sensitivity) <strong>[TP / (TP + FN)]</strong> False negatives are costly.F1-score <strong>[2 × (Precision × Recall) / (Precision + Recall)]</strong> A balance between precision and recall is important.ROC-AUC Area under the ROC curve.Comparing ranking performance across thresholds.PR-AUC Area under the precision-recall curve.Often especially informative for rare positive classes.</p><p>For example, in medical screening, missing a true case may be particularly costly, so recall can be important. In a spam filter, incorrectly marking legitimate email as spam may make precision important. The metric should reflect the real objective.</p><pre>import numpy as np<br>from sklearn.metrics import mean_squared_error, r2_score<br>from sklearn.metrics import classification_report, confusion_matrix</pre><pre># Regression<br>rmse = np.sqrt(mean_squared_error(y_test, y_pred))<br>r2 = r2_score(y_test, y_pred)</pre><pre># Classification<br>print(confusion_matrix(y_test, y_pred))<br>print(classification_report(y_test, y_pred))</pre><p>Use predictions from the model that matches the task: regression metrics for numeric targets and classification metrics for categorical targets.</p><h3>6. Data Leakage: The Mistake That Makes Scores Look Better Than Reality</h3><p>Data leakage occurs when information that would not legitimately be available during training influences model fitting or evaluation. The result is often an overly optimistic score that does not hold up on new data.</p><p>Preprocessing steps such as imputation, scaling, encoding, and feature selection can learn information from data. If they are fitted on the entire dataset before the split, the held-out test set influences the training process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCS0j1wg_w-CjbCIUg9V1A.png" /><figcaption><em>Figure 8: Split first, fit preprocessing on training data, and apply the learned transformations to held-out data.</em></figcaption></figure><h3>Incorrect: preprocessing before splitting</h3><pre># Incorrect: test data contributes to scaling statistics<br>X_scaled = StandardScaler().fit_transform(X)</pre><pre># Splitting after fitting has already leaked information<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><h3>Correct: split first, then fit on training data</h3><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)</pre><pre>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br>X_test_scaled = scaler.transform(X_test)</pre><p>The rule is simple: <strong>use </strong><strong>fit or </strong><strong>fit_transform on training data, then use </strong><strong>transform on validation and test data.</strong></p><p>Other leakage risks include selecting features using the full dataset, applying SMOTE before splitting, allowing duplicate records across train and test sets, using features that are only known after the outcome, and randomly shuffling time-series observations.</p><h3>Use a pipeline for safer preprocessing</h3><p>A scikit-learn Pipeline helps keep preprocessing and model training together. Combined with ColumnTransformer, it can apply different steps to numeric and categorical columns. It also helps ensure that cross-validation refits preprocessing inside each training fold.</p><pre>from sklearn.compose import ColumnTransformer<br>from sklearn.pipeline import Pipeline<br>from sklearn.impute import SimpleImputer<br>from sklearn.preprocessing import StandardScaler, OneHotEncoder<br>from sklearn.linear_model import LogisticRegression</pre><pre>num_cols = [&quot;age&quot;, &quot;income&quot;]<br>cat_cols = [&quot;city&quot;]</pre><pre>preprocess = ColumnTransformer([<br>    (&quot;num&quot;, Pipeline([<br>        (&quot;imputer&quot;, SimpleImputer(strategy=&quot;median&quot;)),<br>        (&quot;scaler&quot;, StandardScaler())<br>    ]), num_cols),</pre><pre>    (&quot;cat&quot;, Pipeline([<br>        (&quot;imputer&quot;, SimpleImputer(strategy=&quot;most_frequent&quot;)),<br>        (&quot;encoder&quot;, OneHotEncoder(handle_unknown=&quot;ignore&quot;))<br>    ]), cat_cols)<br>])</pre><pre>model = Pipeline([<br>    (&quot;preprocess&quot;, preprocess),<br>    (&quot;classifier&quot;, LogisticRegression(max_iter=1000))<br>])</pre><pre>model.fit(X_train, y_train)<br>print(&quot;Test accuracy:&quot;, model.score(X_test, y_test))</pre><p>This example assumes a classification target and that the column names exist in your dataset. For regression, replace the classifier and use suitable regression metrics.</p><h3>7. Quick Revision: Which Technique Should I Try First?</h3><p>Problem A reasonable starting point Missing numeric values in skewed data Median imputation Missing categorical values Mode or an explicit “Unknown” category Features on different scales StandardScaler for many distance-based or regularised models Bounded feature inputs MinMax Scaler when appropriate Nominal feature with few categories One-hot encoding Meaningfully ordered categories Ordinal encoding with an explicit order Extreme values Investigate using plots/IQR; then retain, correct, cap, or transform as justified Strong right skew Consider log or power transformation. Too many irrelevant or redundant features Filter, wrapper, or embedded feature selection Imbalanced classification .Consider class weights, training-only resampling, and precision/recall-based metrics .A fair estimate of generalisation Keep an untouched test set and avoid leakage</p><h3>Five mistakes worth avoiding</h3><ol><li>Fitting preprocessing on the full dataset before splitting.</li><li>Relying on accuracy alone for imbalanced classification.</li><li>Assigning arbitrary integer values to nominal categories and treating them as ordered.</li><li>Removing outliers without checking whether they are genuine observations.</li><li>Forgetting to scale models that depend on distances, or assuming tree-based models always need scaling.</li></ol><h3>Conclusion</h3><p>A dependable machine learning solution is built through a sequence of careful decisions — not by choosing an algorithm alone. Understand the problem, explore the data, preprocess thoughtfully, split the data correctly, build a baseline, evaluate with relevant metrics, and monitor the model after deployment.</p><p>The most important habit to take away is this: <strong>keep your evaluation honest.</strong> Fit learned preprocessing only on training data, keep the test set untouched until final evaluation, and choose techniques because they solve a specific data problem.</p><h3>Further Reading</h3><ul><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/common_pitfalls.html">Scikit-learn: Common pitfalls and recommended practices</a></li><li><a href="https://scikit-learn.org/stable/modules/model_evaluation.html">Scikit-learn: Model evaluation</a></li><li><a href="https://imbalanced-learn.org/">imbalanced-learn documentation</a></li><li>Chawla, N. V. et al. (2002). “SMOTE: Synthetic Minority Over-sampling Technique.” <em>Journal of Artificial Intelligence Research</em>, 16, 321–357.</li></ul><p><em>What preprocessing technique has made the biggest difference in one of your machine learning projects? Share your experience or questions in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c508c368644" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>