Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathFind Structure Without Labels: Clustering, PCA and Recommenders
  1. 1
    K-Means Clustering: Find Groups in Data With No Labels
  2. 2
    Choosing k for K-Means: the Elbow Method and the Silhouette Score
  3. 3
    Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
  4. 4
    Dimensionality Reduction with PCA: 13 Columns Down to 2
  5. 5
    Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
  6. 6
    Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Unsupervised Learning

Learning path: Find Structure Without Labels: Clustering, PCA and Recommenders · Step 6 of 6

Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity

Build an item-based recommender: a user-item matrix, correlation and cosine similarity on five readers, then 433,671 Book-Crossing ratings in a sparse matrix to find the books closest to A Painted House.

Chaand Sheikh

·27 November 2026Unsupervised Learning

What you will learn

  • Build a user-item matrix with pivot_table
  • Find similar items with correlation and cosine similarity
  • Avoid the small-overlap trap with a minimum ratings threshold
  • Store ratings in a sparse matrix and recommend the closest books

Before you start

  • pandas pivot tables and value_counts
  • Correlation and Heatmaps

You open a book on a shopping site, say A Painted House. Right below it: "customers who bought this also bought" The Testament, The Brethren and 2nd Chance. Nobody wrote that list by hand. It comes from what other shoppers did. This idea is called collaborative filtering, and it needs no labels: the ratings alone teach the model which books go together.

There are two flavours:

  • User-based: find readers like you, and recommend what they liked.
  • Item-based: find books rated like this one, and recommend those.

We'll build the item-based one.

One row per rating, then pivot

Start tiny: five readers, four books, ratings from 1 to 10. Ratings usually arrive one row per rating:

import warnings
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix
from sklearn.metrics.pairwise import (
    cosine_similarity)

warnings.filterwarnings("ignore")

data = {
    "Ann":  {"Potter": 9, "Narnia": 8, "Cookbook": 2},
    "Ben":  {"Potter": 8, "Narnia": 9, "Hobbit": 7},
    "Cara": {"Potter": 2, "Narnia": 3, "Hobbit": 2,
             "Cookbook": 9},
    "Dan":  {"Narnia": 8, "Hobbit": 9, "Cookbook": 1},
    "Eve":  {"Potter": 9, "Hobbit": 8, "Cookbook": 3}}
rows = [(r, b, s) for r, d in data.items()
        for b, s in d.items()]
small = pd.DataFrame(rows,
    columns=["reader", "book", "rating"])
small.shape
(16, 3)
small.head(2)
  reader    book  rating
0    Ann  Potter       9
1    Ann  Narnia       8

Sixteen ratings, one per row. pivot_table moves each rating into its own cell: readers go down, books go across.

table = small.pivot_table(index="reader",
    columns="book", values="rating")
table = table.rename_axis(index=None, columns=None)
table
      Cookbook  Hobbit  Narnia  Potter
Ann        2.0     NaN     8.0     9.0
Ben        NaN     7.0     9.0     8.0
Cara       9.0     2.0     3.0     2.0
Dan        1.0     9.0     8.0     NaN
Eve        3.0     8.0     NaN     9.0

This is a user-item matrix. NaN means the reader hasn't read that book yet.

Which books are rated like the Hobbit?

Way 1: correlation

corrwith compares the Hobbit column with every other column, using only the readers who rated both (see Correlation and Heatmaps):

like = table.corrwith(table["Hobbit"])
print(like.round(2).to_string())
Cookbook   -0.99
Hobbit      1.00
Narnia      0.91
Potter      1.00

Way 2: cosine similarity

Cosine similarity treats each book column as an arrow and compares their angles: 1 means they point the same way. It can't handle gaps, so we fill the empty cells with 0. We transpose with .T so each book becomes a row to compare.

filled = table.fillna(0)
cos = cosine_similarity(filled.T)
cos = pd.DataFrame(cos, index=filled.columns,
    columns=filled.columns)
print(cos["Hobbit"].round(2).to_string())
Cookbook    0.37
Hobbit      1.00
Narnia      0.68
Potter      0.62
User-item matrix and similarity to the Hobbit CookbookHobbitNarniaPotter Ann 2?89 -798 9232 198- 38-9 BenCaraDanEve Like the Hobbit? corrcosine Cookbook-0.990.37 Narnia0.910.68 Potter1.000.62 Ann loved Potter and Narnia but hasn't read the Hobbit, so we recommend it to her.
The user-item matrix (a dash is an unread book; the red ? is the book we want to recommend) and how alike each book is to the Hobbit.

Both ways agree: the Hobbit goes with Potter and Narnia, and the cookbook is the opposite taste. Ann loved Potter and Narnia but hasn't read the Hobbit, so we recommend it to her.

One warning: Potter's 1.00 correlation rests on only 3 readers who rated both books. Keep that in mind; it comes back as a trap on real data.

The Book-Crossing ratings

ratings = pd.read_csv("BX-Book-Ratings.csv",
    sep=";", encoding="latin-1")
titles = pd.read_csv("BX-Books-titles.csv",
    dtype=str).set_index("ISBN")
print(ratings.shape)
(1149780, 3)

1,149,780 rows. In this data a rating of 0 means no rating was given, so we keep only the ratings above 0:

ratings = ratings[ratings["Book-Rating"] > 0]
readers = ratings["User-ID"].nunique()
books = ratings["ISBN"].nunique()
print(ratings.shape, readers, books)
(433671, 3) 77805 185973

433,671 ratings from 77,805 readers on 185,973 books. How big would one full table be? Books times readers, times 8 bytes per number:

