AI Wiki中文/EN

Collaborative filtering: whose ratings make two items alike?

协同过滤

Compute co-rated adjusted cosine, shrink weak evidence and predict from an explicit item neighborhood.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

An empty cell is not a one-star review

Suppose two readers both like films A and B. A third reader has rated B but has never seen A. Their missing A rating supplies no direct evidence about whether A and B appeal to similar people. Filling that cell with zero would turn ignorance into an opinion.

Collaborative filtering uses patterns across user–item interactions. A user neighborhood asks which users behave alike; an item neighborhood asks which items receive similar responses. Latent-factor methods also belong to collaborative filtering, although they need not retrieve explicit neighbors. This article implements an item neighborhood, leaving latent factors to matrix factorization. Koren and colleagues, PDF 2–3

Sarwar and colleagues describe item similarities based on users who rated both items, including an adjusted cosine that subtracts each user’s average rating. That adjustment matters when one reader gives nearly everything high scores and another uses the lower end of the scale. Item-based CF, PDF 4, section 3.1

The same four co-raters produce raw similarities and support-shrunk positive weights.
The same four co-raters produce raw similarities and support-shrunk positive weights.

Compare opinions on the shared evidence

Let r be a U-by-I rating matrix, with missing entries represented separately from numeric ratings. O_u is the set of items rated by user u. Compute that user’s mean using observed training ratings only:

rˉu=1∣Ou∣∑j∈Ouruj.\bar r_u=\frac{1}{|O_u|}\sum_{j\in O_u}r_{uj}.

For an empty user row, our program uses the global observed mean as a fallback. It requires at least one observed rating somewhere in the matrix. A real zero remains an observation; NaN denotes missingness.

For items i and j, define U_ij as users who rated both. Adjusted cosine compares their mean-centered ratings on that same overlap in both numerator and denominator:

sij=∑u∈Uij(rui−rˉu)(ruj−rˉu)∑u∈Uij(rui−rˉu)2∑u∈Uij(ruj−rˉu)2.s_{ij}=\frac{\sum_{u\in U_{ij}}(r_{ui}-\bar r_u)(r_{uj}-\bar r_u)}{\sqrt{\sum_{u\in U_{ij}}(r_{ui}-\bar r_u)^2}\sqrt{\sum_{u\in U_{ij}}(r_{uj}-\bar r_u)^2}}.

This is the adjusted cosine described in the paper, not cosine after filling every missing entry. The user means use all their observed training ratings, while the paired products use only co-raters. PDF 4, adjusted cosine

A similarity of 1 from two people should not be confused with extensive evidence. Our teaching variant requires at least two co-raters and shrinks similarity using support n and a nonnegative parameter beta:

s~ij=nijnij+βsij,nij=∣Uij∣.\widetilde s_{ij}=\frac{n_{ij}}{n_{ij}+\beta}s_{ij},\qquad n_{ij}=|U_{ij}|.

This shrinkage is an explicit design choice in our example, not a formula attributed to Sarwar’s paper. We use beta=2. Insufficient support or a zero denominator gives similarity zero; the diagonal is zero because an item is not its own recommendation neighbor.

For a target user, choose at most k positively similar items they have rated. With that set N, predict a raw rating by a normalized weighted sum:

r^ui=∑j∈Ns~ijruj∑j∈Ns~ij,s~ij>0.\widehat r_{ui}=\frac{\sum_{j\in N}\widetilde s_{ij}r_{uj}}{\sum_{j\in N}\widetilde s_{ij}},\qquad \widetilde s_{ij}>0.

The paper describes weighted prediction using a sum of absolute similarities in the denominator. Our positive-neighbor restriction makes that denominator equal to the sum above. Other implementations can retain negative neighbors or predict centered residuals; those are different choices and need their own checks. PDF 5, section 3.2.1

For a nonempty positive neighborhood, normalized weights are nonnegative and sum to one. Consequently:

