Concepts / Categorical Variables in Machine Learning

Categorical Variables in Machine Learning

The raw column of typed responses goes in, and a clean categorical column comes out.

  • Programming

A Survey Question Goes Wrong

Imagine you are building a survey and want to know each respondent's favorite color. One design offers a list of options and lets people pick one. That approach keeps the answers tidy, because every response is exactly one of the values you offered. Now change one detail. Instead of a menu, you give people an empty text box. The answers are no longer guaranteed to match anything you planned for, and the data becomes much harder to analyze.

This is the situation this article addresses. A free string is text that a person typed without being constrained to a list. Some free strings can still be mapped onto categories, meaning a person can read each response and decide which category it belongs to. Other free strings have an underlying structure, such as an address or a date, but no fixed list of possible answers. Both situations appear constantly in real datasets, so recognizing them is a practical skill.

Following One Answer Through the Pipeline

Turning free text into categories is a preprocessing task. The raw column of typed responses goes in, and a clean categorical column comes out. The work usually happens in a fixed order. First you gather the raw text and look at which entries appear most often. Then you decide on a set of categories, either by promoting the common entries or by designing categories that serve your purpose. Each response is assigned to a category, and anything that does not fit is placed in a catch-all category.

Raw typed responsesunconstrained text columnCount common entriesfind what people repeatDefine categoriespromote common entries ordesign for purposeAssign each responseone category per responseClean categoricalcolumnfinished variableCatch-all: otheranswers that fit nothinginspectdecidematchno matchoutputoutput
What happens to a raw typed answer as it moves from input to a final category, and where do unmatched answers end up?

Trace a single raw answer through this diagram. The response 'velociraptor cloaka' enters as raw text. It does not match any of the categories you defined, so it skips the assignment to a standard color and lands in other. Every response leaves the pipeline with some category. That guarantee is what makes the finished column usable, even though the raw input was unpredictable.

Why Free Text Resists Analysis

A free string is hard to analyze because the set of possible values is effectively open. A fixed-list answer has a known, small set of values, so counting how many respondents chose each option is direct. A free-text answer can contain misspellings, alternate spellings, extra words, and phrasings nobody anticipated. The same underlying answer can therefore show up under many different strings, and a model or a simple count will treat each string as a separate value unless someone intervenes.

The source's color survey shows the range. Typed answers included plain color names such as black and blue, misspellings, alternate spellings such as gray and grey, and more specific names such as midnight blue. Some answers were far stranger, such as velociraptor cloaka, which is very hard to connect to any color automatically, or at all.

Choosing the Categories

You choose categories in one of two ways. One option is to look at the most common entries and build categories around them. The other is to define categories that capture responses in a way that fits your application, even if no respondent used those exact words. A reasonable result for the color survey might include categories for standard colors, a category called multicolored for answers describing more than one color, such as a striped green and red, and an other category for anything that cannot be assigned to the rest.

The catch-all category is what keeps the scheme complete. Without it, every unusual answer would force you to either invent a new category on the spot or drop the row. With it, the mapping is total: each response, however strange, gets a home. The cost is that other can become a large bucket, so checking how many responses land there is a useful habit when you review a mapping.

Many Spellings, One Category

Read a mapping as a lookup table. Each typed response is a key, and the category assigned to it is the value. Two different strings can land in the same category. A strange response with no reasonable match still gets a home in other. The assignments below are one reasonable choice for illustration; a different application might decide that midnight blue deserves its own category.

greygrayGRAYgrayblackblackstriped green and redmulticoloredvelociraptor cloakaother
Which different raw strings all collapse to the same category label?

Notice that 'grey' and 'GRAY' are different raw strings, yet both map to the single label gray. This many-to-one property is the whole point of the exercise. It turns a column with dozens of spellings into a column with a handful of values that a model or a count can treat consistently.

Tracing the Mapping Function in Python

The following small program shows the mapping idea in code. It uses a dictionary for known standard colors, cleans each response by removing surrounding spaces and lowercasing it, and falls back to the multicolored and other categories when no standard match exists. Its rule for multicolored is deliberately simple. It is a teaching device, not a complete solution for real survey data.

python
Output (expected)
gray
other
Notes on the code
  • The dictionary maps known spellings to a standard label.
  • strip() and lower() normalize each response before any comparison.
  • The ' and ' test catches answers naming more than one color.
  • The final return guarantees every input receives a category.

Stepping Through the Function's Checks

Trace the function on one response at a time. The text 'grey' is cleaned to 'grey', which is found in the dictionary, so the function returns 'gray' and nothing else runs. The text 'velociraptor cloaka' is cleaned to itself. It is not in the dictionary and contains no ' and ', so the function falls through to the final return and produces 'other'. The function never fails on a strange answer, which is exactly the property you want when input is unpredictable.

