Implement the hashing trick with signed buckets for tokens and DataFrame columns
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `hash_token`, `hash_tokens` and a `HashingEncoder` class that map tokens or categorical values into a fixed vector of `n_buckets` buckets. Each token adds a signed `±1.0` to its bucket so that collisions partially cancel.
The functions and the class must behave as follows.
- `hash_token(token, n_buckets)` hashes `str(token).encode("utf-8")`. The bucket is the first 8 bytes of the `md5` digest, read as a little-endian integer, modulo `n_buckets`. The sign is `1.0` when the first 8 bytes of the `sha1` digest, read as a little-endian integer, are even, and `-1.0` otherwise. It returns `(bucket, sign)`.
- `hash_tokens(docs, n_buckets, alternate_sign=True)` takes a list of token lists and returns a `float64` array of shape `(n_docs, n_buckets)`. Every token occurrence adds its sign to its bucket, or `+1.0` when `alternate_sign=False`. `None` and `NaN` tokens are skipped.
- `HashingEncoder(n_buckets=16, alternate_sign=True)` encodes the columns of a pandas DataFrame. `fit(X)` raises `TypeError` when `X` is not a DataFrame and stores the column names in `feature_names_in_`. Calling `transform` before `fit` raises `RuntimeError`.
- `transform(X)` hashes the key `f"{col}={value}"` for the fitted columns only. Missing values are skipped, and values that never appeared during fit are hashed like any other value. It returns a DataFrame with the index of `X` and columns `hash_0` through `hash_{n-1}`, and it never mutates the input.
- When `n_buckets` is not a positive integer (booleans are rejected), raise `ValueError`. For the encoder, this check happens in `fit`.
```hint Booleans are integers
In Python, `isinstance(True, int)` is `True`. Order your type checks with that in mind.
```
```hint Positions versus labels
The DataFrame index can hold any labels, including duplicates. Think about how you fill the output rows so they always line up with the input rows.
```
### What a Strong Answer Covers
- Stable digest-based hashing exactly as specified, and why Python's built-in `hash` would break consistency between training and serving
- Separate bucket and sign hashes, with `alternate_sign` switching between signed and unsigned counts
- Missing-value detection that skips `None`, `NaN` and similar scalars without failing on other token types, plus column-qualified keys
- Validation of `n_buckets` (including the boolean case), the fitted state and the input type, with the exception classes the spec names
- An output built by row position with the input's index and `hash_j` column names, the input left untouched, and the time and memory cost
### Follow-up Questions
- Why does the sign hash reduce collision bias?
- How would you choose `n_buckets`?
- How would you make this scale to millions of rows?
Overview: Implement the hashing trick with signed buckets for token lists and categorical DataFrame columns, using stable md5 and sha1 digests to pick each bucket and sign. It tests careful spec following, missing-value handling, fit and transform state checks, and the reasoning behind signed feature hashing.