min⁡j∈Nruj≤r^ui≤max⁡j∈Nruj.\min_{j\in N}r_{uj}\le\widehat r_{ui}\le\max_{j\in N}r_{uj}.

That bound follows from a convex combination, not from collaborative filtering in general. If no neighbor survives, the program returns the user’s mean.

Trace a prediction back to two ratings

The complete original program runs with Python 3.12 and NumPy 1.26.4. It uses a disclosed synthetic 5-by-5 rating matrix. User 0 has ratings 5, 4 and 1; item 2 is unobserved. No held-out rating is silently inserted into similarity estimation.

"""Original positive-neighbor item CF using co-rated adjusted cosine."""
import json
import numpy as np


def validate(ratings):
    r=np.asarray(ratings,float)
    if r.ndim!=2 or min(r.shape)==0 or np.isinf(r).any() or not np.isfinite(r).any():raise ValueError('finite observations or NaN required')
    return r


def means(ratings):
    r=validate(ratings);observed=np.isfinite(r);count=observed.sum(axis=1)
    return np.divide(np.nansum(r,axis=1),count,out=np.full(len(r),np.nanmean(r)),where=count>0)


def similarity(ratings, min_common=2, shrinkage=2.):
    r=validate(ratings)
    if not isinstance(min_common,int) or min_common<1 or not np.isfinite(shrinkage) or shrinkage<0:raise ValueError('invalid support controls')
    avg=means(r);n=r.shape[1];s=np.zeros((n,n));support=np.zeros((n,n),int)
    for i in range(n):
        for j in range(i):
            common=np.isfinite(r[:,i]) & np.isfinite(r[:,j]);count=int(common.sum());support[i,j]=support[j,i]=count
            if count<min_common:continue
            a=r[common,i]-avg[common];b=r[common,j]-avg[common]
            denom=np.linalg.norm(a)*np.linalg.norm(b)
            if denom:s[i,j]=s[j,i]=float(a@b/denom)*count/(count+shrinkage)
    return s,support


def predict(ratings,user,item,k=2,shrinkage=2.):
    r=validate(ratings)
    if not isinstance(k,int) or k<0 or not 0<=user<len(r) or not 0<=item<r.shape[1]:raise ValueError('invalid indices or k')
    s,support=similarity(r,shrinkage=shrinkage)
    candidates=[j for j in range(r.shape[1]) if j!=item and np.isfinite(r[user,j]) and s[item,j]>0]
    chosen=sorted(candidates,key=lambda j:(-s[item,j],j))[:k]
    value=float(sum(s[item,j]*r[user,j] for j in chosen)/sum(s[item,j] for j in chosen)) if chosen else float(means(r)[user])
    return dict(value=value,neighbors=chosen,weights=[float(s[item,j]) for j in chosen],support=[int(support[item,j]) for j in chosen])


def demo():
    r=np.array([[5,4,np.nan,1,np.nan],[4,5,4,1,2],[1,2,1,5,4],[2,1,2,4,5],[5,4,5,np.nan,1]],float)
    raw,count=similarity(r,shrinkage=0);shrunk,_=similarity(r,shrinkage=2)
    return dict(prediction=predict(r,0,2),user_mean=float(means(r)[0]),
                raw_similarities=raw[2].tolist(),shrunk_similarities=shrunk[2].tolist(),support=count[2].tolist(),
                no_neighbors=predict(r,0,2,k=0),ratings=[[None if np.isnan(v) else float(v) for v in row] for row in r])


if __name__=='__main__':print(json.dumps(demo(),allow_nan=False))

Items 0 and 1 become the selected neighbors. Both have four co-raters with item 2. Their shrunk weights are approximately 0.666667 and 0.453333. The weighted prediction is 4.595238, between the contributing ratings 4 and 5. Setting k=0 instead returns the user’s mean, 10/3. The example explains a prediction; without a disclosed target label, it does not measure prediction accuracy.

