Sub topic 16
Combining collaborative and content signals
This chapter assumes you have read the earlier chapters on item-based collaborative filtering, matrix factorization, and the cold start problem. It also assumes you can read NumPy code and know what cosine similarity is.
Why combine signals
Collaborative filtering (CF) uses only the interaction matrix. It is strong when an item has many ratings, and it has nothing to say about an item with none. A content-based recommender uses item attributes such as genre, text, price, or an embedding. It works on a brand-new item, but it can only recommend things that resemble what the user already liked, so it rarely surprises anyone.
The two fail in different places. CF fails for new items and new users. Content-based methods fail when attributes are poor or when the user wants variety. A hybrid recommender uses each signal where it is reliable.
Common hybrid designs
| Design | How it works | Typical use |
|---|---|---|
| Weighted | Compute both scores and blend them with weights | Simple, easy to tune |
| Switching | Pick one model per request based on a rule | Use content for new items, CF otherwise |
| Cascade | One model produces candidates, another reranks them | Large catalogs |
| Feature augmentation | Feed one model's output as input to the other | Content scores as a feature in a ranker |
| Model-level | Put side features inside one model | Factorization with item or user attributes |
Weighted and switching hybrids need no new training code. They only combine predictions you already have. Model-level hybrids take more work and handle cold start more gracefully.
A weighted hybrid with a confidence weight
A fixed blend such as 0.5 CF and 0.5 content wastes the strength of CF on popular items and trusts it too much on rare ones. A better weight depends on the evidence. If an item has n ratings, set the CF weight to n / (n + m). Here m is a shrinkage constant. At n = 0 the weight is 0, so the item is scored by content alone. As n grows, the weight approaches 1.
The code below builds on the item-based CF from earlier. The matrix has an extra column, item 4, that nobody has rated. Each row of F is a one-hot-style genre vector for an item.
import numpy as np
# Rows are users, columns are items. 0 means "not rated".
# Item 4 is new: nobody has rated it yet.
R = np.array([
[5, 3, 0, 1, 0],
[4, 0, 0, 1, 0],
[1, 1, 0, 5, 0],
[1, 0, 0, 4, 0],
[0, 1, 5, 4, 0],
], dtype=float)
# Item features: [action, romance, scifi]
F = np.array([
[1, 0, 0],
[1, 0, 1],
[0, 1, 1],
[0, 1, 0],
[1, 0, 0],
], dtype=float)
def item_cosine(R):
norms = np.linalg.norm(R, axis=0)
norms[norms == 0] = 1.0
return (R.T @ R) / np.outer(norms, norms)
def cf_scores(R, S, user):
rated = R[user] > 0
sims = S[:, rated]
denom = sims.sum(axis=1)
num = sims @ R[user, rated]
out = np.full(R.shape[1], np.nan)
ok = denom > 0
out[ok] = num[ok] / denom[ok]
return out # NaN means "CF has no opinion"
def content_scores(R, F, user):
rated = R[user] > 0
centered = R[user, rated] - R[user, rated].mean()
profile = centered @ F[rated] # taste vector in feature space
p_norm = np.linalg.norm(profile)
f_norm = np.linalg.norm(F, axis=1)
f_norm[f_norm == 0] = 1.0
if p_norm == 0:
return np.full(R.shape[1], 3.0) # no taste signal: neutral
cos = (F @ profile) / (f_norm * p_norm)
return 3.0 + 2.0 * cos # map [-1, 1] to the 1-5 scale
def hybrid_scores(R, F, user, m=2.0):
S = item_cosine(R)
cf = cf_scores(R, S, user)
ct = content_scores(R, F, user)
n = (R > 0).sum(axis=0)
w = n / (n + m)
cf = np.where(np.isnan(cf), ct, cf) # fall back to content
scores = w * cf + (1 - w) * ct
scores[R[user] > 0] = -np.inf # never re-recommend
return scores
scores = hybrid_scores(R, F, user=0)
for item in np.argsort(scores)[::-1][:2]:
print(item, round(float(scores[item]), 2))User 0 rated the action-leaning items 0 and 1 higher than the romance item 3. Item 4 is an action title with no ratings, so only content can score it. It comes out near 4.4 and ranks first. Item 2 has one rating, so its CF score gets a weight of 1/3 and its score is about 1.9.
Three details make this work:
- The user profile is built from mean-centered ratings. A rating of 1 pushes the profile away from that item's features, which is what a dislike should do.
- CF returns NaN where an item has no co-rated neighbors. The code treats NaN as "no opinion" and not as a score of 0.
- Content scores are mapped onto the rating scale, so both scores are comparable before blending.
Switching and cascade hybrids
A switching hybrid is a rule: if an item has fewer than a set number of ratings, use content only. This is easier to explain and debug than a smooth weight. The cost is a visible jump in behavior at the threshold, and an item just above it can suddenly drop in the ranking.
A cascade suits large catalogs, as covered in the chapter on scale. A cheap method, such as content similarity or approximate nearest neighbor search on embeddings, shortlists a few hundred candidates. A more expensive model, such as a factorization model or a trained ranker, reranks only those candidates. The first stage limits what the second can ever recommend, so measure its recall separately.
Model-level hybrids
Instead of blending outputs, you can give one model both kinds of information. Two common approaches:
- Feature-based item factors. Define an item's latent vector as its learned vector plus a projection of its features:
q_i = q_i_free + W @ f_i. A new item has no learned part, so its vector comes entirely fromW @ f_i. As ratings arrive, the free part starts to carry real signal. - Side features in a ranker. Train a model such as gradient-boosted trees or a neural network on rows of (user features, item features, CF score, label). The CF score is one input among many.
Model-level hybrids train both signals together, so they can learn how much to trust each one. They also need more code, more hyperparameters, and more care with data splitting, because a CF score used as an input must itself be computed without seeing the label it predicts.
Tuning and evaluating a hybrid
Choose m, the blend weights, and any switching threshold on a validation split, never on the test set. Measure results in slices, not only overall:
- Warm items: the hybrid should match or beat plain CF.
- Cold items: items with few or no training ratings. Build this slice by holding out all interactions for a sample of items. This split is harder than a random one, and it is the only one that tests cold start.
- Cold users: do the same for users with only a few interactions.
A hybrid that improves overall precision@k but hurts warm items has usually been tuned toward the cold slice. Watch for that.
Pitfalls
- Leakage through content features. A feature computed from ratings, such as an item's average rating, leaks label information if it includes test interactions. Compute it from training data only.
- Poor attributes. If genre tags are coarse, content scores for many items are identical and the ranking among them is arbitrary. Add a tiebreaker such as popularity.
- Over-specialization. Content-heavy blends narrow what users see. Keep CF weight meaningful for warm items so recommendations can cross genres.
- Extra maintenance. Every added signal is another pipeline that can break silently. Log which component supplied each score, so you can tell during debugging whether a bad recommendation came from CF or from content.
Exercise
In the weighted hybrid, an item has 6 ratings and m = 2. What is its CF weight, and what does the final score become if the item has 0 ratings?
Show answer
The weight is n / (n + m) = 6 / 8 = 0.75, so the score is 0.75 times the CF score plus 0.25 times the content score. With 0 ratings the weight is 0 / (0 + 2) = 0, so the score is the content score alone.
Exercise
You want to show that your hybrid helps with cold start. Why is a random 80/20 split of interactions a poor test, and what split should you use?
Show answer
A random split leaves most test items with plenty of training ratings, so it mostly measures warm-item performance. Instead, hold out all interactions for a sample of items (and optionally users), so the test items have no ratings in training. Then compare plain CF, content-only, and the hybrid on that cold slice.