Concepts / Preprocessing Data for Machine Learning

Preprocessing Data for Machine Learning

Unsupervised algorithms are often used to understand data in an exploratory setting, not as part of a larger automatic system.

  • Programming

Why Run an Algorithm That Predicts Nothing

Most introductions to machine learning start with a model that makes a prediction and gets scored against a known answer. Unsupervised algorithms work differently. They look at data that has no answer attached and try to find structure in it. That raises a practical question for anyone working with data: if nothing is being predicted, what is the algorithm actually for?

The answer comes in two parts. In the first, the algorithm is a tool for a person who wants to understand a dataset. In the second, the algorithm is a preprocessing step that prepares data for a later supervised stage. This article follows both roles, and then turns to the preprocessing steps that make data usable at all: encoding categories and building new features from existing ones.

Exploratory Use of Unsupervised Algorithms

Unsupervised algorithms are often used to understand data in an exploratory setting. Here a data scientist wants to see better what a dataset contains before deciding what to do with it. The purpose is insight, not a deployed system. The algorithm is a tool for the person looking at the data, helping them notice structure they would otherwise miss.

In this setting the unsupervised algorithm is usually not part of a larger automatic system that runs on its own. Its output goes to a person who reads it, questions it, and decides on the next step. Keeping this in mind prevents a common confusion: an unsupervised result used for understanding is a different kind of thing from an unsupervised step wired into a production pipeline.

Preprocessing as a Pipeline Step

Preprocessing means transforming data before a later stage uses it. In the second application, the later stage is a supervised algorithm, one that learns from labeled examples. Instead of handing the supervised algorithm the raw data, the data first passes through an unsupervised step that learns a new representation of it.

Definition

A representation is a way of describing each data point. The same underlying data can be described in many ways, and some descriptions make the patterns a supervised algorithm needs easier to pick up. The unsupervised step does not need labels to build this new description, which is why it can sit in front of a supervised step at all.

Raw data pointsUnsupervised steplearns new descriptionwithout labelsNew representationnew description of eachpointSupervised algorithmlearns from labeledexamplesKnown answerspasses throughproducesinputsupervises
How does raw data flow through the unsupervised step to produce a new representation, and then into the supervised model? The labels reach the supervised step directly, while the unsupervised step never sees them.

Follow one dataset through both applications. In the exploratory role, a data scientist runs the unsupervised algorithm, looks at the structure it reveals, and forms questions. Nothing downstream consumes the result automatically. In the preprocessing role, the same kind of algorithm runs first, its new representation is passed on, and a supervised algorithm learns from that representation together with the known answers. The data moves through the same first stage in both cases, but the reason for running it and the consumer of its output are completely different.

Tracing a Representation Change

The source describes this idea in general terms and does not name a specific unsupervised method, so the following code is a generated illustration of the mechanical shape of a representation change. Each original point has two measurements. Each point is rewritten as a new pair of values computed from those two measurements. Here the new pair is the sum and the product of the measurements, chosen only to make the transformation visible.

python
Output (expected)
3 3
[(3, 2), (7, 12), (11, 30)]
Notes on the code
  • points stores three data points, each with two measurements, as tuples
  • the list comprehension builds one new pair per original point
  • len shows the number of points is unchanged by the transformation

What a Learned Representation Can Deliver

A new representation can bring two practical benefits to supervised learning. It can sometimes improve the accuracy of the supervised algorithm. It can also sometimes reduce memory and time consumption. Both are possibilities, not promises.

The hedged wording matters. A preprocessing step adds its own work, so the benefit has to outweigh the cost of running it. A learner should treat preprocessing as a hypothesis to test against the supervised result, not as a step that always helps. The only reliable check is to train the supervised algorithm with and without the step and compare the results.

What do you think happens?

If a preprocessing step makes the supervised model faster to train, does that guarantee the model will also be more accurate?

  • Yes, a faster model is always more accurate

  • No, the accuracy effect is not guaranteed and must be tested

Reveal answer
Answer:

No, the accuracy effect is not guaranteed and must be tested

The source states that the benefits of a new representation are not guaranteed, so a preprocessing step should be tested against the supervised result. A speed gain says nothing about accuracy.

Why Models Need Numeric Input

Before a machine learning algorithm can learn anything, the data has to be written in a form the algorithm can work with. A model does not read a spreadsheet the way a person does. It works with numbers arranged in a consistent layout, so the same kind of information must always appear in the same place and in the same form.

Definition

A categorical variable is a feature whose values are categories, such as a color, a city, or a product type, rather than numbers. Machine learning algorithms need data in a consistent numeric form, so categorical variables must be encoded before an algorithm can use them.

Encoding Categories with One-Hot Vectors

One-hot encoding gives each category its own column. The column for the matching category holds a 1, and every other column holds a 0. Because each category gets its own slot, the encoding does not imply a false order between categories. Read the diagram below from left to right: the incoming label is matched against a fixed list of categories, and the position of that match decides which output slot becomes 1.

red0green1blue0
Which position in the vector corresponds to which category, and how does a single category become a row of 0s with one 1? For the input green, the green slot holds 1 and every other slot holds 0.