print(round(books * readers * 8 / 1e9), "GB")
116 GB

Almost every cell is empty

Each reader has rated only a few books, so almost every cell of that table is empty. A normal (dense) table stores every single cell, and that's where the 116 GB come from. A sparse matrix stores only the ratings that exist, about 433 thousand numbers. That fixes the memory problem.

The trap: a perfect score from two readers

There's a second problem. Take everyone who rated A Painted House, and correlate that book with every other book they rated:

house = "038550120X"   # A Painted House
fans = ratings.loc[ratings["ISBN"] == house,
    "User-ID"]
sub = ratings[ratings["User-ID"].isin(fans)]
pv = sub.pivot_table(index="User-ID",
    columns="ISBN", values="Book-Rating")
corr = pv.corrwith(pv[house]).drop(house)
top = pd.DataFrame({"corr": corr.dropna(),
    "shared": pv.notna().sum()}).dropna()
top = top.sort_values("corr", ascending=False)
names = titles["Book-Title"].str[:22]
print(top.head(4).join(names).to_string())
            corr  shared              Book-Title
ISBN
0020519001   1.0       2  A Farewell to Arms (A
0849932017   1.0       3  Stick A Geranium In Yo
0842329242   1.0       2  Nicolae: The Rise of A
006099486X   1.0       2  The Professor and the 

Four books get a perfect 1.0. But look at the shared column: only 2 or 3 readers in common. That isn't real taste, it's luck: two readers who happened to agree. (The titles are cut to 22 characters to fit.)

The fix is a minimum: keep a book only if it has at least 50 ratings. Then every similarity rests on many readers.

Keep popular books, store the table sparse

counts = ratings["ISBN"].value_counts()
popular = counts[counts >= 50].index
r50 = ratings[ratings["ISBN"].isin(popular)]
isbn = r50["ISBN"].astype("category")
user = r50["User-ID"].astype("category")
M = csr_matrix((r50["Book-Rating"],
    (isbn.cat.codes, user.cat.codes)))
print(M.shape, M.nnz)
print(round(M.shape[0] * M.shape[1] * 8 / 1e6, 1), "MB")
(537, 21078) 50192
90.6 MB

value_counts gives the number of ratings per book, and we keep books with at least 50: 537 of the 185,973 survive. The category codes turn each ISBN and reader ID into a row and column number, and csr_matrix builds the sparse matrix from (rating, (row, column)).

The result has 537 books (rows) and 21,078 readers (columns), and M.nnz says it stores 50,192 ratings. As a dense table it would need 90.6 MB; the sparse one keeps only those 50,192 values.

The five closest books

sim = cosine_similarity(M)
i = list(isbn.cat.categories).index(house)
best = np.argsort(-sim[i])[1:6]
for j in best:
    b = isbn.cat.categories[j]
    t = titles.loc[b, "Book-Title"]
    print(round(sim[i, j], 3), t)
0.107 The Testament
0.1 The Brethren
0.096 2nd Chance
0.082 Midwives: A Novel
0.082 The Summons

cosine_similarity works directly on the sparse matrix and returns a book-by-book table. We find the row of A Painted House, sort it from high to low with argsort(-sim[i]), and skip position 0, which is the book itself. The next five are our recommendations.

Three of the five are by the same author, and nobody told the model about authors. It learned that from the ratings alone.

Common mistakes

  • Counting 0 as a rating when the data uses 0 for "not rated".
  • Trusting similarities from a tiny overlap. Two shared readers can give a perfect 1.0 by luck. Set a minimum number of ratings.
  • Building a dense table on real data. 116 GB won't fit; use a sparse matrix.
  • Forgetting to skip the item itself. A book is always most similar to itself.

Quick recap

StepCodeBook-Crossing result
Readers by bookspivot_table / csr_matrix537 x 21,078, 50,192 ratings
Drop non-ratingsratings["Book-Rating"] > 0433,671 of 1,149,780 rows
Avoid luckcounts >= 50537 books kept
Similaritycorrwith or cosine_similarityThe Testament 0.107
Recommendnp.argsort(-sim[i])[1:6]Five closest books

Try it yourself

Change the threshold from 50 to 30 ratings and recommend for A Painted House again. Which titles change?

The notebook and the Book-Crossing files are in the StudyEasy AI Community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
K-Means Clustering: Find Groups in Data With No Labels

How k-means finds groups without labels: the assign-update loop worked by hand on eight homes, then KMeans on 2,600 customers, bad random starts, k-means++ and why you scale first.

Choosing k for K-Means: the Elbow Method and the Silhouette Score

K-means always returns exactly k groups, even when k is wrong. Use the elbow plot and the silhouette score to pick k for 2,600 customers, then describe each group in plain words.

Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise

Two more ways to find groups: agglomerative clustering builds a family tree of merges (the dendrogram), and DBSCAN grows clusters from crowds and leaves loners out as noise. Shown on eight homes, 2,600 customers and two moons.

Dimensionality Reduction with PCA: 13 Columns Down to 2

PCA squeezes many columns into a few new ones and keeps most of the information. Reduce 178 wines from 13 columns to 2, see why scaling comes first, pick the number of components and use PCA in a pipeline.

On this page
  • One row per rating, then pivot
  • Which books are rated like the Hobbit?
  • Way 1: correlation
  • Way 2: cosine similarity
  • The Book-Crossing ratings
  • Almost every cell is empty
  • The trap: a perfect score from two readers
  • Keep popular books, store the table sparse
  • The five closest books
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.