← All guides

Guide

Building a recommendation system in Python: the steps

Building a recommendation system in Python takes five steps: gather the data, build a first content-based model, add collaborative filtering, evaluate the results, then serve the recommendations in production. The first three fit in a few dozen lines with pandas, scikit-learn and the implicit library. The last one is the one that takes the most work. Here is each step, with the code.

What data does a recommendation system need?

Two tables are enough to start:

  • The catalog: one identifier per item, a title, a description, and the useful attributes (category, brand, genre).
  • The interactions: who viewed, clicked, added to cart or bought what, and when. These are implicit signals: you don’t ask the user anything, you observe. They are often given a weight, for example 1 for a view and 5 for a purchase.

No need for explicit ratings (stars): most sites have almost none, and implicit signals are far more numerous.

Step 1: a first content-based model with scikit-learn

Content-based filtering recommends items close to the one being viewed. It works without any history, which makes it the right starting point. You vectorize the texts with TF-IDF, then compare the vectors:

import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel

items = pd.read_csv("items.csv")  # item_id, title, description
text = items["title"].fillna("") + " " + items["description"].fillna("")

matrix = TfidfVectorizer(min_df=2).fit_transform(text)
similarity = linear_kernel(matrix, matrix)  # normalized vectors: cosine

def similar_items(index, k=5):
    best = similarity[index].argsort()[::-1]
    best = [i for i in best if i != index][:k]
    return items.iloc[best]["item_id"].tolist()

TF-IDF only ships with an English stop-word list: for a catalog in another language, pass your own list to the stop_words parameter. To go further, replace TF-IDF with semantic embeddings (for example with sentence-transformers), which bring together two descriptions worded differently. On a large catalog, the full similarity matrix gets too heavy: you then store the vectors in a vector database and look up the nearest neighbors on demand.

Step 2: collaborative filtering with implicit

Collaborative filtering learns from behavior: people who buy the same items have similar tastes. The ALS (Alternating Least Squares) algorithm, suited to implicit signals, is available in the implicit library:

import implicit
import pandas as pd
from scipy.sparse import csr_matrix

events = pd.read_csv("events.csv")  # user_id, item_id, weight (view = 1, purchase = 5...)
users = events["user_id"].astype("category")
products = events["item_id"].astype("category")

user_items = csr_matrix(
    (events["weight"].astype("float32"), (users.cat.codes, products.cat.codes))
)

model = implicit.als.AlternatingLeastSquares(factors=64, regularization=0.05, iterations=20)
model.fit(user_items)

user = 0
ids, scores = model.recommend(user, user_items[user], N=10, filter_already_liked_items=True)
print(products.cat.categories[ids].tolist())

The factors and regularization parameters are tuned by evaluating the model (next step). Keep the main limit in mind: a user or an item without any interaction has no vector, and therefore no recommendation. This is the cold start problem, handled by falling back on content or on popular items. We compare these approaches in detail in collaborative, content-based or hybrid filtering.

Step 3: combine the two into a hybrid model

The simplest way is to normalize both scores between 0 and 1, then blend them with a weight: score = alpha * content + (1 - alpha) * collaborative. A high alpha follows what the person is looking at now, a low alpha reflects their past tastes. For a new user, start with an alpha close to 1 and lower it as their history grows.

Step 4: how do you evaluate a recommendation system?

Split the interactions in time: train on the past and check whether the model finds what users did next. A random split leaks the future into training and gives overly optimistic scores. The usual metrics:

  • Precision@k and recall@k: of the k recommended items, how many were actually viewed or bought.
  • NDCG@k: takes the position into account; a good recommendation in first place is worth more than in tenth.
  • Coverage and diversity: a model that always recommends the same ten best-sellers can have good precision and add nothing.

Always compare against a simple baseline, such as the most popular items: if the model does not beat it, it is not ready.

Step 5: put the recommendation system into production

A notebook that produces good recommendations is not a system yet. You still have to:

  • expose the recommendations behind an API, with short response times;
  • collect the site’s events continuously;
  • retrain regularly, without degrading production if a new model is worse;
  • handle the cold start and anonymous visitors;
  • measure which recommendations are seen, clicked and bought.

This is the part that costs the most over time, as we explain in LIKYLY vs. building your own solution.

What LIKYLY simplifies with its Python SDK

If your goal is to display recommendations rather than run an engine, the LIKYLY Python SDK replaces steps 1 to 5 with three calls. It installs with pip install likyly, works with Python 3.9 or later, is fully typed and offers a synchronous client (Likyly) and an asyncio client (AsyncLikyly):

import os
from likyly import Likyly

# Server side only: the secret key gives access to your catalog.
likyly = Likyly(api_key=os.environ["LIKYLY_SECRET_KEY"])

# 1. Send the catalog (with your own identifiers).
likyly.items.upsert_many([
    {"item_id": "SKU-1", "title": "Nike Air Max", "description": "Cushioned running shoe"},
    {"item_id": "SKU-2", "title": "Adidas Ultraboost", "description": "Responsive running shoe"},
])

# 2. Record what visitors do.
likyly.events.view(user_id="user_123", item_id="SKU-1")

# 3. Ask what to display: LIKYLY picks the strategy based on what it knows.
recs = likyly.recommendations.get(
    user_id="user_123", item_id="SKU-1", placement="product_page", limit=6
)
for item in recs.items:
    print(item.item_id, item.title, item.score)

You don’t choose the algorithm: depending on what you send (a known user, an anonymous session, the product on screen), LIKYLY uses content, session, collaborative filtering or hybrid. The SDKs for other languages are on the developers page.