Skip to main content

10 - Recommendation Systems: Collaborative vs Content-Based

Build collaborative filtering that handles missing ratings, a TF-IDF content-based model and matrix factorization, then score lists with precision@K and NDCG.

What do you think about this article?

At a Glance

Build collaborative filtering that handles missing ratings, a TF-IDF content-based model and matrix factorization, then score lists with precision@K and NDCG.

Recommending is predicting a hole in a table

A recommender system answers a simple question: given that this user liked these things, which other will they like? The starting data is a table with users on the rows, products on the columns and a rating (or an interaction) in the cells. Almost all the cells are empty, because nobody has seen, read or bought more than a small fraction of the catalog, and the job consists of predicting the most promising empty cells. There are three families of solutions. Collaborative filtering uses the behavior of others: if people with your tastes loved a film, you will probably like it too. Content-based filtering uses the characteristics of the products: you like sci-fi films, so I suggest more sci-fi. Hybrid approaches combine the two strategies. In this article you build all the parts with numbers you can check, including the evaluation, which for recommendations is made of metrics different from those of classification. If you do not know distances yet, you need the article on K-Nearest Neighbors, and for evaluation the one on metrics.

User-based collaborative filtering, with missing data handled well

The idea is to measure how much two users resemble each other looking only at the films both have rated, and to predict the missing rating with the weighted mean of the ratings of the most similar users. Two details decide the quality. The first: a missing rating is not a zero, and writing it as zero means saying the user hated that film. The second: users have different scales, some always give 4-5 and some 2-3, so you compare the deviations from their own mean and not the raw ratings. The Pearson correlation on the films in common does exactly this. In the listing the matrix has six users and six films, with two groups of tastes (sci-fi and romance), and np.nan marks the missing data. The prediction for user 0 starts from their mean and adds the deviations, weighted by similarity, of the other users on the film to predict.

Python - Collaborative filtering with Pearson correlation on the films in common
import numpy as np

film = ["Matrix", "Inception", "Interstellar", "Notebook", "Titanic", "Emma"]
# Rows: users. nan = not rated (NOT zero: zero would be a very low rating)
R = np.array([
    [5, 4, np.nan, 1, 2, np.nan],      # user 0: loves sci-fi, not romance
    [5, 5, 4, 1, np.nan, 2],
    [4, np.nan, 5, 2, 1, 1],
    [1, 2, 1, 5, 5, 4],                # users 3 and 4 love romance
    [2, 1, np.nan, 4, 5, 5],
    [np.nan, 3, 3, 3, 4, np.nan],
])
utente = 0

def pearson(a, b):
    comuni = ~np.isnan(a) & ~np.isnan(b)                 # only the films rated by both
    if comuni.sum() < 2:
        return 0.0
    x, y = a[comuni] - np.nanmean(a), b[comuni] - np.nanmean(b)
    d = np.sqrt((x ** 2).sum() * (y ** 2).sum())
    return float((x * y).sum() / d) if d > 0 else 0.0

def predici(R, u, i, k=2):
    candidati = [v for v in range(len(R)) if v != u and not np.isnan(R[v, i])]
    sim = np.array([pearson(R[u], R[v]) for v in candidati])
    scelti = np.argsort(-np.abs(sim))[:k]                 # the k most similar (in absolute value)
    scarti = np.array([R[candidati[j], i] - np.nanmean(R[candidati[j]]) for j in scelti])
    peso = np.abs(sim[scelti]).sum()
    return np.nanmean(R[u]) + (sim[scelti] * scarti).sum() / peso if peso > 0 else np.nanmean(R[u])

print("films not seen by user 0 and predicted rating (mean of their ratings: %.2f):" % np.nanmean(R[utente]))
for i in np.where(np.isnan(R[utente]))[0]:
    print(f"  {film[i]:13s} {predici(R, utente, i):.2f}")
print("Pearson similarity of user 0 with the others:", [round(pearson(R[0], R[v]), 2) for v in range(1, 6)])

# Output:
# films not seen by user 0 and predicted rating (mean of their ratings: 3.00):
#   Interstellar  4.30
#   Emma          1.80
# Pearson similarity of user 0 with the others: [0.97, 0.85, -0.96, -0.78, -0.25]

User 0 has a mean of 3.00. The similarities say that their tastes are almost the same as those of users 1 (0.97) and 2 (0.85) and opposite to those of users 3 (-0.96) and 4 (-0.78), who love romantic films. For Interstellar the model predicts 4.30, because the similar users rated it well, for Emma it predicts 1.80, because the similar ones rated it badly. In the code the line np.argsort(-np.abs(sim)) chooses the neighbors by absolute value: a user with a strongly negative correlation is as informative as a positive one, because their deviation is multiplied by a negative similarity and therefore inverted. With a table as small as this, the prediction relies on few ratings, and that is why real systems use thousands of users and check how many films in common are needed before trusting a similarity (here 2 are enough, so as not to discard everything).

