TF-IDF Vectoriser

medium
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 16. Everything before it counts as cleared.

TF-IDF turns documents into vectors where common words count for little and distinctive words count for a lot. It's still a strong baseline for search and text classification.

Implement a class TfidfVectorizer with:

  • fit(docs): tokenise by lowercasing and splitting on whitespace. Build vocabulary_, a dict from word to column index with words sorted alphabetically, and idf_ with the smoothed IDF: idf(t)=ln⁡1+N1+df(t)+1\text{idf}(t) = \ln\frac{1 + N}{1 + \text{df}(t)} + 1. Return self.
  • transform(docs): a NumPy array of shape (len(docs), vocab_size). Each entry is the raw count of the term in the document times its IDF, and each row is then L2-normalised. Rows with no known words stay all zeros. Unknown words are ignored.
  • fit_transform(docs).

(These are scikit-learn's default settings.)

#nlp#features#search2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
TF-IDF Vectoriser · TechGradify