<?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 Sami on Medium]]></title>
        <description><![CDATA[Stories by Sami on Medium]]></description>
        <link>https://medium.com/@imsami13062004?source=rss-c95969eee154------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*R-bxGa_Fg80ISUbo</url>
            <title>Stories by Sami on Medium</title>
            <link>https://medium.com/@imsami13062004?source=rss-c95969eee154------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:44:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imsami13062004/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[The Perceptron Problem Nobody Explains Properly]]></title>
            <link>https://medium.com/@imsami13062004/the-perceptron-problem-nobody-explains-properly-ff705dfa8525?source=rss-c95969eee154------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff705dfa8525</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[perceptron]]></category>
            <dc:creator><![CDATA[Sami]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 10:16:19 GMT</pubDate>
            <atom:updated>2026-06-30T10:16:19.062Z</atom:updated>
            <content:encoded><![CDATA[<p>Every course mentions that a single perceptron cannot solve XOR. Almost none show why in a way that sticks. They throw a truth table at you, say “not linearly separable,” and move to the next slide. You nod along and forget it by the next chapter. That gap is worth closing, because it explains the entire reason multi-layer networks exist.</p><h3>What a perceptron actually does</h3><p>A perceptron takes inputs, multiplies each by a weight, adds them, and checks if the sum crosses a threshold. Geometrically, that threshold is a straight line in two dimensions, or a flat plane in higher dimensions. Everything on one side gets one label. Everything on the other side gets the other label. That’s the whole model.</p><p>Now look at XOR. The output is true when exactly one input is true, false otherwise. Plot the four points: (0,0) and (1,1) belong to one class, (0,1) and (1,0) belong to the other. Try to draw one straight line that puts the first pair on one side and the second pair on the other. It can’t be done. The two classes sit in opposite corners, alternating, and no single straight cut separates them.</p><p>This is not a quirk of XOR. It’s a hard limit on what one linear boundary can ever represent. Researchers Minsky and Papert proved this in 1969, and the result stalled neural network research for over a decade because people assumed it meant networks had hit a ceiling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tc61XeEkmm8fM9pYI6p5Fg.png" /></figure><h3>Why stacking layers fixes it</h3><p>A multi-layer perceptron adds a hidden layer between input and output. The hidden layer draws two separate lines instead of one, then combines the results. Picture two perceptrons in the hidden layer, each drawing its own boundary across the four XOR points. Neither line alone solves the problem, but combining their outputs creates a region shaped like a bent boundary, something no single straight line could ever form.</p><p>This is the part most explanations skip. The hidden layer doesn’t add power because it has “more neurons.” It adds power because it lets you combine multiple straight cuts into a curved or folded boundary. Two lines can box in a region a single line cannot touch. That is the entire reason depth matters, demonstrated on the smallest possible example.</p><h3>The part that still confuses people</h3><p>A common assumption is that adding a hidden layer “automatically” solves any classification problem. It does, given enough hidden units and the right training, but the network does not discover the right boundary by magic. It needs backpropagation to adjust every weight in every layer based on the error at the output, layer by layer, working backward. Without that mechanism, a multi-layer perceptron is just an unsolved puzzle with the right shape but no way to fill it in.</p><p>So the real story is two-part. A single perceptron is geometrically blind to certain patterns, full stop, no amount of training fixes that. A multi-layer version removes the geometric blindness, but only because backpropagation gives it a way to learn the right combination of lines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff705dfa8525" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Doesn’t Work the Way Most Intros Claim]]></title>
            <link>https://medium.com/@imsami13062004/deep-learning-doesnt-work-the-way-most-intros-claim-f9a9d1b7e1f8?source=rss-c95969eee154------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9a9d1b7e1f8</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Sami]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 10:03:06 GMT</pubDate>
            <atom:updated>2026-06-30T10:03:06.978Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8BjRLiCOp1AJEiLDEufeQ.png" /></figure><p>Open any beginner course and you get the same line. A neural network is modeled on the brain. Neurons fire, signals pass, intelligence appears. The picture is clean and it is wrong in a way that costs people months of confusion later.</p><p>A biological neuron sends signals through thousands of connections that change shape over time, run on chemistry, and operate without anything resembling a global learning rule. A network node does none of that. It multiplies numbers, adds them, and passes the result through a fixed formula. The brain comparison sells the idea, but it hides the one fact that actually explains why deep learning works.</p><h3>What’s really happening</h3><p>A neural network is a stack of simple math functions, chained together, tuned by repeated correction. Strip away the biology metaphor and you get this: input numbers go in, get multiplied by weights, get added up, and get passed through a small nonlinear twist. Stack that twist a few dozen or a few hundred times and the network can bend an input space into shapes a straight line never could.</p><p>That bending is the entire trick. A single layer can only draw straight boundaries between categories. Add layers, and each one reshapes the space the next layer sees. By the last layer, data that was tangled and inseparable sits in neat, separable groups. No neuron metaphor needed, just geometry, applied over and over.</p><h3>The misconception that trips people up</h3><p>Most learners assume more layers always means more intelligence. That belief comes straight from the brain analogy, since a bigger brain seems smarter. But depth without correction is just noise stacked on noise. Early deep networks failed for decades, not because the idea was wrong, but because gradients shrank to nothing as they traveled backward through many layers. Researchers call this the vanishing gradient problem, and it sat unsolved until better activation functions, normalization tricks, and initialization schemes arrived in the 2010s.</p><p>So depth is not the source of power. Depth is a liability that pays off only when the training process can actually reach every layer. That single correction reframes the entire field. Deep learning took off in 2012 not because someone added more layers, but because someone finally trained deep layers without the signal dying on the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MZ519LRkQ8bTbQbAwCZZqQ.png" /></figure><h3>A simple way to picture it</h3><p>Think of each layer as a filter on a photo. One filter shifts colors slightly. Apply ten filters in sequence and the photo looks transformed, even though each step was small. A neural network does this to data instead of pixels, reshaping it step by step until the categories you care about become easy to separate with a flat cut.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9a9d1b7e1f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MAE vs MSE]]></title>
            <link>https://medium.com/@imsami13062004/mae-vs-mse-9084d2e57fc4?source=rss-c95969eee154------2</link>
            <guid isPermaLink="false">https://medium.com/p/9084d2e57fc4</guid>
            <category><![CDATA[mse]]></category>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[loss-function]]></category>
            <dc:creator><![CDATA[Sami]]></dc:creator>
            <pubDate>Sun, 24 May 2026 06:22:34 GMT</pubDate>
            <atom:updated>2026-05-24T06:22:34.509Z</atom:updated>
            <content:encoded><![CDATA[<h3>Picking the Right Loss Function Changes Everything in Linear Regression</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsDZj9l08qkgs_lJjQOVsw.png" /></figure><blockquote>A practical breakdown of L1 and L2 loss — what they measure, how they behave, and which one your model actually needs.</blockquote><p>Most people learning linear regression focus on the algorithm. But one of the most important decisions you’ll make is something that comes before training even starts — <strong>how you measure error.</strong></p><p>Loss tells your model what “wrong” looks like. Choose the wrong loss function and your model will optimize for the wrong thing — no matter how good your data is.</p><p>Let’s break down the two most common loss functions and when to use each.</p><p><strong>WHAT IS LOSS?</strong></p><p>Loss is simply a number that measures how far a model’s predictions are from the actual values. The goal of training is to minimize this number as much as possible. Crucially, loss focuses on the <em>distance</em> between predicted and actual values — not the direction. So we always remove the sign when calculating it.</p><p><strong><em>L1 Loss</em>:<em> Mean Absolute Error(MAE)</em></strong></p><p>Takes the absolute difference between the predicted and actual value for each data point, then averages them. Every error is penalized equally — a big mistake counts proportionally, not exponentially.</p><p><strong>MAE = (1/n) × Σ |actual − predicted|</strong></p><ul><li>Robust to Outliers</li><li>Easy to Interpret</li><li>Not smooth at zero</li><li>Slower OPtimization</li></ul><p><strong><em>L2 Loss</em>:<em> Mean Squared Error(MSE)</em></strong></p><p>Squares the difference between predicted and actual values before averaging. This means large errors are penalized much more heavily than small ones — outliers have an outsized impact on the model.</p><p><strong>MSE = (1/n) × Σ (actual − predicted)²</strong></p><ul><li>Smooth Gradient</li><li>Penalizes Large Errors</li><li>Senstive to Outliers</li><li>Units are Squared</li></ul><h4>MAE VS MSE</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*ny_ODkxT0Xc7lmdRtYKPeA.png" /></figure><h4>HOW TO CHOOSE :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*mHAV0SSCBXwtadUJonbTdQ.png" /></figure><blockquote><strong>Pro tip:</strong> If you use MSE but want your error back in the same units as your label, use <strong>RMSE</strong> (Root Mean Squared Error) — just take the square root of MSE. It’s the most common metric used in reporting because it’s interpretable <em>and</em> penalizes large errors.</blockquote><p>At the end of the day, there’s no universally “better” loss function. The right choice depends on your data, your outliers, and — critically — <strong>what kind of errors are most costly for your business problem.</strong></p><p>In a fraud detection model, missing a fraud case (large error) should be penalized heavily → MSE. In a demand forecasting model where outlier spikes are seasonal noise → MAE keeps your model grounded.</p><p>Loss function selection isn’t a footnote. It’s a design decision.</p><p>Are you team MAE or MSE? Or do you reach for something else — Huber loss perhaps? 👇 Drop it in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9084d2e57fc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[None of these mistakes throw loud errors.]]></title>
            <link>https://medium.com/@imsami13062004/none-of-these-mistakes-throw-loud-errors-6616650cb44c?source=rss-c95969eee154------2</link>
            <guid isPermaLink="false">https://medium.com/p/6616650cb44c</guid>
            <dc:creator><![CDATA[Sami]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 11:29:21 GMT</pubDate>
            <atom:updated>2026-04-15T11:29:21.035Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FvgmK9jEjfYM6fw4KLBsGQ.png" /></figure><p>None of these mistakes throw loud errors. Most let your code run fine. The damage shows up later, inside your model, where it is much harder to trace back.</p><ol><li><strong>File path and access errors</strong></li></ol><p>A hardcoded path works on your machine and breaks on every other one. Use relative paths and check file existence before loading.</p><p><strong>2. Inconsistent file formats</strong></p><p>A file named .csv is sometimes actually a TSV or Excel file. Always check the format before assuming the extension is correct.</p><p><strong>3. Encoding errors</strong></p><p>Files saved in Latin-1 or Windows-1252 break when loaded as UTF-8. Always specify encoding= explicitly when calling pd.read_csv().</p><p><strong>4. Delimiter mismatches</strong></p><p>Pandas defaults to comma. Your file uses a pipe or tab. One wrong assumption and every row becomes a single-column mess.</p><p><strong>5. Missing value representation</strong></p><p>Your dataset marks missing values as &quot;N/A&quot;, &quot;null&quot;, &quot;-&quot;, or 99999. Pandas only catches NaN by default.</p><p><strong>6. Incorrect data types</strong></p><p>Pandas guesses column types on load. An ID column of all integers gets cast to int64. One row with a letter and the whole column flips to object.</p><p><strong>07. Handling large datasets</strong></p><p>Loading a 10GB file with pd.read_csv() crashes the kernel. You need chunking. This is covered in depth below.</p><p><strong>08. Header and column name issues</strong></p><p>Files without headers get the first data row treated as column names. Always set header=None and pass names=[] when the file has no header row.</p><p><strong>09. Dirty column names</strong></p><p>Column names with spaces, special characters, or inconsistent casing break downstream code. Clean them on load, not after 200 lines of processing.</p><p><strong>10. Mixed data types in columns</strong></p><p>A numeric column with a few stray string values silently becomes an object dtype. Your scaler will crash on it later with a confusing error.</p><p><strong>11. Inconsistent date formats</strong></p><p>Three vendors send dates as MM/DD/YYYY, DD-MM-YY, and YYYY-MM-DD. Pandas reads them all as strings unless you parse explicitly.</p><p><strong>12. Corrupted or incomplete data</strong></p><p>A file cut off mid-row, a database export that timed out at row 50,000. Always check row counts against an expected count after loading.</p><blockquote><strong>Quick fix for half of these</strong></blockquote><blockquote>When you call pd.read_csv(), always pass encoding=&#39;utf-8&#39;, na_values=[&#39;N/A&#39;, &#39;null&#39;, &#39;-&#39;, &#39;&#39;], and dtype={} with your expected types. These three arguments alone prevent mistakes 03, 05, and 06.</blockquote><h3>Chunking: load big data without crashing your machine</h3><p>Here is the problem. Your dataset is 8GB. Your laptop has 16GB of RAM. You think you are safe. You call pd.read_csv(&#39;big_dataset.csv&#39;) and your system freezes after three minutes.</p><p>Why? Because Pandas loads the entire file into memory at once. Eight gigabytes of CSV becomes roughly 20 to 30GB in memory after Pandas builds its internal structures. Your machine cannot hold that.</p><blockquote>Chunking means you never load the whole file. You load 10,000 rows, work on them, throw them away, and load the next 10,000.</blockquote><p>That is it. No libraries to install. No special hardware. Just one argument added to a function you already know.</p><h3>The core idea, visually</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*-7G1uVyZjdYdptSS9pXo8A.png" /></figure><p>Your RAM never holds more than 10,000 rows at a time. A file with 10 million rows becomes 1,000 loops of 10,000 rows each.</p><h3>The basic pattern</h3><pre>import pandas as pd<br><br>total_rows = 0<br><br>for chunk in pd.read_csv(&#39;big_dataset.csv&#39;, chunksize=10000):<br>    chunk = chunk.dropna()          # remove rows with missing values<br>    total_rows += len(chunk)          # count rows after cleaning<br><br>print(&#39;Total rows processed:&#39;, total_rows)</pre><p>The chunksize=10000 argument tells Pandas to return an iterator. Each time the loop runs, it gives you a DataFrame with 10,000 rows. You work on it. The loop moves on. The old chunk is gone.</p><blockquote>Beginner confusion</blockquote><blockquote>The variable chunk is just a normal Pandas DataFrame. Every Pandas method you already know works on it. dropna(), groupby(), merge(). Nothing changes except the size.</blockquote><h3>What “processing” actually means inside the loop</h3><p>The word “processing” sounds abstract. It is not. Processing means any operation you want to run on the data. Here are six concrete examples.</p><ol><li><strong>Data cleaning</strong></li></ol><p>chunk = chunk.dropna() removes rows with missing values before they reach your model.</p><p>2.<strong> Filtering rows</strong></p><p>chunk = chunk[chunk[&#39;age&#39;] &gt; 18] keeps only the rows you care about. Irrelevant rows never enter your pipeline.</p><p>3.<strong> Feature engineering</strong></p><p>chunk[&#39;total_price&#39;] = chunk[&#39;quantity&#39;] * chunk[&#39;price&#39;] creates new columns on each batch.</p><p>4. <strong>Aggregation</strong></p><p>total_sales += chunk[&#39;sales&#39;].sum() builds a running total across all chunks without loading the full file.</p><p>5.<strong> Encoding</strong></p><p>chunk[&#39;gender&#39;] = chunk[&#39;gender&#39;].map({&#39;M&#39;: 1, &#39;F&#39;: 0}) converts categories to numbers batch by batch.</p><p>6.<strong> Saving to disk</strong></p><p>chunk.to_csv(&#39;cleaned.csv&#39;, mode=&#39;a&#39;, header=False) writes processed rows to a new file without holding everything in memory.</p><h3>A full, working example</h3><p>Here is a realistic chunk pipeline. It cleans the data, engineers a feature, filters rows, and saves the result. All without loading the full file.</p><pre>Python · Full chunk pipeline with memory tracking<br>import pandas as pd<br>import psutil<br>import os<br><br>def check_memory():<br>    process = psutil.Process(os.getpid())<br>    mb = process.memory_info().rss / (1024 * 1024)<br>    print(f&quot;Memory in use: {mb:.1f} MB&quot;)<br><br># Track results across all chunks<br>total_rows = 0<br>first_chunk = True<br><br>for chunk in pd.read_csv(<br>    &#39;big_dataset.csv&#39;,<br>    chunksize=10000,<br>    encoding=&#39;utf-8&#39;,<br>    na_values=[&#39;N/A&#39;, &#39;null&#39;, &#39;-&#39;, &#39;&#39;]<br>):<br>    # Step 1: Clean — remove rows with missing values<br>    chunk = chunk.dropna(subset=[&#39;age&#39;, &#39;quantity&#39;, &#39;price&#39;])<br><br>    # Step 2: Filter — keep only adults<br>    chunk = chunk[chunk[&#39;age&#39;] &gt; 18]<br><br>    # Step 3: Feature engineering — new column<br>    chunk[&#39;total_price&#39;] = chunk[&#39;quantity&#39;] * chunk[&#39;price&#39;]<br><br>    # Step 4: Encode a categorical column<br>    chunk[&#39;gender_num&#39;] = chunk[&#39;gender&#39;].map({&#39;M&#39;: 1, &#39;F&#39;: 0})<br><br>    # Step 5: Save to a new CSV (append mode after first chunk)<br>    chunk.to_csv(<br>        &#39;cleaned_data.csv&#39;,<br>        mode=&#39;a&#39;,<br>        header=first_chunk,  # write header only once<br>        index=False<br>    )<br><br>    total_rows += len(chunk)<br>    first_chunk = False<br><br>    # Optional: watch memory stay flat<br>    check_memory()<br><br>print(f&quot;Done. {total_rows} rows written to cleaned_data.csv&quot;)</pre><blockquote>What to watch</blockquote><blockquote>Run check_memory() every few chunks. You will see the memory number stay almost flat. That is the whole point. A 10GB file processes at roughly 50 to 200MB of RAM.</blockquote><h3>How to pick your chunksize</h3><p>There is no single right number. A chunksize of 10,000 is a solid default. Here is how to think about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*Pf1U6jPxQvyayJXqd9vywg.png" /></figure><h3>What chunking cannot do</h3><p>Chunking is not magic. It has real limits you need to know before you rely on it.</p><p><strong>Sorting across the full dataset is not possible.</strong> You cannot sort 10 million rows when you only have 10,000 in memory at a time. For full-file sorts, load a smaller sample or use a database.</p><p><strong>Joins across two large files are hard.</strong> Joining chunk A from file 1 with the correct rows from file 2 requires careful key-based matching. It is doable, but not with a simple loop.</p><p><strong>Rolling window features need overlap.</strong> If you want a 7-day rolling average, the last 7 rows of chunk N need to be the first 7 rows of chunk N+1. You have to manage that overlap manually.</p><p>For these cases, tools like Dask or PySpark are built for exactly this problem. Chunking with Pandas covers 80% of real-world large file scenarios. When you hit the 20%, those tools are the next step.</p><h3>Before you load any dataset, check these five things</h3><p>Make this a habit. Five minutes here saves hours of debugging later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*p9m3CJwGk9l6-1t0nQiTlw.png" /></figure><h3>The point, in four sentences</h3><p>Data loading is not a formality. It is where your pipeline either starts clean or starts broken. The 12 mistakes above are not edge cases. They appear in almost every real dataset.</p><p>Chunking is the single most useful technique for working with large files in Python. One argument, chunksize=10000, transforms an unloadable file into a manageable loop. You already know every Pandas method that works inside that loop.</p><p>Fix the loader, and the rest of the pipeline gets easier. Ignore it, and no amount of model tuning will save you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6616650cb44c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your model isn’t bad.
Your data is.]]></title>
            <link>https://medium.com/@imsami13062004/your-model-isnt-bad-your-data-is-81c0f24c5133?source=rss-c95969eee154------2</link>
            <guid isPermaLink="false">https://medium.com/p/81c0f24c5133</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ads]]></category>
            <dc:creator><![CDATA[Sami]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 10:36:13 GMT</pubDate>
            <atom:updated>2026-04-14T10:36:13.686Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A no-fluff guide to building ML pipelines that don’t break in production — and engineering features your model actually learns from.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmxoL7SA7bn6VmqZFdz_kg.png" /></figure><p>You spend three days tuning hyperparameters. You try six different architectures. Your validation loss is still garbage. Then someone looks at your data and spots it: a column that leaks the future. A date field that wasn’t normalized. Categorical values with 47 different spellings of “New York.”</p><p>That’s the real story of most failed ML projects. Not wrong algorithms. Bad data, and no system to catch it.</p><p>This guide covers two inseparable things: how to build an ML pipeline that holds together end-to-end, and how to do feature engineering that actually moves your model’s performance. Not theory. Applied, production-minded thinking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*PeB_XmUoFzh7kd7HnzHcHQ.png" /></figure><h3>What exactly is an ML pipeline?</h3><p>A pipeline is a reproducible sequence of steps that takes raw data and produces a trained, deployable model. Every step is explicit. Every transformation is recorded. Nothing happens “in a notebook” that can’t be replayed.</p><p>Think of it like an assembly line. Raw steel goes in one end. A finished car part comes out the other. Each station does one job. Each job is testable in isolation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVBQ8D5cgL5JJ9FYWD51qg.png" /></figure><p>The highlighted step <strong>feature engineering</strong> is where most of the leverage lives. It’s also where most mistakes happen.</p><blockquote>Why this matters?</blockquote><blockquote>A pipeline isn’t just about convenience. It’s about trust. When something breaks in production, you need to know exactly which step produced which output. A pipeline gives you that audit trail. A messy notebook does not.</blockquote><h4>The anatomy of a solid pipeline</h4><p>Every production-grade ML pipeline has six layers. Skimp on any one of them and you’ll feel it later — usually at the worst possible moment.</p><p><strong>Data ingestion</strong> — Pull data from sources. Validate schemas. Log row counts and timestamps. Fail loudly if something’s missing.</p><p><strong>Preprocessing </strong>— Handle nulls, outliers, and encoding. This is rule-based. Deterministic. Always reproducible.</p><p><strong>Feature engineering</strong> — Transform raw columns into signals your model can learn from. This is where craft lives.</p><p><strong>Train/validation split </strong>— Done <em>after</em> feature engineering, not before. Many people get this wrong.</p><p><strong>Model training &amp; tuning </strong>— The part everyone loves. It’s actually the least differentiating step.</p><p><strong>Evaluation &amp; logging</strong> — Metrics, confusion matrices, feature importances. Log everything. Always.</p><h3>Feature engineering: where models get smart</h3><p>Features are the language your model speaks. You’re the translator between raw data and model-ready signals.</p><p>A raw timestamp means nothing to a gradient boosting tree. But hour_of_day, is_weekend, and days_since_last_purchase? Now you&#39;re talking.</p><blockquote>“Give me six hours to chop down a tree and I will spend the first four sharpening the axe.” — Feature engineering is sharpening the axe.</blockquote><h4>The four types of features you’ll work with</h4><p><strong>Numerical</strong></p><p>Age, price, count. The most intuitive. Still needs normalization, outlier treatment, and sometimes log transforms.</p><p><strong>Categorical</strong></p><p>City, product category, user tier. Needs encoding — one-hot, target encoding, or embeddings depending on cardinality.</p><p><strong>Temporal</strong></p><p>Dates and timestamps. Explosive with engineering. Extract cyclic patterns, lags, rolling windows, and trend indicators.</p><p><strong>Interaction</strong></p><p><strong>Interaction</strong></p><h4>Numerical features — don’t just feed them raw</h4><p>Most beginners feed raw numbers straight into the model. That works, sometimes. But you’re leaving signal on the table.</p><pre>import numpy as np<br>from sklearn.preprocessing import StandardScaler, RobustScaler<br><br># Log transform — great for right-skewed distributions (e.g. income, price)<br>df[&#39;log_revenue&#39;] = np.log1p(df[&#39;revenue&#39;])  # log1p handles zeros<br><br># Binning — convert continuous to ordinal signals<br>df[&#39;age_bucket&#39;] = pd.cut(df[&#39;age&#39;], bins=[0,18,35,55,100],<br>                          labels=[&#39;teen&#39;,&#39;young&#39;,&#39;mid&#39;,&#39;senior&#39;])<br><br># Robust scaling — better than StandardScaler when outliers exist<br>scaler = RobustScaler()<br>df[&#39;price_scaled&#39;] = scaler.fit_transform(df[[&#39;price&#39;]])</pre><blockquote><strong>Common mistake</strong></blockquote><blockquote>Fitting your scaler on the full dataset before splitting. This leaks validation statistics into your training process. Always fit_transform on train, transform only on test.</blockquote><h4>Categorical features — cardinality is everything</h4><p>The right encoding depends on how many unique values a column has. Get this wrong and you either blow up your feature space or lose meaningful signal.</p><pre>from sklearn.preprocessing import LabelEncoder<br>import category_encoders as ce<br><br># Low cardinality (&lt; 10 unique values) → One-Hot<br>df = pd.get_dummies(df, columns=[&#39;color&#39;], drop_first=True)<br><br># High cardinality (50+ values) → Target Encoding<br># Encodes category as mean of target — captures signal, avoids explosion<br>encoder = ce.TargetEncoder(cols=[&#39;city&#39;])<br>df[&#39;city_encoded&#39;] = encoder.fit_transform(df[&#39;city&#39;], df[&#39;target&#39;])<br><br># Ordinal (natural order) → Label Encoding with explicit mapping<br>order_map = {&#39;low&#39;: 0, &#39;medium&#39;: 1, &#39;high&#39;: 2}<br>df[&#39;tier_encoded&#39;] = df[&#39;tier&#39;].map(order_map)</pre><h4>Temporal features — your richest source of signal</h4><p>Timestamps are deceptively powerful. A single date column can become a dozen strong features. This is where experienced engineers pull ahead.</p><pre># Extract cyclic components<br>df[&#39;hour&#39;] = df[&#39;timestamp&#39;].dt.hour<br>df[&#39;day_of_week&#39;] = df[&#39;timestamp&#39;].dt.dayofweek<br>df[&#39;is_weekend&#39;] = df[&#39;day_of_week&#39;].isin([5, 6]).astype(int)<br>df[&#39;month&#39;] = df[&#39;timestamp&#39;].dt.month<br>df[&#39;quarter&#39;] = df[&#39;timestamp&#39;].dt.quarter<br><br># Cyclic encoding — hour 23 and hour 0 are adjacent, not opposite<br>df[&#39;hour_sin&#39;] = np.sin(2 * np.pi * df[&#39;hour&#39;] / 24)<br>df[&#39;hour_cos&#39;] = np.cos(2 * np.pi * df[&#39;hour&#39;] / 24)<br><br># Rolling window features (time-series gold)<br>df[&#39;revenue_7d_avg&#39;] = (df.groupby(&#39;user_id&#39;)[&#39;revenue&#39;]<br>                         .transform(lambda x: x.rolling(7).mean()))<br><br># Lag features — what happened N periods ago<br>df[&#39;revenue_lag_1&#39;] = df.groupby(&#39;user_id&#39;)[&#39;revenue&#39;].shift(1)<br>df[&#39;revenue_lag_7&#39;] = df.groupby(&#39;user_id&#39;)[&#39;revenue&#39;].shift(7)</pre><h3>Building it with sklearn: the right way</h3><p>Scikit-learn’s Pipeline and ColumnTransformer are underused. Most people still write sequential transform code in notebooks. That approach breaks the moment you need to deploy.</p><p>A proper sklearn pipeline does three things automatically: it prevents data leakage, it makes deployment trivial, and it lets you tune hyperparameters across the full preprocessing + modeling chain.</p><pre>from sklearn.pipeline import Pipeline<br>from sklearn.compose import ColumnTransformer<br>from sklearn.preprocessing import StandardScaler, OneHotEncoder<br>from sklearn.impute import SimpleImputer<br>from sklearn.ensemble import GradientBoostingClassifier<br><br># Define which columns are which type<br>num_features = [&#39;age&#39;, &#39;revenue&#39;, &#39;session_duration&#39;]<br>cat_features = [&#39;device_type&#39;, &#39;country&#39;]<br><br># Numeric pipeline: impute then scale<br>num_pipeline = Pipeline([<br>    (&#39;imputer&#39;, SimpleImputer(strategy=&#39;median&#39;)),<br>    (&#39;scaler&#39;,  StandardScaler())<br>])<br><br># Categorical pipeline: impute then encode<br>cat_pipeline = Pipeline([<br>    (&#39;imputer&#39;, SimpleImputer(strategy=&#39;most_frequent&#39;)),<br>    (&#39;encoder&#39;, OneHotEncoder(handle_unknown=&#39;ignore&#39;, sparse_output=False))<br>])<br><br># Combine both into a ColumnTransformer<br>preprocessor = ColumnTransformer([<br>    (&#39;num&#39;, num_pipeline, num_features),<br>    (&#39;cat&#39;, cat_pipeline, cat_features)<br>])<br><br># Full pipeline: preprocess → model<br>full_pipeline = Pipeline([<br>    (&#39;preprocessor&#39;, preprocessor),<br>    (&#39;model&#39;, GradientBoostingClassifier(n_estimators=200))<br>])<br><br># Train on train set only — pipeline handles the rest<br>full_pipeline.fit(X_train, y_train)<br>preds = full_pipeline.predict(X_test) </pre><blockquote>Why this beats manual transforms?</blockquote><blockquote>When you call full_pipeline.fit(X_train), the scaler learns only from training data. When you call .predict(X_test), it applies those learned parameters. You can&#39;t accidentally leak test statistics. Ever.</blockquote><h3>Feature selection: less is more</h3><p>More features is not better. Every irrelevant feature adds noise. It hurts interpretability, slows training, and often degrades accuracy. The discipline of removing features is as important as creating them.</p><h4>Three methods that actually work</h4><pre>from sklearn.feature_selection import SelectKBest, mutual_info_classif<br>import lightgbm as lgb<br><br># Method 1: Correlation — drop features correlated with each other<br>corr_matrix = X_train.corr().abs()<br>upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(bool))<br>to_drop = [col for col in upper.columns if any(upper[col] &gt; 0.95)]<br>X_train.drop(columns=to_drop, inplace=True)<br><br># Method 2: Mutual information — measures non-linear dependency on target<br>selector = SelectKBest(mutual_info_classif, k=20)<br>X_selected = selector.fit_transform(X_train, y_train)<br><br># Method 3: Tree-based importance (most reliable in practice)<br>model = lgb.LGBMClassifier().fit(X_train, y_train)<br>importance = pd.Series(model.feature_importances_, index=X_train.columns)<br>top_features = importance.nlargest(20).index.tolist()</pre><p>In practice: start with tree-based importance. It handles non-linear relationships. Then prune highly correlated features from whatever survives.</p><h3>The one mistake that poisons everything: data leakage</h3><p>Data leakage is when information from outside the training boundary seeps into your model. Your model looks incredible in validation. It fails the moment it hits real data.</p><p>Leakage is silent and confident. That’s what makes it deadly.</p><h3>Type of Data Leakages</h3><p><strong>Target leakage</strong></p><p>A feature that’s derived from the target variable. Example: using “days in hospital” to predict “will be hospitalized.”</p><p><strong>Train-test contamination</strong></p><p>Fitting scalers, encoders, or imputers on the full dataset before splitting. The most common mistake.</p><p><strong>Temporal leakage</strong></p><p>Using future data to predict the past. Especially sneaky with lag features and rolling windows.</p><p><strong>Group leakage</strong></p><p>The same user/entity appears in both train and test. Your model memorizes IDs instead of learning patterns.</p><blockquote>RED FLAG</blockquote><blockquote>If your model achieves <strong>suspiciously high accuracy </strong>early — think 98% on a noisy real-world problem — your first instinct should be “where is the leakage?” Not “I’m a genius.”</blockquote><h3>Taking it to production</h3><p>A model that works locally is a demo. A model that works in production is a product. The gap between the two is where most ML projects die.</p><h4>Save your pipeline, not just your model</h4><pre>import joblib<br><br># Save the entire pipeline — preprocessor + model<br>joblib.dump(full_pipeline, &#39;model_pipeline_v1.pkl&#39;)<br><br># Load it anywhere — no manual transform code needed<br>loaded_pipeline = joblib.load(&#39;model_pipeline_v1.pkl&#39;)<br>predictions = loaded_pipeline.predict(new_raw_data)<br><br># The pipeline remembers what it learned at training time.<br># It will apply those exact same transformations to any new input.<br># This is the whole point.</pre><h3>Monitor for drift</h3><p>Data changes. User behavior shifts. Markets move. A model trained six months ago may be predicting based on a world that no longer exists. You need to watch for this.</p><ul><li><strong>Feature drift</strong> — Track the distribution of input features in production. Flag when they diverge from training distributions.</li><li><strong>Label drift </strong>— If your target variable’s distribution shifts, your model’s calibration degrades silently.</li><li><strong>Performance monitoring </strong>— Log predictions and, when you get ground truth, compare to actuals. Set alerts on AUC drop or RMSE increase.</li><li><strong>Retraining triggers </strong>— Define upfront what conditions warrant a retrain. Don’t make it a judgment call each time.</li></ul><h3>The mental model that ties it all together</h3><p>Here’s how to think about this entire stack:</p><blockquote>The pipeline is your discipline. Feature engineering is your craft. Together, they’re what separates an ML project that ships from one that stays in a Jupyter notebook forever.</blockquote><p>Build your pipeline early, even when the data is simple. You’ll thank yourself at 2am when something breaks in prod and you have a clean, logged, reproducible system to debug instead of a 600-line notebook.</p><p>Invest in your features before you invest in your model. A mediocre model with great features will beat a state-of-the-art model with raw, messy inputs. Every time.</p><p>And never, ever trust a suspiciously great validation score. It’s usually lying to you.</p><p><em>This blog covered the core of what you need to build reliable ML systems. Next logical steps: learn MLflow for experiment tracking, explore feature stores for team-scale feature sharing, and dive into time-series cross-validation if your data has temporal structure.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81c0f24c5133" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>