Why zeros are not used in place of missing data

Many examples online fill the missing ratings with zero and apply the cosine similarity (the cosine of the angle between the two rating vectors). The listing repeats the same matrix with zeros and shows what goes wrong. The cosine compares direction and not level: two users with proportional ratings come out identical even if one loves everything and the other hates everything.

Python - What cosine similarity does with zeros
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

# Same matrix, but with 0 in place of the missing data (the most common mistake)
R0 = np.array([
    [5, 4, 0, 1, 2, 0],
    [5, 5, 4, 1, 0, 2],
    [4, 0, 5, 2, 1, 1],
    [1, 2, 1, 5, 5, 4],
    [2, 1, 0, 4, 5, 5],
    [0, 3, 3, 3, 4, 0],
])
print("cosine of user 0 with the others, zeros in place of the missing:", cosine_similarity(R0)[0, 1:].round(2))
print("user 5 (ratings 3,3,3,4, and two missing): cosine with user 0 =", round(float(cosine_similarity(R0)[0, 5]), 2))
# A user who gave 5 to everything, but only to two films, and one who gave 1 to the same two
A = np.array([[5, 5, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0]])
print("cosine between whoever gave 5 and whoever gave 1 to the same films:", round(float(cosine_similarity(A)[0, 1]), 2))

# Output:
# cosine of user 0 with the others, zeros in place of the missing: [0.8  0.52 0.49 0.49 0.52]
# user 5 (ratings 3,3,3,4, and two missing): cosine with user 0 = 0.52
# cosine between whoever gave 5 and whoever gave 1 to the same films: 1.0

With zeros, user 0 gets a cosine of 0.52 with user 2, 0.49 with the two users 3 and 4 and 0.52 with user 5. User 2 has tastes similar to theirs (Pearson 0.85), while users 3 and 4 have opposite ones (-0.96 and -0.78), but the cosine does not tell them apart: the empty cells, treated as zero ratings, enter the calculation and make two users look similar or different even for the films that one has seen and the other has not. The last line is the simplest demonstration of the problem: whoever gave 5 to two films and whoever gave 1 to the same two come out identical, with cosine 1.00, because the two vectors have the same direction. The cosine remains excellent for count data (words in a text, purchases) where zero really means "no interaction", as in the TF-IDF below. For explicitly missing ratings, resort to Pearson or to mean-centered ratings.

Item-based CF is the mirror of the previous one: instead of looking for similar users it looks for films similar to those the user has already rated well, on the columns instead of the rows. It is the approach described by Sarwar and colleagues (GroupLens, 2001) in the paper listed in the sources; in practice the similarities between products can be precomputed, but I did not verify in the text of the paper the reasons the authors give for the choice, so I do not report them.

Content-based: similarity from descriptions

Content-based does not need the other users: it describes each product with a vector and recommends those close to the products you already loved. Here each film is a short description of keywords, turned by TfidfVectorizer into a vector where rare words weigh more than common ones (TF-IDF: term frequency, weighted by the inverse of how many documents contain it). The user profile is the mean similarity with the films they liked, and the last step zeroes those already seen.

Python - Content-based recommendations with TF-IDF
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

film = {
    "Matrix": "sci-fi action cyberpunk hacker virtual reality",
    "Inception": "sci-fi action dreams psychological thriller",
    "Notebook": "romance drama love story emotional",
    "Titanic": "romance drama historical ship love",
    "Interstellar": "sci-fi space exploration time gravity",
    "Blade Runner": "sci-fi cyberpunk android dystopia",
    "Pride and Prejudice": "romance historical drama society",
    "Dark Knight": "action superhero crime thriller",
}
nomi = list(film)
tfidf = TfidfVectorizer().fit_transform(film.values())
sim = cosine_similarity(tfidf)

piaciuti = ["Matrix", "Interstellar"]
idx = [nomi.index(f) for f in piaciuti]
profilo = sim[idx].mean(axis=0)                  # mean similarity with the liked films
profilo[idx] = -1                                # do not recommend again what has been seen
for i in np.argsort(-profilo)[:3]:
    print(f"{nomi[i]:22s} score {profilo[i]:.3f}")
print("Titanic, which has no words in common:", round(float(profilo[nomi.index('Titanic')]), 3))