The list order must stay fixed across the whole dataset. If the order changed between rows, the same color would map to different columns in different rows, and the model would receive contradictory information.

Deriving New Features from Existing Columns

Feature engineering creates derived features from existing data, and expert knowledge can guide which ones to build. Three common forms are binning, polynomial terms, and interactions. Binning splits a numeric column into ranges. A polynomial term adds a column that is a power of an existing column, such as its square. An interaction adds a column that is the product of two existing columns.

x1original columnx1 in rangesbinned columnx2original columnx1 squaredpolynomial columnx1 times x2interaction columnbinningpolynomial terminteractioninteraction
How do original columns combine or transform to produce new derived feature columns? Two original columns each feed one or more new columns, and the interaction draws on both.
Worked example

Building an interaction column by hand

A dataset has two columns, x1 and x2. Build the interaction column and explain what it adds that the originals do not give directly.

  1. 1
    Pick the row

    Take the first row, where x1 is 2 and x2 is 5.

  2. 2
    Multiply the originals

    The interaction value is x1 times x2, which is 2 times 5, giving 10.

  3. 3
    Add the column

    Store 10 in a new column beside the originals. The model now receives x1, x2, and their product.

  4. 4
    Check what is new

    The value 10 is built from information already present. What changes is that a linear model, which weights x1 and x2 separately, now has a direct route to the product.

Result

The interaction column contains no new information, but it reshapes the same information so a linear model can use a pattern that depends on both columns together.

Notice that none of these new columns contain information that was not already in the original inputs. The bins, squares, and products are rearrangements of what was already there. What changes is the shape of the information the model receives.

Matching Features to the Algorithm

The features you use, and how well they match the method you choose, is often the most important factor in whether a machine learning approach works well. For a linear model, much of the effort of capturing nonlinear structure can be placed into the features, which is why binning and polynomial or interaction terms are useful. For random forests and SVMs, the explicit expansion may not be necessary, because these methods may learn complex tasks without it.

Data scientist runsitPipeline runs itPerson reads outputProgram consumesoutputPerson chooses nextstepDownstream stage acts
How do the two uses differ in who runs the algorithm, what its output is used for, and whether a person is in the loop? In the exploratory column a person reads the output, while in the automatic column code consumes it.

Mistakes Beginners Make with Preprocessing

  • Common mistake

    Treating a preprocessing step as guaranteed to help

    What it looks like

    Adding a learned representation and assuming accuracy rises

    Why it fails

    The benefits of a new representation are not guaranteed, and the step adds its own cost.

    Do this instead

    Train the supervised model with and without the step and compare the results.

  • Common mistake

    Encoding categories as plain integers

    What it looks like

    Mapping red to 0, green to 1, and blue to 2 and feeding those numbers directly

    Why it fails

    The numbers imply an order and distances that the categories do not have.

    Do this instead

    Use one-hot encoding so each category has its own column.

  • Common mistake

    Changing the category order between rows

    What it looks like

    Building the vector with a list that is reordered for a second batch of data

    Why it fails

    The same category would land in different columns, giving the model contradictory input.

    Do this instead

    Fix the category list once and reuse it for the whole dataset.

  • Common mistake

    Assuming derived features add new information

    What it looks like

    Expecting an x1 times x2 column to reveal facts absent from x1 and x2

    Why it fails

    Derived columns are rearrangements of existing information, not new data.

    Do this instead

    Think of derived features as changing the shape of the information the model can use.

  • Common mistake

    Reading exploratory output as a production decision

    What it looks like

    Letting a clustering result from an analysis notebook drive an automatic system without review

    Why it fails

    In the exploratory setting the output is meant for a person who decides the next step.

    Do this instead

    Keep exploratory results for human judgment, and treat any automated use as a separate design decision.

Practice Choosing a Preprocessing Step

MEDIUM

A dataset has a column called size with the values small, medium, and large, and a numeric column called price. Describe how you would encode size before training a linear model, and name one derived feature you might test for price and size together.

Hints
  • Ask whether small, medium, and large have a natural numeric distance between them.
  • One-hot encoding gives each size its own column; think about which column a medium row sets to 1.
  • An interaction is the product of two existing columns, so consider a price-size product only if size is numeric.
EASY

Using the categories list from this article, write one_hot for the label blue and predict the printed vector before running the code. Then change the category order to blue, red, green and predict how the output for blue changes.

Hints
  • The 1 appears in the slot whose position matches the label in the category list.
  • Changing the order moves the 1, even though the label itself did not change.

Key Takeaways

  • Unsupervised algorithms are often used in an exploratory setting, where a person reads their output to understand data, and they are not usually part of a larger automatic system.
  • An unsupervised step can act as preprocessing by learning a new representation that a supervised algorithm then uses. This can sometimes improve accuracy or reduce memory and time use, but the benefit is not guaranteed and must be tested.
  • Machine learning algorithms need numeric, consistent input, so categorical variables must be encoded. One-hot encoding gives each category its own column with a 1 in the matching position and 0 elsewhere, using a fixed category order.
  • Binning, polynomial terms, and interactions create derived features from existing columns. They reshape information rather than adding new information, and how much they help depends on the algorithm.

Related concepts

More concepts starting with P