Sub topic 3
The user-item matrix and why it is sparse
This chapter assumes you know basic Python, can read NumPy arrays, and understand matrices and averages. Every method later in the tutorial starts from the object built here. That includes neighborhood methods, matrix factorization, and evaluation. If the matrix is wrong, everything after it is wrong too.
What the matrix is
The user-item matrix, written R, has one row per user and one column per item. Cell R[u, i] holds what user u did with item i. That is a rating, a purchase flag, a play count, or whatever your feedback signal is. The previous chapter covered how explicit and implicit feedback differ. Here we only care about the shape of the data.
Most cells have no value, because most users have not interacted with most items. A missing cell does not mean "zero". It means "unknown", and the recommender's job is to predict the unknown cells.
import numpy as np
# Rows are users, columns are items. 0 means "not rated".
R = np.array([
[5, 3, 0, 1],
[4, 0, 0, 1],
[1, 1, 0, 5],
[1, 0, 0, 4],
[0, 1, 5, 4],
], dtype=float)
observed = R > 0
sparsity = 1.0 - observed.sum() / R.size
print(f"{observed.sum()} ratings, sparsity = {sparsity:.2f}")The output is 13 ratings, sparsity = 0.35. Sparsity is the fraction of cells with no observation. Its complement, density, is the fraction that has one.
This toy matrix is unusually full. Real matrices are far emptier, as the next section shows.
Why real matrices are so sparse
Three forces push sparsity toward 99% and beyond.
- Limited attention. A person watches a few hundred films in a lifetime. A catalog may hold hundreds of thousands.
- A long-tailed distribution. A few popular items collect most interactions. Most items collect very few. Item 2 in the example above has exactly one rating.
- Uneven users. A few heavy users produce many rows of data. Most users produce a handful.
The numbers get large quickly. Take 1 million users and 100,000 items, with 100 million recorded interactions:
- The matrix has 10^11 cells.
- Density is 10^8 / 10^11 = 0.001, so sparsity is 99.9%.
- Stored densely as float32, it needs about 400 GB.
- Stored sparsely, it needs about 800 MB (one 4-byte value and one 4-byte column index per interaction).
So you never materialize the dense matrix at scale. You store only the observed entries.
Building the matrix from an event log
Production data arrives as rows of (user_id, item_id, value), not as a grid. You convert it in three steps: deduplicate, map ids to contiguous integers, and build a sparse matrix.
import numpy as np
from scipy.sparse import csr_matrix
events = [
("ana", "dune", 5.0),
("ana", "alien", 3.0),
("ben", "dune", 4.0),
("ben", "heat", 1.0),
("cy", "alien", 2.0),
]
user_ids = {u: i for i, u in enumerate(sorted({e[0] for e in events}))}
item_ids = {m: j for j, m in enumerate(sorted({e[1] for e in events}))}
rows = [user_ids[u] for u, _, _ in events]
cols = [item_ids[m] for _, m, _ in events]
vals = [v for _, _, v in events]
R = csr_matrix((vals, (rows, cols)), shape=(len(user_ids), len(item_ids)))
density = R.nnz / (R.shape[0] * R.shape[1])
print(R.shape, R.nnz, f"{1 - density:.2f}")
print(R.toarray())This prints (3, 3) 5 0.44, followed by the dense view of the matrix. R.nnz is the number of stored entries.
CSR (compressed sparse row) stores each row's column indexes and values contiguously. That makes "give me everything user u touched" fast, which is the lookup user-based methods do constantly. Its mirror, CSC, is better for column access. Item-based methods often keep a CSC copy.
The zero problem
The first example stores "not rated" as 0. That works only while 0 can never be a real value. It breaks in three common cases:
- A rating scale that includes 0, such as 0 to 5 stars.
- Mean-centering. Subtracting a user's mean turns observed ratings into zeros and negatives, and those must stay distinct from missing cells.
- Implicit data, where a count of 0 can be a real observation, such as "viewed, but played for 0 seconds".
Always keep the observation mask separate from the values. In a sparse matrix the mask is simply the set of stored entries. In a dense array, compute it explicitly and use it in every statistic.
import numpy as np
R = np.array([
[5, 3, 0, 1],
[4, 0, 0, 1],
[1, 1, 0, 5],
[1, 0, 0, 4],
[0, 1, 5, 4],
], dtype=float)
mask = R > 0
user_means = R.sum(axis=1) / mask.sum(axis=1)
print(user_means.round(2))Dividing by mask.sum(axis=1) averages only the observed ratings. Using R.mean(axis=1) would divide by 4 for every user. It would drag the means down for users with gaps, so user 1 would get 1.25 instead of 1.67. The output here is [3. 2.5 2.33 2.5 3.33].
What sparsity does to the algorithms
Sparsity is not only a storage concern. It changes what each method can and cannot learn.
| Effect | Where it shows up |
|---|---|
| Few co-rated items between two users | Similarity is computed from tiny overlaps and is noisy. Two users who share one item can look identical. |
| Items with one or two ratings | Item-item similarity is unreliable. The item may have no usable neighbors. |
| Users with no history | No row to compare. This is the cold start case covered later. |
| Low coverage | Neighborhood methods may be unable to predict many user-item pairs at all. |
| Few observed cells per parameter | Matrix factorization overfits unless you regularize. |
Cosine similarity over missing values shows the first problem concretely. Treating missing as 0 means two users with no shared items have similarity exactly 0. A pair that shares a single item and rated it identically gets similarity near 1 on that item alone. Neither number carries much evidence. Later chapters address this with shrinkage, minimum-overlap thresholds, and regularization.
Missing is not random
The unobserved cells are not a random sample of the full matrix. People choose what to rate, and the choice carries information.
- Users tend to rate items they expect to like, so observed ratings skew high.
- Items shown more often in the interface get more interactions, regardless of quality.
- In implicit data, absence can mean "never saw it" rather than "did not like it".
This is why evaluation and training can both mislead. A model trained only on observed cells learns the preferences of what users chose to interact with, not of what they would like if shown everything. The chapters on data splitting and on popularity bias return to this.
Quick checks before you model
Run these on any new interaction table:
- Count users, items, and interactions, and compute density.
- Look at the distribution of interactions per user and per item. Report the median, not just the mean, because the long tail pulls the mean up.
- Count users and items below a minimum threshold, such as fewer than 5 interactions.
- Confirm no duplicate
(user, item)pairs remain. - Confirm your missing-value convention cannot collide with a real value.
Exercise
A dataset has 1,000 users, 500 items, and 20,000 observed ratings. What are its density, its sparsity, and the average number of ratings per user? Then name one reason a dense float64 copy of a matrix 1,000 times larger in each dimension would be impractical, and say what you would use instead.
Show answer
There are 1,000 x 500 = 500,000 cells, so density = 20,000 / 500,000 = 0.04 and sparsity = 0.96. The average is 20,000 / 1,000 = 20 ratings per user. Scaling each dimension by 1,000 gives 10^12 cells. At 8 bytes each that is 8 TB, far more than memory holds, while the observed entries stay a small fraction of that. Use a sparse format such as CSR, which stores only the observed entries and their indexes.