Sub topic 2
Why the Matrix Is Sparse and How It Is Stored
This chapter assumes you know basic Python, can read NumPy arrays, and understand logarithms. A document-term matrix has one row per document and one column per vocabulary term. Each cell holds the count of that term in that document.
Why the matrix is sparse
Most documents use only a small share of the vocabulary. Three short sentences built from eight distinct words make a 3 x 8 matrix with 24 cells. Only 14 of those cells are nonzero. Real corpora are far more extreme. Ten thousand documents over 50,000 terms can have over 99 percent zeros.
A sparse matrix stores only the nonzero entries. scikit-learn uses the compressed sparse row (CSR) format, which keeps three arrays: the nonzero values, their column indices, and row pointers.
Term frequency
Term frequency (TF) is the count of a term in one document, often divided by the document length. Raw counts are the simplest form. Sublinear TF replaces the count with 1 + ln(count), so a term that appears 10 times does not score 10 times higher than one that appears once.
Inverse document frequency
Inverse document frequency (IDF) lowers the weight of terms that appear in many documents. With n documents and df documents containing a term, scikit-learn's default smoothed IDF is:
idf = ln((1 + n) / (1 + df)) + 1
The word "the" appears in all three documents, so its IDF is 1.0. The word "chased" appears in one document, so its IDF is about 1.69.
Combining TF and IDF
The TF-IDF weight is the product tf x idf. In the first document, "the" has a raw count of 2, so its TF-IDF value is 2 x 1.0 = 2.0. The word "cat" has a count of 1 and an IDF of about 1.29, so its value is 1.29.
Normalizing document vectors
Long documents produce larger counts than short ones. To compare documents fairly, scikit-learn divides each row by its L2 norm, the square root of the sum of squared values. After this step every row has length 1. For the first document the norm is about 3.44, so "cat" becomes 0.3742 and "the" becomes 0.5812.
CountVectorizer and TfidfVectorizer in scikit-learn
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
counts = CountVectorizer().fit_transform(docs)
print(counts.nnz, counts.shape) # 14 (3, 8)
tfidf = TfidfVectorizer().fit_transform(docs)
print(tfidf[0].toarray().round(4))
# [[0.3742 0. 0. 0. 0.492 0.3742 0.3742 0.5812]]Exercise
In the example above, the number of nonzero entries is 14. How many nonzero entries would a 3 x 8 matrix need if every cell were nonzero, and what fraction of the cells are nonzero in the actual example?
Show answer
24 entries would be nonzero, which is every cell. The actual example has 14 of 24 nonzero cells, or about 58 percent.