Sign in to track progress, unlock prep layers, and browse your pipeline.Sign in
Implement TF–IDF with sparse matrices
Implement TF–IDF from Scratch (Python + NumPy/SciPy)
You are given a list of documents (strings). Your task is to build a TF–IDF vectorizer from scratch with the following specified behavior.
Requirements
- Tokenization and Preprocessing:
- Convert all text to lowercase.
- Strip punctuation from tokens.
- Implement a memory-efficient tokenizer (e.g., streaming or generator-based) without using external Natural Language Processing (NLP) libraries.
- Vocabulary and Filtering:
- Support optional
min_dfandmax_dfdocument-frequency filtering. - These parameters can be interpreted as either:
- An integer: representing an absolute number of documents.
- A float in the range (0, 1]: representing a fraction of documents.
- The vocabulary (which forms the columns of the output matrix) must be ordered lexicographically.
- Support optional
- TF–IDF Computation:
- Term Frequency (TF) should be calculated as the raw count of a term within a document.
- Use the smoothed Inverse Document Frequency (IDF) formula:
idf = log((1 + N) / (1 + df)) + 1, whereNis the total number of documents anddfis the document frequency of the term. - The final output must be a SciPy CSR (Compressed Sparse Row) sparse matrix with dimensions
(n_documents, vocab_size).
- Transform Behavior:
- Ignore any out-of-vocabulary (OOV) tokens encountered during the
transformphase. - Support optional L2 normalization per row (document) in the output matrix.
- Ignore any out-of-vocabulary (OOV) tokens encountered during the
- API Surface:
- Implement a class with the following methods:
fit,transform,fit_transform, andinverse_transform(doc_index, k=None). - The
inverse_transformmethod should return the top-k terms for a given document, ordered by their TF–IDF score in descending order. IfkisNone, return all terms for that document, sorted by score.
- Implement a class with the following methods:
- Complexity Analysis:
- Analyze and discuss the time and space complexity for both the
fitandtransformmethods. This analysis should be in terms of the number of documents, total tokens, and vocabulary size.
- Analyze and discuss the time and space complexity for both the
- Unit Test:
- Provide a unit test to verify the correctness of your implementation using a small 3-document toy corpus that includes repeated terms.
Constraints
- Only Python standard library, NumPy, and SciPy are allowed. No other external NLP libraries.
- The implementation must gracefully handle empty documents.
- Ensure deterministic lexicographic column order for reproducibility.
AI interview prep
Core dilemma
Balancing memory efficiency and computational performance for large text corpora while adhering to strict mathematical definitions and API requirements, especially concerning sparse matrix representations.
Mid-level signals3
Senior signals3
Red flags3
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Implement TF–IDF with sparse matrices
Implement TF–IDF from Scratch (Python + NumPy/SciPy)
You are given a list of documents (strings). Your task is to build a TF–IDF vectorizer from scratch with the following specified behavior.
Requirements
- Tokenization and Preprocessing:
- Convert all text to lowercase.
- Strip punctuation from tokens.
- Implement a memory-efficient tokenizer (e.g., streaming or generator-based) without using external Natural Language Processing (NLP) libraries.
- Vocabulary and Filtering:
- Support optional
min_dfandmax_dfdocument-frequency filtering. - These parameters can be interpreted as either:
- An integer: representing an absolute number of documents.
- A float in the range (0, 1]: representing a fraction of documents.
- The vocabulary (which forms the columns of the output matrix) must be ordered lexicographically.
- Support optional
- TF–IDF Computation:
- Term Frequency (TF) should be calculated as the raw count of a term within a document.
- Use the smoothed Inverse Document Frequency (IDF) formula:
idf = log((1 + N) / (1 + df)) + 1, whereNis the total number of documents anddfis the document frequency of the term. - The final output must be a SciPy CSR (Compressed Sparse Row) sparse matrix with dimensions
(n_documents, vocab_size).
- Transform Behavior:
- Ignore any out-of-vocabulary (OOV) tokens encountered during the
transformphase. - Support optional L2 normalization per row (document) in the output matrix.
- Ignore any out-of-vocabulary (OOV) tokens encountered during the
- API Surface:
- Implement a class with the following methods:
fit,transform,fit_transform, andinverse_transform(doc_index, k=None). - The
inverse_transformmethod should return the top-k terms for a given document, ordered by their TF–IDF score in descending order. IfkisNone, return all terms for that document, sorted by score.
- Implement a class with the following methods:
- Complexity Analysis:
- Analyze and discuss the time and space complexity for both the
fitandtransformmethods. This analysis should be in terms of the number of documents, total tokens, and vocabulary size.
- Analyze and discuss the time and space complexity for both the
- Unit Test:
- Provide a unit test to verify the correctness of your implementation using a small 3-document toy corpus that includes repeated terms.
Constraints
- Only Python standard library, NumPy, and SciPy are allowed. No other external NLP libraries.
- The implementation must gracefully handle empty documents.
- Ensure deterministic lexicographic column order for reproducibility.