An independent test computes the shared-rating dot product with scalar loops. Other tests distinguish missing values from zeros, check symmetry and constant-rating denominators, and verify the convex-combination bound. In a hand case where two co-raters have identical centered opinions, raw similarity is 1; support 2 and beta 2 shrink it to 0.5.

For U users and I items, this dense implementation takes O(U I²) time to construct all pair similarities, stores O(U I + I²), and recomputes them per prediction. Once similarities are cached, selecting a user’s top k neighbors by full sorting takes at most O(I log I), then summing costs O(k). Sarwar’s paper also discusses precomputing item neighborhoods; a production implementation should avoid recomputing the full table on every request. PDF 5, section 3.3

A strong similarity can rest on a narrow audience

Co-rating is selective: a niche audience may be the only overlap between two items. Shrinkage reduces the weight of small samples but does not remove selection bias. Popular items can supply more usable neighbors; new items with no ratings cannot obtain a collaborative neighborhood. Metadata can provide a separate route through content-based recommendation.

Mean-centering similarity does not mean this predictor corrects all user scale differences: its final sum still combines the target user’s raw ratings. Nor does a predicted rating establish top-k ranking quality. Evaluate on ratings or future choices withheld before constructing means and similarities. The matrix must be rebuilt from training observations, otherwise the target itself can influence its neighbors. These limits distinguish the example from a full recommender service.

Check the overlap before the score

  1. Is a real rating of zero missing in this implementation? Answer: No. A finite zero participates in means and pair statistics. Only NaN is missing.
  2. With raw similarity 1, two co-raters and beta=2, what weight remains? Answer: 0.5, because the support multiplier is 2/(2+2). It measures a chosen shrinkage, not a probability.
  3. Can our positive-neighbor predictor return 6 from neighbor ratings 4 and 5? Answer: No. Positive normalized weights form a convex combination bounded by 4 and 5. Negative-neighbor variants need not obey this argument.
  4. A newly released item has a detailed description and no ratings. Which additional route is available? Answer: A content model can score its attributes for an existing user profile. The item neighborhood alone has no co-raters from which to estimate similarity.

Separate the paper’s method from our choices

The source reading covers the paper’s identity, item similarities, prediction and neighborhood precomputation on physical PDF pages 1, 4 and 5. Those pages were viewed because extracted text was corrupted. The Koren overview locates neighborhood methods alongside latent factors. Minimum support, support shrinkage, positive-only neighbors and deterministic tie-breaking are disclosed choices of this original implementation. No published benchmark result is reproduced here.

Make a prediction, then check

Why is a missing rating not safely replaceable by zero?

Choose one answer

Learning objectives

  • Distinguish missing ratings from real zeros and explain a neighborhood prediction.
  • Run the original example, check its numerical result and explain one failure condition.

Prerequisites & connections

Explore related knowledge →

References

  1. Item-Based Collaborative Filtering Recommendation Algorithms
    Badrul Sarwar; George Karypis; Joseph Konstan; John Riedl · 2001
  2. Matrix Factorization Techniques for Recommender Systems
    Yehuda Koren; Robert Bell; Chris Volinsky · 2009

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: Viewed physical PDF 1, 4–5 because text extraction was garbled; identity, co-rated adjusted cosine, weighted prediction and precomputed neighborhoods. Physical PDF 1 identity, 2–4 methods text; viewed page 4 equations. Observed ratings, biases, SGD/ALS. No benchmark reproduction. 5 paired equations and four explained exercises. Checked co-rated adjusted cosine by an independent scalar loop, support shrinkage, positive weights, convex prediction, missing versus zero, constant denominators and fallback. Disclosed neighborhood variant.

  • Checked co-rated adjusted cosine by an independent scalar loop, support shrinkage, positive weights, convex prediction, missing versus zero, constant denominators and fallback. Disclosed neighborhood variant.
  • Four computed SVG variants per topic;11 numeric/geometry tests and36 responsive cases passed. Twelve selected captures visually checked;11 current images match previously viewed bytes and the revised matrix-factorization image was viewed again. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.