Build a TF-IDF representation from text documents. Convert text to lowercase, split on whitespace, and sort the unique vocabulary alphabetically.
tf(t,d)=∣d∣count(t,d) idf(t)=log(df(t)N) tfidf(t,d)=tf(t,d)idf(t)Here, t is a term, d is a document, ∣d∣ is its token count, N is the number of documents, and df(t) is the number of documents containing t. Return a dictionary with tfidf_matrix, a NumPy array of shape (N,V), and vocabulary, the sorted list of V terms.
Input: documents = ["the cat sat", "the cat ran", "the dog sat"]
Output: {"tfidf_matrix": [[0.135155, 0.0, 0.0, 0.135155, 0.0], [0.135155, 0.0, 0.366204, 0.0, 0.0], [0.0, 0.366204, 0.0, 0.135155, 0.0]], "vocabulary": ["cat", "dog", "ran", "sat", "the"]}
Explanation: The vocabulary fixes the column order, then every document receives one TF-IDF weight per vocabulary term.
Input: documents = ["machine learning is great", "cooking pasta is fun"]
Output: {"tfidf_matrix": [[0.0, 0.0, 0.173287, 0.0, 0.173287, 0.173287, 0.0], [0.173287, 0.173287, 0.0, 0.0, 0.0, 0.0, 0.173287]], "vocabulary": ["cooking", "fun", "great", "is", "learning", "machine", "pasta"]}
Use Counter(tokens) for term counts and Counter.update(set(tokens)) for document frequencies.
Create a token-to-column dictionary with enumerate(vocabulary).
Initialize the output with np.zeros((len(documents), len(vocabulary))).
Sign in to take notes on this problem
Accepts: array
Build a TF-IDF representation from text documents. Convert text to lowercase, split on whitespace, and sort the unique vocabulary alphabetically.
tf(t,d)=∣d∣count(t,d) idf(t)=log(df(t)N) tfidf(t,d)=tf(t,d)idf(t)Here, t is a term, d is a document, ∣d∣ is its token count, N is the number of documents, and df(t) is the number of documents containing t. Return a dictionary with tfidf_matrix, a NumPy array of shape (N,V), and vocabulary, the sorted list of V terms.
Input: documents = ["the cat sat", "the cat ran", "the dog sat"]
Output: {"tfidf_matrix": [[0.135155, 0.0, 0.0, 0.135155, 0.0], [0.135155, 0.0, 0.366204, 0.0, 0.0], [0.0, 0.366204, 0.0, 0.135155, 0.0]], "vocabulary": ["cat", "dog", "ran", "sat", "the"]}
Explanation: The vocabulary fixes the column order, then every document receives one TF-IDF weight per vocabulary term.
Input: documents = ["machine learning is great", "cooking pasta is fun"]
Output: {"tfidf_matrix": [[0.0, 0.0, 0.173287, 0.0, 0.173287, 0.173287, 0.0], [0.173287, 0.173287, 0.0, 0.0, 0.0, 0.0, 0.173287]], "vocabulary": ["cooking", "fun", "great", "is", "learning", "machine", "pasta"]}
Use Counter(tokens) for term counts and Counter.update(set(tokens)) for document frequencies.
Create a token-to-column dictionary with enumerate(vocabulary).
Initialize the output with np.zeros((len(documents), len(vocabulary))).
Sign in to take notes on this problem
Accepts: array