One-hot encoding with an unknown bucket
Problem
Build the vocabulary as the sorted unique values of train_col followed by "<unk>". Return (vocab, rows), where rows one-hot encodes each value of test_col and maps unseen values to the "<unk>" column.
Signature
def one_hot(train_col: list[str], test_col: list[str]) -> tuple[list[str], list[list[int]]]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> one_hot(['b','a','b'], ['a','b']) == (['a', 'b', '<unk>'], [[1, 0, 0], [0, 1, 0]])
True
>>> one_hot(['b','a'], ['z']) == (['a', 'b', '<unk>'], [[0, 0, 1]])
TrueHints
Vocabulary: sorted unique train values followed by <unk>.
Dict lookup with a default — unseen values map to <unk>.
Return (vocab, rows) where rows are one-hot aligned to that vocab.
Reference solution
def one_hot(train_col, test_col):
vocab = sorted(set(train_col)) + ["<unk>"]
idx = {c: i for i, c in enumerate(vocab[:-1])}
rows = []
for c in test_col:
r = [0] * len(vocab)
r[idx.get(c, len(vocab) - 1)] = 1
rows.append(r)
return vocab, rowsWhat a strong solution covers
- Deterministic vocabulary order.
- Dict lookup with a default.
- Discusses rare-category bucketing, hashing for high cardinality, and serving-time consistency.
Common mistakes
- building the vocabulary from test data
- crashing on unseen categories.