Implement a TF-IDF vectorizer from scratch with smooth IDF and L2 normalization
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `TfidfVectorizer` with `fit(docs)`, `transform(docs)` and `fit_transform(docs)`. Tokenize by lowercasing and splitting on whitespace (`str(doc).lower().split()`). Return a `pd.DataFrame` of L2-normalized TF-IDF rows.
The class must meet these requirements:
- `fit` sets `vocabulary_` (alphabetically sorted list of tokens) and `idf_` (aligned array: `ln((1 + n) / (1 + df)) + 1`), and returns `self`.
- TF is the raw token count. Each row is `tf * idf_`, then L2-normalized. All-zero rows stay zero (no `NaN`).
- Tokens not in `vocabulary_` are ignored. `transform` never changes `idf_`.
- Output: `float64` columns named by `vocabulary_`, with a `RangeIndex`. Input lists are not mutated.
- Calling `transform` before `fit` raises `RuntimeError`.
Example:
```python
vec = TfidfVectorizer().fit(["cat dog", "cat fish"])
vec.vocabulary_ # ['cat', 'dog', 'fish']
vec.idf_ # [1.0, 1.4055, 1.4055]
vec.transform(["dog dog fish kiwi"])
# cat dog fish
# 0 0.0 0.8944 0.4472 # 'kiwi' is OOV and ignored
```
```hint Document frequency
`df` counts documents, not occurrences. Check what your counting loop does with a document that repeats a token.
```
```hint Normalization
Think about a document whose tokens are all out of vocabulary, or an empty string, before you divide each row by its norm.
```
### What a Strong Answer Covers
- How `fit` computes document frequencies and builds the sorted vocabulary with an aligned `idf_` array.
- How `transform` maps tokens to columns against the frozen vocabulary and treats out-of-vocabulary tokens.
- The L2 normalization step and what happens to a row with no known tokens.
- Output and input handling: column names, dtype, index, no mutation of the input, and the error when unfitted.
- Time and space complexity, and where the dense matrix becomes the bottleneck.
### Follow-up Questions
- How would you scale this to a large corpus and vocabulary?
- How would you add `min_df` and `max_df` vocabulary pruning?
- Why use smooth IDF, and what does the trailing `+1` term do?
Overview: Implement a TF-IDF vectorizer in Python with fit, transform and fit_transform, using smooth IDF, raw term counts and L2-normalized rows returned as a DataFrame. It tests document frequency counting, out-of-vocabulary tokens, zero-norm rows, avoiding leakage between fit and transform, and complexity on large vocabularies.