A video platform deciding what to show next, an online store displaying related products, and a learning platform suggesting the next lesson all face a similar problem: which items are likely to be useful to a particular user? A recommendation system, or recommender system, estimates the relevance or utility of available items and uses those estimates to select or rank suggestions.
A recommendation is not necessarily a prediction of what someone will like. A system may instead optimize learning progress, long-term satisfaction, safety, discovery, or another explicitly defined objective. The objective and the data used to measure it affect what the system recommends.
Start with a simple example
Imagine PlainCS has five articles and a learner has completed two introductory Python lessons. The website has to choose what to suggest next. It could recommend the most popular article to everyone, but that ignores what this particular learner already knows. A more useful system might suggest NumPy before a neural-network tutorial, because the learner is more likely to understand it.
A recommender therefore needs items (articles), some representation of the user (completed lessons or interests), and a goal (for example, helping the learner progress). It then assigns scores to candidate articles and ranks them. Scores are estimates, not facts about what a person will enjoy.
For a simple illustrative content-based system, suppose a learner’s interest vector is , with the first dimension representing Python and the second representing web development. A Python article is and a web article is . Using the dot product as a toy similarity score:
The Python article ranks first. Real systems use richer features, different objectives, and checks for quality, diversity, and fairness. A high score also does not prove that the recommendation caused a good outcome.
This example prepares us to distinguish content-based filtering, which uses item and user characteristics, from collaborative filtering, which uses patterns of interaction across people and items.
1. The recommendation problem
The main components are:
- Users: People or accounts receiving recommendations.
- Items: Products, videos, articles, songs, lessons, or other recommendable entities.
- Interactions: Observed actions such as views, clicks, ratings, purchases, completions, or skips.
- Context: Optional signals such as device, time, location at a suitable privacy level, or the current session.
- Candidate set: Items eligible for recommendation, after availability and policy constraints.
- Scoring and ranking: Estimating each candidate’s usefulness and deciding which items to show.
If is a user and is an item, a model might estimate a score or a conditional probability such as , where is the context. Scores do not automatically represent calibrated probabilities. A ranking procedure orders items by the chosen scoring rule, subject to product requirements.
Recommendation and information retrieval overlap but differ in emphasis. Search retrieves items in response to an explicit query; recommendation often proposes items without a specific query, using preferences or context. Both systems can use similar retrieval and ranking techniques.
2. Explicit and implicit feedback
A recommender learns from signals, but not all signals mean the same thing.
| Feedback type | Examples | What it tells us | Main limitation |
|---|---|---|---|
| Explicit | Ratings, likes, preference choices | Directly stated preferences | Sparse; users rarely rate everything |
| Implicit | Clicks, views, purchases, dwell time | Observed behavior | An action does not necessarily imply enjoyment |
| Negative or weak feedback | Dislikes, skips, returns | Possible dissatisfaction | Meaning depends on context |
| Missing feedback | No recorded interaction | Usually unknown preference | Cannot generally be treated as a dislike |
A click can indicate curiosity rather than satisfaction. A purchase can reflect necessity rather than preference. Logged behavior is also shaped by exposure: users can interact only with items they have had an opportunity to see. Training only on observed interactions can reinforce previous recommendations and reduce discovery.
The first task is therefore to specify a target signal. Is the system predicting a rating, a click, the probability of a completed lesson, or something else? Each target leads to different data and evaluation choices.
3. Content-based recommendation
Content-based filtering recommends items using their attributes and a representation of user preferences. A book recommender might represent books by genres, topics, and descriptions, then suggest books similar to those a reader has previously enjoyed.
A simple procedure is:
- Convert items into feature vectors, such as topic indicators or text embeddings.
- Build a user profile from the features of items associated with positive feedback.
- Compare the user profile with eligible item vectors.
- Rank the most relevant items, excluding items that should not be repeated.
For numerical feature vectors and , one common similarity measure is cosine similarity:
The expression requires nonzero vectors. Cosine similarity measures directional alignment rather than Euclidean distance, so the choice of feature representation matters.
Example: If a learner has completed several introductory Python lessons, a content-based system might recommend functions, lists, or debugging lessons because their topics align with the learner’s prior activity. However, recommending only very similar lessons can prevent progression into unfamiliar but necessary subjects.
Content-based systems are useful when item metadata is informative or new items have few interactions. Their weaknesses include limited discovery beyond represented features and dependence on accurate item descriptions.
4. Collaborative filtering
Collaborative filtering uses patterns across interactions between many users and items. Its underlying premise is that interaction histories can reveal preferences that item metadata alone may not capture.
4.1 The user–item interaction matrix
A conceptual matrix contains users in rows, items in columns, and recorded interactions in cells:
| User | Python basics | SQL basics | Neural networks | Computer vision |
|---|---|---|---|---|
| A | 1 | 1 | ? | ? |
| B | 1 | 1 | 1 | ? |
| C | ? | ? | 1 | 1 |
Here, 1 means an observed positive interaction, while ? means no observed interaction. The missing entries are not automatically zeros or negative labels.
The system seeks useful patterns in this sparse matrix. Two traditional forms are:
- User-based collaborative filtering: Find users with similar histories and recommend items appreciated by the neighbors.
- Item-based collaborative filtering: Find items with similar interaction patterns and recommend items related to what the user consumed.
4.2 Matrix factorization
Matrix factorization approximates an interaction matrix using lower-dimensional user and item representations. A common prediction form is:
where is a global baseline, and are user and item bias terms, and and are learned latent-factor vectors. Particular algorithms may omit bias terms or use different objectives.
The factor vectors capture useful statistical patterns, but a latent dimension does not necessarily have a clear human-readable meaning. Factorization algorithms trained on ratings and algorithms designed for implicit interactions often use different losses and assumptions.
Collaborative filtering can reveal unexpected associations between items, but it typically needs sufficient interaction history. New users and new items can be difficult to model without additional information.
5. Hybrid and context-aware systems
A hybrid recommender combines multiple sources of evidence, such as content similarity, collaborative scores, popularity, editorial rules, and contextual information.
For example, a simple hybrid score could be:
where . This weighted blend is meaningful only if the component scores have compatible scales or have been calibrated or normalized appropriately.
More sophisticated systems use learned ranking models to combine features. Context-aware recommendation additionally accounts for circumstances such as the current learning stage, current session, or item availability. Context should be collected and used only when appropriate and justified.
A learning platform could use collaborative patterns to find helpful courses, content features to establish prerequisites, and explicit rules to exclude courses a learner has already completed. A single model does not need to handle every requirement.
6. Candidate generation and ranking
When a catalog contains millions of items, scoring every item with a costly ranking model is often impractical. Large-scale systems commonly use multiple stages:
- Candidate generation: Retrieve a manageable set using popularity, co-interactions, approximate nearest-neighbor search, or other methods.
- Eligibility filtering: Enforce availability, permissions, content restrictions, or prerequisite requirements.
- Ranking: Estimate a chosen outcome or utility for the candidates.
- Reranking and selection: Consider diversity, freshness, coverage, fairness, repetition, and other product constraints.
- Display and feedback: Present results, record appropriately authorized interactions, and evaluate outcomes.
A retrieval-stage metric measures whether worthwhile items enter the candidate set. A ranking-stage metric measures how well those candidates are ordered. A system can fail at either stage: an excellent ranker cannot select an item that retrieval never supplied.
7. A practical content-based recommender in Python
The example below uses TF-IDF features from article descriptions and cosine similarity to recommend articles related to a previously selected article. It is deliberately small and does not require historical user data.
Install the dependency:
python -m pip install scikit-learn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
articles = [
{"title": "Python Functions", "text": "python functions arguments return values"},
{"title": "Python Lists", "text": "python lists indexing slicing collections"},
{"title": "SQL Queries", "text": "sql database queries joins tables"},
{"title": "Neural Networks", "text": "neural networks weights layers training"},
{"title": "Gradient Descent", "text": "training optimization gradients weights loss"},
]
vectorizer = TfidfVectorizer()
features = vectorizer.fit_transform([a["text"] for a in articles])
similarity = cosine_similarity(features)
selected_index = 3 # Neural Networks
ranked = sorted(
(
(similarity[selected_index, index], article["title"])
for index, article in enumerate(articles)
if index != selected_index
),
reverse=True,
)
for score, title in ranked[:2]:
print(f"{title}: {score:.3f}")
The text descriptions determine which words overlap. In this deliberately chosen dataset, Gradient Descent should have the highest similarity to Neural Networks because the descriptions share the words training and weights. The example is reproducible for a fixed scikit-learn version but should not be mistaken for a personalized, production-ready recommendation service.
Notice what the example does not do: it does not train a collaborative filtering model, use individual user profiles, guarantee educational prerequisite order, or measure user satisfaction. These would require additional data, logic, and evaluation.
8. How recommendation systems are evaluated
A recommender must be evaluated against its defined objective, not simply by whether its suggestions look plausible.
8.1 Offline ranking metrics
Suppose each user has a set of relevant held-out items, and the recommender returns a ranked list of items.
Precision at K measures the fraction of recommended items that are relevant:
Recall at K measures the fraction of all relevant held-out items included in those recommendations:
Recall is undefined when the chosen held-out set contains no relevant items; evaluation code must specify how such users are handled.
Other metrics include:
| Metric | What it evaluates |
|---|---|
| Hit Rate@K | Whether at least one relevant item appears in the top K |
| Mean Reciprocal Rank (MRR) | How early the first relevant item appears |
| NDCG@K | Ranking quality with position discounts and possibly graded relevance |
| Coverage | How much of the item catalog or user population the system can serve |
| Diversity | How varied a recommendation list is under a defined measure |
| Novelty | Whether recommendations go beyond familiar or popular items |
For ratings, prediction metrics such as MAE or RMSE can be useful, but good rating prediction does not necessarily produce good top-K recommendations.
8.2 Offline evaluation design
To simulate real recommendation conditions, training data must not contain interactions that occur after the evaluation time. Time-based splits often better reflect deployment than random interaction splits. Related interactions can also leak across splits, so splitting policy should reflect the intended use case.
Feedback data is frequently missing not at random because the current interface and recommender determine what users see. An offline benchmark built only from logged interactions may favor the policy that created those logs. Interpret evaluation results with this exposure bias in mind.
8.3 Online evaluation
Once a system is safe to test, online evaluation can examine outcomes such as successful learning, retention, purchases, satisfaction, or complaint rates. A/B tests compare alternative policies on actual traffic under controlled conditions. Short-term clicks should not automatically outweigh long-term user value.
9. Common challenges and failure modes
Cold start
A new-user cold start occurs when a user has little history; a new-item cold start occurs when an item has few interactions. Possible responses include an onboarding preference survey, item metadata, contextual signals, or a carefully designed popularity baseline.
Sparsity
Most users interact with only a small fraction of available items. Sparse feedback can make similarity estimates unstable and difficult to generalize.
Popularity bias and feedback loops
Popular items receive more exposure and therefore more interactions, which can make them even more likely to be recommended. This feedback loop can marginalize new, niche, or educationally important content. Exploration and explicit coverage goals can help, but they require tradeoffs and careful measurement.
Privacy and security
Interaction histories can reveal personal preferences or sensitive information. Minimize collection, respect consent and permissions, protect stored records, and limit how long information is retained. Recommenders must also account for manipulated interactions, automated clicks, and attempts to promote items fraudulently.
Conflicting objectives
Maximizing click-through rate can create incentives to recommend sensational or repetitive content. For a learning platform, recommending the most-clicked lesson may be less useful than recommending the lesson that actually helps the learner progress. Choose objectives that correspond to the product’s real purpose.
10. Designing a recommendation system for PlainCS
Imagine a PlainCS feature that suggests what to study after reading an article about Neural Network Fundamentals.
A straightforward initial design could be:
- Store each article’s topic, difficulty, and prerequisite article slugs.
- Identify the current article and the learner’s explicitly available progress data.
- Retrieve related articles using topic tags or text features.
- Exclude unpublished or inaccessible articles and any items that should not be repeated.
- Apply prerequisite rules so that introductory material precedes advanced topics when necessary.
- Rank suitable candidates and explain the connection in ordinary language, such as “Uses the gradients introduced in this article.”
- Evaluate whether learners successfully continue along the intended learning path.
This first version can use metadata and conventional ranking rules. A learned recommender becomes useful when there is adequate, appropriately collected interaction data and a demonstrated improvement over that baseline.
11. Related concepts
- Machine Learning Paradigms explains learning from different kinds of supervision.
- Text Processing, Tokenization, and Embeddings introduces numerical text representations useful for content similarity.
- Dimensionality Reduction and PCA explains an approach to compressing feature representations.
- Evaluating Machine Learning Models covers broader evaluation principles and data leakage.
- Information Retrieval and Search extends candidate retrieval and ranking to query-based search.
- Embeddings and Vector Search explores semantic retrieval techniques in greater detail.
12. References and further reading
- Ricci, F., Rokach, L., and Shapira, B. (eds.). Recommender Systems Handbook. Springer, 2022 (3rd edition).
- Aggarwal, C. C. Recommender Systems: The Textbook. Springer, 2016.
- Koren, Y., Bell, R., and Volinsky, C. “Matrix Factorization Techniques for Recommender Systems.” Computer, 42(8), 2009, pp. 30–37. DOI: 10.1109/MC.2009.263.
- scikit-learn: Working with text data explains text feature extraction used in the Python example.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.