Article
Content-Based Recommendation Systems: Theory and Practice (2/2)
Part 2 of the series: the machine learning pipeline behind a recommender, cosine similarity explained, and a Python implementation of content-based filtering.

Introduction
Content-based recommender systems are used to recommend items based on their similarity to other items. The most common way of measuring the similarity between two items is through the use of cosine similarity. Cosine similarity is a measure of the angle between two vectors in an n-dimensional space, and is commonly used in natural language processing and information retrieval.
Machine Learning Pipeline

A machine learning pipeline is a set of steps that are used to deploy a machine learning model into production. It is the process of taking a trained model and deploying it into an environment where it can be used to make predictions or decisions. The machine learning pipeline typically includes the following steps:
1. Data Collection and Pre-Processing: The first step in the pipeline is to collect and pre-process the data that will be used to train the model. This includes cleaning, normalizing, and transforming the data so that it can be used effectively by the model.
2. Model Training: Once the data is ready, it can be used to train a machine learning model using various algorithms such as supervised or unsupervised learning techniques. This step involves optimizing hyperparameters, selecting features, and evaluating performance metrics such as accuracy, precision, recall, and F1 score.
3. Model Evaluation: After training the model, it needs to be evaluated on unseen data (test set) to measure its performance before deployment into production. This step involves comparing different models based on their performance metrics and selecting the best performing one for deployment.
4. Model Deployment: After selecting a model for deployment, it needs to be deployed in an environment where it can be used for making predictions or decisions. This usually involves packaging up the model into a container such as Docker or Kubernetes and deploying it on cloud platforms such as AWS or GCP.
5. Monitoring & Maintenance: After deployment of the model in production, it needs to be monitored regularly for any changes in performance due to changing input data or other factors such as concept drift or dataset shift over time. It also needs to be maintained regularly by updating parameters or retraining when necessary in order to keep its performance optimal over time. We will go over each step In detail.
Implementing A Recommender System
One mathematical explanation of content-based recommender system is to use a vector space model to represent each item as a vector of features, and then compute the similarity between two items using a measure such as cosine similarity or Euclidean distance.
Cosine Similarity
Cosine similarity is a measure of how similar two vectors are in an inner product space. It is calculated by taking the dot product of the vectors divided by the product of their lengths. The result is a value between -1 and 1, where 1 means the vectors are identical, 0 means they are orthogonal (perpendicular), and -1 means they are opposite.
Cosine similarity can be used to compare documents in natural language processing (NLP), by representing each document as a vector of word counts or term frequencies. This way, cosine similarity can capture the semantic similarity between documents based on their word usage.
However, cosine similarity has some limitations when dealing with different topics, synonyms, antonyms, or word order. To overcome these issues, some extensions of cosine similarity have been proposed, such as soft cosine similarity (which considers the semantic meaning of words) or sentence vectorization (which considers the syntactic structure of sentences).
The mathematical symbols for cosine similarity are:
- The dot product: a · b = a1b1 + a2b2 + … + anbn
- The length (or norm) of a vector: ||a|| = √(a · a) = √((a1)² + (a2)² + … + (an)²
- The cosine similarity: cos(θ) = (a · b) / (||a|| ||b||)

In content-based recommender systems, cosine similarity is used to calculate how similar one item is to another. This can be used to recommend items that are similar to ones that have been previously rated or purchased by a user. For example, if a user has purchased an item A, then items with high cosine similarities to A will be recommended as potential purchases for that user.

Example
Here is an example of python function code for content-based recommender system using cosine similarity:
# Import libraries
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# Load data
movies = pd.read_csv("movies.csv")
# Define features to use
features = ["genres", "director", "actors", "plot"]
# Combine features into a single string
def combine_features(row):
return " ".join(row[feature] for feature in features)
movies["combined_features"] = movies.apply(combine_features, axis=1)
# Create TF-IDF matrix from combined features
# In my case I'm using TF-IDF, but you can use any Encoder.
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(movies["combined_features"])
# Compute cosine similarity matrix
cosine_sim = cosine_similarity(tfidf_matrix)
# Define a function to get similar movies based on an input movie title
def get_similar_movies(title):
# Get the index of the input movie
index = movies[movies["title"] == title].index[0]
# Get the similarity scores of all other movies with respect to the input movie
sim_scores = list(enumerate(cosine_sim[index]))
# Sort the movies by similarity scores in descending order
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
# Get the top 10 most similar movies (excluding the input movie itself)
sim_scores = sim_scores[1:11]
# Get the movie indices
movie_indices = [i[0] for i in sim_scores]
# Return the titles of the top 10 most similar movies
return movies["title"].iloc[movie_indices]
Result & Conclusion
The function gives back a list of 10 movies that are similar to the one you entered. Imagine using this on a website — whenever someone visits a movie’s page, they could see a section titled “Similar Movies” suggesting other movies they might like. This could work for all sorts of things, not just movies — like suggesting similar products on an online store or related topics in education.