Receive responseraw stringStrip and lowercasecleaned stringIn standarddictionary?exact match on cleaned textReturn mapped colorfor example grayReturn multicoloredmulti-color answerContains ' and '?more than one colorReturn otherno check matchedyesnoyesno
In what order are the checks run, which branch does each input take, and what happens when no check matches?

What do you think happens?

What does categorize_color return for 'striped green and red', and which check produces it?

Reveal answer
Answer:

multicolored, produced by the ' and ' check after the dictionary lookup fails.

The cleaned text 'striped green and red' is not a key in the dictionary, so the function moves to the second check. It contains ' and ', so the function returns 'multicolored' before reaching the final return.

Structured Strings: Dates and Addresses

Not every manually entered value fits a category. Some values have no fixed list of answers yet still follow an underlying structure. Addresses, names of places or people, dates, telephone numbers, and other identifiers belong to this group. The source calls this structured string data because the text carries a pattern, even though the set of possible values is effectively unlimited. Structured data in this sense is data with a predefined format or organization.

A structured string is a different problem from a categorical one. You cannot list every address, so you cannot map addresses onto categories the way you mapped colors. Instead, the pattern is what you care about. An address is typically a sequence of parts such as a street, a city, a region, and a postal code. The order and separators of those parts are conventions that vary by place, which is one reason the parsing is hard.

Why 03/04/2024 Has Two Meanings

Structure does not make the data easy. Structured string data is often very hard to parse, and the right treatment depends heavily on context and domain. Take a date written as 03/04/2024. The pattern looks like two numbers and a four-digit year, but the first two numbers could be read as a month and a day in one convention, or as a day and a month in another. Under the first reading the date is 4 March 2024. Under the second it is 3 April 2024. The text alone does not settle the question. You need to know where the data came from.

Source contextLikely conventionMeaning of 03/04/2024
A form from a region that writes month firstMonth, then day4 March 2024
A form from a region that writes day firstDay, then month3 April 2024
A dataset with no documented conventionUnknownCannot be settled from the text alone

The same string can carry two dates. The context it came from decides which.

The pattern the eye sees is three groups separated by slashes. The meaning of the first two groups is not fixed by that pattern. This is why the source treats these strings as hard to handle, and why it does not attempt a full method for them. Its scope stops short of a systematic treatment of cases like this one.

Mistakes When Mapping Free Text

  • Common mistake

    Assuming the raw strings are already clean

    What it looks like

    Treating 'grey' and 'gray' as two separate colors in a count

    Why it fails

    Spelling variants split one answer across several values and distort the counts.

    Do this instead

    Normalize and map variants to a shared label before counting.

  • Common mistake

    Leaving out a catch-all category

    What it looks like

    Mapping only the standard colors and dropping every other response

    Why it fails

    Unusual answers disappear from the dataset, and the mapping is no longer complete.

    Do this instead

    Include an other category so every response receives a category.

  • Common mistake

    Treating the multicolored rule as complete

    What it looks like

    Relying on the ' and ' test for every multi-color answer

    Why it fails

    The rule is deliberately simple and will miss many real phrasings.

    Do this instead

    Use the rule for teaching, then review real responses and refine the logic.

  • Common mistake

    Parsing a date without knowing its source

    What it looks like

    Reading 03/04/2024 as 4 March 2024 in every dataset

    Why it fails

    The same string can mean 3 April 2024 under a different convention.

    Do this instead

    Document or confirm the date convention for each data source before parsing.

Practice Tracing the Mapping Function

MEDIUM

Using the categorize_color function from this article, predict the output for each of these inputs before running it: ' BLACK ', 'gray and blue', and 'midnight blue'. For each one, name the check that produces the result.

Hints
  • Start by applying strip() and lower() to each input.
  • Check the dictionary first, then the ' and ' test, then the final return.
  • A cleaned string that is not a dictionary key and has no ' and ' falls through to other.

What do you think happens?

What does categorize_color return for ' BLACK '?

Reveal answer
Answer:

black

strip() removes the surrounding spaces and lower() produces 'black'. That string is a dictionary key, so the dictionary lookup returns 'black'.

Key Takeaways

  • Free-text answers have no fixed list of values, so they are harder to count and model than answers chosen from a menu.
  • Free strings that can be read by a person can be mapped onto a limited set of categories, with an other category catching everything that does not fit.
  • A mapping function normalizes text, checks known spellings, and falls back to catch-all categories, so every input receives a label.
  • Structured strings such as dates and addresses follow a pattern, but their meaning depends on the context and convention of their source, as 03/04/2024 shows.
  • Preprocessing free text is expensive, so the cheapest fix is to avoid manual entry where a fixed set of choices will capture the concept.

Related concepts

More concepts starting with C