# Output:
# Blade Runner           score 0.277
# Inception              score 0.239
# Dark Knight            score 0.065
# Titanic, which has no words in common: 0.0

To whoever loved Matrix and Interstellar the system suggests Blade Runner (0.277, words in common with Matrix: sci-fi, cyberpunk) and Inception (0.239). Then comes Dark Knight, 0.065, which shares only action and thriller with one of the two. The last line shows the structural limit: Titanic has no word in common with the loved films, so it is worth exactly zero. The system will never discover that whoever loves science fiction also appreciates a historical drama, unlike collaborative filtering, which can catch these links because it looks at behaviors. This is the "filter bubble" of content-based. On the other hand it works for a film just released, with no ratings, as long as its description is known.

Matrix factorization: the hidden tastes

Matrix factorization assumes that tastes are explained by a few latent factors, for example how "action" a film is and how "romantic", and that each user has a sensitivity toward each factor. Each user u is associated with a vector pu, each film i with a vector qi, and the predicted rating is the global mean plus the dot product between the two. The vectors are learned by minimizing the error on the observed ratings only, with a penalty on the weights; Koren, Bell and Volinsky, in the paper that tells the lesson of the Netflix Prize, explain why: the classical SVD is not defined if the matrix has missing data, filling them in (imputation) is expensive and can distort the data, and fitting the few known ratings without regularization leads to overfitting.

The listing generates a matrix of 100 users and 40 films with three true hidden factors and noise, reveals only 25% of the ratings and sets aside a fifth of the revealed ones for evaluation. It learns the factors with stochastic gradient descent, one rating at a time, and evaluates the root mean squared error (RMSE) on those set aside. The comparison line is the baseline: predicting the global mean for everyone.

Python - Matrix factorization with stochastic gradient descent
import numpy as np

rng = np.random.default_rng(0)
n_utenti, n_film, k_vero = 100, 40, 3
U = rng.normal(0, 1, (n_utenti, k_vero))
V = rng.normal(0, 1, (n_film, k_vero))
vero = np.clip(3.5 + U @ V.T * 0.5 + rng.normal(0, 0.3, (n_utenti, n_film)), 1, 5)    # ratings from 1 to 5

