Recommend unseen items with item-item cosine similarity
Item-item collaborative filtering says: people who interacted with what you interacted with also liked these. It is cheap, explainable and still a strong baseline in production recommenders.
Write recommend_items(R, user, k). R has shape (n_users, n_items) with interaction strengths (0 means no interaction).
1. Treat each item as its column vector of R. Build the item-item cosine similarity matrix S. Columns with zero norm have similarity 0 with everything. Set the diagonal of S to 0.
2. The user's score for item j is sum over items m of S[j, m] * R[user, m].
3. Exclude every item the user already interacted with (R[user, j] > 0). Rank the rest by score, highest first. Round scores to 10 decimals before ranking, and break ties by lower item index.
Return a list of up to k item indices (fewer if the user has fewer than k unseen items).
def recommend_items(R, user, k)Example
R = [[1, 1, 0], [1, 0, 1], [0, 1, 1]] (rows are users). For user 0, only item 2 is unseen, so the answer for k = 2 is [2].
Understand the idea
Item-item filtering says two items are similar if the same users interacted with both. Each item is a column of the user-item matrix R, and cosine similarity compares those columns while ignoring how popular each item is. A user's score for an unseen item adds up its similarity to everything the user already touched, weighted by how strongly. Worked example: R = [[1, 0, 0], [1, 1, 0], [0, 1, 1]]. Columns: item 0 = [1, 1, 0], item 1 = [0, 1, 1], item 2 = [0, 0, 1]. cos(0, 1) = 1 / (1.414 * 1.414) = 0.5, cos(0, 2) = 0, cos(1, 2) = 1 / 1.414 = 0.707. User 0 only touched item 0, so score(item 1) = 0.5 and score(item 2) = 0. Ranking: [1, 2]. Rule: S[j, m] = (col_j . col_m) / (norm_j * norm_m), zero-norm columns give 0, diagonal set to 0; score_j = sum_m S[j, m] * R[user, m]; drop items with R[user, j] > 0; sort by rounded score, ties to lower index. Used for 'customers also bought' style widgets.