One-hot encode with an 'other' column for rare and unseen categories

Why it matters Click logs, product ids and city names all have long tails, and an 'other' bucket keeps the feature matrix small while still handling new values at serving time.

High-cardinality columns blow up one-hot matrices, so rare categories are usually folded into a single 'other' column.

Write one_hot_rare(train, test, min_count). train and test are lists of strings. Keep the train categories that appear at least min_count times, sorted. Return (kept, M) where kept is that sorted list and M is an int array of shape (len(test), len(kept) + 1). Row r has a single 1: in the column of its category if kept, otherwise in the last 'other' column (this covers both rare train categories and categories never seen in train).

Signaturedef one_hot_rare(train, test, min_count)

Example

train ["a", "b", "a", "c", "a", "b"], test ["a", "c", "z", "b"], min_count 2 gives kept ["a", "b"] and M [[1, 0, 0], [0, 0, 1], [0, 0, 1], [0, 1, 0]].

Understand the idea

One-hot encoding turns a category into a row of zeros with a single 1, one column per category. With thousands of rare categories the matrix becomes huge and the rare columns are mostly noise, so we keep only frequent categories and send the rest to one shared 'other' column, like a school grouping tiny clubs into one 'misc' club.

Worked example: train has a three times, b two times, c once. With min_count 2 we keep a and b, so the columns are a, b, other. Test value a is [1, 0, 0], c is rare so [0, 0, 1], z was never seen so also [0, 0, 1], and b is [0, 1, 0].

Rule: column(v) = index of v in sorted frequent categories, else K, where K is the number of kept categories.

This is the same idea as an infrequent-category option in common encoders, and recommendation and ads pipelines use it for ids with long tails.

Shapes and data flow

test (m,) -> M (m, K + 1) with exactly one 1 per row
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleone_hot_rare(['a', 'b', 'a', 'c', 'a', 'b'], ['a', 'c', 'z', 'b'], 2)
  • Sample 2: all rareone_hot_rare(['x', 'y'], ['y', 'q'], 3)
  • Test 3: min count 1one_hot_rare(['m', 'k', 'm'], ['k', 'm', 'new'], 1)
  • Test 4: citiesone_hot_rare(['blr', 'del', 'blr', 'hyd', 'del', 'blr', 'goa'], ['goa', 'blr', 'hyd', 'mum', 'del'], 2)