visibili = rng.random((n_utenti, n_film)) < 0.25          # only 25% of the ratings are observed
coppie = np.argwhere(visibili)
rng.shuffle(coppie)
test, train = coppie[: len(coppie) // 5], coppie[len(coppie) // 5 :]
print(f"observed ratings: {len(coppie)} out of {n_utenti * n_film}, of which {len(train)} for learning and {len(test)} for evaluation")

def rmse(P, idx):
    return float(np.sqrt(np.mean([(vero[u, i] - P(u, i)) ** 2 for u, i in idx])))

media_globale = np.mean([vero[u, i] for u, i in train])
print(f"baseline, global mean:          RMSE {rmse(lambda u, i: media_globale, test):.3f}")

def fattorizza(k, reg, epoche=60, lr=0.01):
    r = np.random.default_rng(1)
    P, Q = r.normal(0, 0.1, (n_utenti, k)), r.normal(0, 0.1, (n_film, k))
    for _ in range(epoche):
        for u, i in train[r.permutation(len(train))]:
            e = vero[u, i] - media_globale - P[u] @ Q[i]
            P[u], Q[i] = P[u] + lr * (e * Q[i] - reg * P[u]), Q[i] + lr * (e * P[u] - reg * Q[i])
    return lambda u, i: media_globale + P[u] @ Q[i]

for k, reg in ((3, 0.0), (20, 0.0), (20, 0.05), (20, 0.5)):
    f = fattorizza(k, reg)
    print(f"k={k:2d}, regularization {reg:4}: RMSE train {rmse(f, train):.3f}  RMSE test {rmse(f, test):.3f}")

# Output:
# observed ratings: 1031 out of 4000, of which 825 for learning and 206 for evaluation
# baseline, global mean:          RMSE 0.843
# k= 3, regularization  0.0: RMSE train 0.429  RMSE test 0.622
# k=20, regularization  0.0: RMSE train 0.238  RMSE test 0.650
# k=20, regularization 0.05: RMSE train 0.327  RMSE test 0.647
# k=20, regularization  0.5: RMSE train 0.818  RMSE test 0.835

The baseline is off by 0.843 stars on average. With three factors, the right number because I chose it when generating the data, the test error falls to 0.622: the latent structure is there and the model finds it. With twenty factors and no regularization the training error collapses to 0.238 but on the test set it rises to 0.650: it has memorized the known ratings, exactly the phenomenon described in article 8. Here light regularization (0.05) does not change the test much (0.647), and one that is too strong (0.5) squashes the factors to zero and brings the model back to the baseline (0.835 against 0.843). The honest lesson is that the number of factors and the regularization are chosen with a validation, and that I did not find a configuration that clearly beats the one with the right rank; in real data the true rank is not known. The loop is slow (pure Python, 825 ratings for 60 epochs) but shows the mechanism: specialized libraries (Surprise, implicit) do the same with compiled code.

Cold start: when there is no data yet

A new user has no ratings, and neither does a new product: collaborative filtering and factorization have nothing to start from. Koren and colleagues discuss it as a problem that systems must face, and the countermeasures are common sense. For a new product you use content-based, because the description is enough. For a new user you ask for a few preferences at signup, start from the most popular products, and switch to collaborative filtering as interactions arrive. A hybrid system is exactly this: content-based covers what collaborative cannot yet cover.

Evaluating a list, not a rating

Predicting a rating well (RMSE, MAE) is not enough: the user cares that the first results of the list are the right ones. So ranking metrics are evaluated. Precision@K is the share of relevant items among the first K. It does not look at the order within the K, whereas NDCG@K does: each relevant item counts less if it appears lower (its gain is divided by the logarithm of the position), and the total is normalized against the ideal list, so it is 1 when all the relevant ones are at the top. The listing computes both metrics by hand on a list of ten recommendations, compares them with scikit-learn's ndcg_score and then moves the same relevant items to the top.

Python - Precision@K and NDCG@K by hand, and with scikit-learn
import numpy as np
from sklearn.metrics import ndcg_score

# Recommended list, in score order: 1 = the user found it relevant, 0 = no
raccomandati = np.array([0, 1, 0, 1, 1, 0, 0, 0, 0, 0])
K = 5
precision_k = raccomandati[:K].sum() / K
print(f"precision@{K}: {precision_k:.2f}")

def dcg(rilevanze, k):
    return sum(r / np.log2(pos + 2) for pos, r in enumerate(rilevanze[:k]))   # position 0 -> divisor log2(2) = 1

ideale = np.sort(raccomandati)[::-1]
ndcg = dcg(raccomandati, K) / dcg(ideale, K)
print(f"NDCG@{K} by hand: {ndcg:.3f}")
punteggi = np.linspace(1, 0.1, 10)                # the scores that produced that order
print(f"NDCG@{K} sklearn: {ndcg_score([raccomandati], [punteggi], k=K):.3f}")

migliore = np.array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0])      # same three relevant ones, but at the top
print(f"same precision@{K}? {migliore[:K].sum() / K:.2f}   NDCG@{K}: {dcg(migliore, K) / dcg(ideale, K):.3f}")

# Output:
# precision@5: 0.60
# NDCG@5 by hand: 0.680
# NDCG@5 sklearn: 0.680
# same precision@5? 0.60   NDCG@5: 1.000

In the list the relevant items are in second, fourth and fifth position: precision@5 is 3/5 = 0.60. The NDCG@5 by hand and the scikit-learn one coincide to three decimals, 0.680. The last line is the reason why NDCG exists: if the same three relevant items are at the top of the list the precision@5 stays 0.60, identical, but the NDCG@5 rises to 1.000. Precision does not see that the system ordered badly; NDCG does. To evaluate a system honestly you set aside recent interactions of each user, have the system recommend without having seen them and measure how many reappear at the top, a bit like the baseline of this series: always compare with the list of the most popular items.

What you can do now

You can build a collaborative filtering that handles missing data correctly and you know why a zero in their place distorts the similarities. You can build a content-based with TF-IDF and say where it stops. You know that matrix factorization learns latent factors from the observed ratings only and how far to trust its regularization. You can evaluate a list with precision@K and NDCG@K. The next article takes models already trained by others and adapts them to your data: transfer learning and fine-tuning.

If you want a supervised model on top of the similarities computed here, ensembles are the next step.

Frequently asked questions

Why are zeros not put in place of missing ratings?

Because zero equals a very low rating and distorts the similarities: in the example the cosine with zeros gives user 0 a similarity of 0.49 with a user of opposite tastes, which Pearson on the films in common estimates at -0.96.

What is the difference between precision@K and NDCG@K?

Precision@K counts how many relevant items are in the first K without looking at the order; NDCG@K weighs relevant items at the top of the list more. With the same three relevant items the precision@5 stays 0.60 both low and high, while the NDCG@5 goes from 0.680 to 1.000.

How do you deal with cold start?

For a new product with content-based, which requires only its characteristics; for a new user with a few initial questions or with the most popular products, switching to collaborative filtering when the first interactions arrive.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects