├── src ├── __init__.py ├── tests │ ├── __init__.py │ ├── non_pers_tests.py │ ├── test_nn_content_based.py │ └── test_coll_filter.py ├── utils │ ├── __init__.py │ ├── tf_utils.py │ ├── style │ │ ├── __init__.py │ │ └── colours.py │ ├── solutions │ │ ├── __init__.py │ │ ├── download_files.sh │ │ ├── CollabFilter.py │ │ ├── dataset_reduction.py │ │ ├── serendipity_recommender.py │ │ ├── als.py │ │ └── knn_recommender.py │ ├── exceptions.py │ ├── data_split.py │ ├── data_utils.py │ ├── collab_filter.py │ ├── non_pers_rec.py │ └── recsysNN_utils.py ├── FinalProject │ ├── __init__.py │ ├── project_2025 │ │ ├── proposed_solution │ │ │ └── __init__.py │ │ └── README.md │ ├── project_2024 │ │ └── README.md │ ├── README.md │ └── project_2023 │ │ ├── proposedSolution │ │ └── README.md │ │ └── README.md ├── exercises │ ├── __init__.py │ ├── BookRecommender.ipynb │ └── HybridNN.ipynb ├── old_lectures │ ├── tests │ │ ├── __init__.py │ │ ├── non_pers_tests.py │ │ ├── test_nn_content_based.py │ │ └── test_coll_filter.py │ ├── utils │ │ ├── __init__.py │ │ ├── tf_utils.py │ │ ├── style │ │ │ ├── __init__.py │ │ │ └── colours.py │ │ ├── solutions │ │ │ ├── __init__.py │ │ │ ├── download_files.sh │ │ │ ├── CollabFilter.py │ │ │ ├── dataset_reduction.py │ │ │ ├── serendipity_recommender.py │ │ │ ├── als.py │ │ │ └── knn_recommender.py │ │ ├── exceptions.py │ │ ├── data_split.py │ │ ├── data_utils.py │ │ ├── collab_filter.py │ │ ├── non_pers_rec.py │ │ └── recsysNN_utils.py │ ├── 11.DeepLove.ipynb │ └── 01.Introduction.ipynb ├── 06.HybridRecommenders.ipynb ├── README.md ├── 04.ContentBasedFiltering.ipynb └── 01.Introduction.ipynb ├── images ├── drawing.png ├── RecSysNN.png ├── bpr_model.png ├── film_reel.png ├── course-logo.png ├── distmatrix.PNG ├── film_award.png ├── film_filter.png ├── film_rating.png ├── movie_camera.png ├── ColabFilterUse.PNG ├── ColabFilterLearn.PNG ├── film_man_action.png ├── film_movie_camera.png └── film_strip_vertical.png ├── environment.yml ├── _config.yml ├── .gitignore ├── scripts ├── download_files.sh └── generate_synthetic_data.sh ├── requirements.txt ├── .github └── FUNDING.yml ├── README.md ├── README_IT.md └── LICENSE /src/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/utils/tf_utils.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/FinalProject/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/exercises/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/utils/style/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/utils/solutions/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/old_lectures/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/old_lectures/utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/old_lectures/utils/tf_utils.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/old_lectures/utils/style/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/old_lectures/utils/solutions/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/FinalProject/project_2025/proposed_solution/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/drawing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/drawing.png -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: recommender-system-lectures 2 | dependencies: 3 | - python=3.9 4 | - tensorflow=2.9.3 5 | -------------------------------------------------------------------------------- /images/RecSysNN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/RecSysNN.png -------------------------------------------------------------------------------- /images/bpr_model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/bpr_model.png -------------------------------------------------------------------------------- /images/film_reel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/film_reel.png -------------------------------------------------------------------------------- /images/course-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/course-logo.png -------------------------------------------------------------------------------- /images/distmatrix.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/distmatrix.PNG -------------------------------------------------------------------------------- /images/film_award.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/film_award.png -------------------------------------------------------------------------------- /images/film_filter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/film_filter.png -------------------------------------------------------------------------------- /images/film_rating.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/film_rating.png -------------------------------------------------------------------------------- /images/movie_camera.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/movie_camera.png -------------------------------------------------------------------------------- /images/ColabFilterUse.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/ColabFilterUse.PNG -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | title: Recommender Systems Course 2 | theme: jekyll-theme-architect 3 | show_downloads: true 4 | markdown: kramdown 5 | -------------------------------------------------------------------------------- /images/ColabFilterLearn.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/ColabFilterLearn.PNG -------------------------------------------------------------------------------- /images/film_man_action.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/film_man_action.png -------------------------------------------------------------------------------- /images/film_movie_camera.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/film_movie_camera.png -------------------------------------------------------------------------------- /images/film_strip_vertical.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oscar-defelice/Recommender-Systems-Course/HEAD/images/film_strip_vertical.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # macOS 2 | .DS_Store 3 | .AppleDouble 4 | .Trashes 5 | .vscode 6 | 7 | # Notebook and python auxiliary files 8 | .ipynb_checkpoints 9 | __pycache__ 10 | 11 | # data folders 12 | data 13 | 14 | # models files 15 | models 16 | 17 | # logs files 18 | logs 19 | -------------------------------------------------------------------------------- /scripts/download_files.sh: -------------------------------------------------------------------------------- 1 | %%bash 2 | if [ ! -d "../data/movielens_complete" ]; then 3 | wget http://files.grouplens.org/datasets/movielens/ml-latest.zip 4 | mkdir -p ../data/movielens_complete 5 | unzip -o ml-latest.zip -d ../data/movielens_complete 6 | else 7 | echo "Data already downloaded" 8 | fi 9 | -------------------------------------------------------------------------------- /src/utils/exceptions.py: -------------------------------------------------------------------------------- 1 | """Exceptions module to collect user-defined exception classes""" 2 | 3 | 4 | class Error(Exception): 5 | """Base class for other exceptions.""" 6 | 7 | pass 8 | 9 | 10 | class NotFittedError(Error): 11 | """Raised when the model has not been fitted.""" 12 | 13 | pass 14 | -------------------------------------------------------------------------------- /src/utils/solutions/download_files.sh: -------------------------------------------------------------------------------- 1 | %%bash 2 | if [ ! -d "../data/movielens_complete" ]; then 3 | wget http://files.grouplens.org/datasets/movielens/ml-latest.zip 4 | mkdir -p ../data/movielens_complete 5 | unzip -o ml-latest.zip -d ../data/movielens_complete 6 | else 7 | echo "Data already downloaded" 8 | fi 9 | -------------------------------------------------------------------------------- /src/old_lectures/utils/exceptions.py: -------------------------------------------------------------------------------- 1 | """Exceptions module to collect user-defined exception classes""" 2 | 3 | 4 | class Error(Exception): 5 | """Base class for other exceptions.""" 6 | 7 | pass 8 | 9 | 10 | class NotFittedError(Error): 11 | """Raised when the model has not been fitted.""" 12 | 13 | pass 14 | -------------------------------------------------------------------------------- /src/old_lectures/utils/solutions/download_files.sh: -------------------------------------------------------------------------------- 1 | %%bash 2 | if [ ! -d "../data/movielens_complete" ]; then 3 | wget http://files.grouplens.org/datasets/movielens/ml-latest.zip 4 | mkdir -p ../data/movielens_complete 5 | unzip -o ml-latest.zip -d ../data/movielens_complete 6 | else 7 | echo "Data already downloaded" 8 | fi 9 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pandas==2.2.3 2 | tensorflow==2.14.1 3 | matplotlib==3.9.4 4 | scipy==1.13.1 5 | scikit-learn==1.1.3 6 | pydotplus==2.0.2 7 | pydot==1.4.2 8 | graphviz==0.16 9 | pydot-ng==2.0.0 10 | imageio==2.9.0 11 | nltk==3.6.6 12 | seaborn==0.13.2 13 | tensorflow-probability==0.12.1 14 | prompt-toolkit==3.0.2 15 | tabulate==0.9.0 16 | pyspark==3.3.2 -------------------------------------------------------------------------------- /src/utils/style/colours.py: -------------------------------------------------------------------------------- 1 | """Module to collect colours objects in order to print coloured logger messages. 2 | 3 | Examples 4 | -------- 5 | print(Colours.RED + "This message will appear in red." + Colours.ENDC) 6 | """ 7 | 8 | 9 | class Colour: 10 | RED = "\033[31m" 11 | GREEN = "\033[32m" 12 | YELLOW = "\033[33m" 13 | BLUE = "\033[34m" 14 | 15 | ENDC = "\033[m" 16 | -------------------------------------------------------------------------------- /src/old_lectures/utils/style/colours.py: -------------------------------------------------------------------------------- 1 | """Module to collect colours objects in order to print coloured logger messages. 2 | 3 | Examples 4 | -------- 5 | print(Colours.RED + "This message will appear in red." + Colours.ENDC) 6 | """ 7 | 8 | 9 | class Colour: 10 | RED = "\033[31m" 11 | GREEN = "\033[32m" 12 | YELLOW = "\033[33m" 13 | BLUE = "\033[34m" 14 | 15 | ENDC = "\033[m" 16 | -------------------------------------------------------------------------------- /src/utils/solutions/CollabFilter.py: -------------------------------------------------------------------------------- 1 | # Set Initial Parameters (W, X), use tf.Variable to track these variables 2 | tf.random.set_seed(1234) # for consistent results 3 | W = tf.Variable(tf.random.normal((num_users, num_features), dtype=tf.float64), name="W") 4 | X = tf.Variable( 5 | tf.random.normal((num_movies, num_features), dtype=tf.float64), name="X" 6 | ) 7 | b = tf.Variable(tf.random.normal((1, num_users), dtype=tf.float64), name="b") 8 | 9 | # Instantiate an optimizer. 10 | optimizer = tf.keras.optimizers.Adam(learning_rate=1e-1) 11 | -------------------------------------------------------------------------------- /src/old_lectures/utils/solutions/CollabFilter.py: -------------------------------------------------------------------------------- 1 | # Set Initial Parameters (W, X), use tf.Variable to track these variables 2 | tf.random.set_seed(1234) # for consistent results 3 | W = tf.Variable(tf.random.normal((num_users, num_features), dtype=tf.float64), name="W") 4 | X = tf.Variable( 5 | tf.random.normal((num_movies, num_features), dtype=tf.float64), name="X" 6 | ) 7 | b = tf.Variable(tf.random.normal((1, num_users), dtype=tf.float64), name="b") 8 | 9 | # Instantiate an optimizer. 10 | optimizer = tf.keras.optimizers.Adam(learning_rate=1e-1) 11 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [oscar-defelice] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: oscardefelice # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: ["https://www.buymeacoffee.com/oscardefelice"] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /src/tests/non_pers_tests.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from utils.non_pers_rec import get_recent_liked_movie as correct_like_fn 3 | from utils.non_pers_rec import get_genre as correct_genre_fn 4 | 5 | 6 | def test_get_recent_liked_movie(target): 7 | usr_test = 3 8 | a = target(usr_test) 9 | atf = correct_like_fn(usr_test) 10 | 11 | assert a == atf, f"Wrong values. Expected {atf}, got {a}" 12 | 13 | usr_test = 74 14 | a = target(usr_test) 15 | atf = correct_like_fn(usr_test) 16 | 17 | assert a == atf, f"Wrong values. Expected {atf}, got {a}" 18 | 19 | print("\033[92m All tests passed.") 20 | 21 | 22 | def test_get_movie_genre(target): 23 | usr_test = 2 24 | a = target(usr_test) 25 | atf = correct_genre_fn(usr_test) 26 | 27 | assert isinstance(a, list), f"Wrong type. Expected list, got {type(a)}" 28 | assert a == atf, f"Wrong values. Expected {atf}, got {a}" 29 | 30 | print("\033[92m All tests passed.") 31 | -------------------------------------------------------------------------------- /src/old_lectures/tests/non_pers_tests.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from utils.non_pers_rec import get_recent_liked_movie as correct_like_fn 3 | from utils.non_pers_rec import get_genre as correct_genre_fn 4 | 5 | 6 | def test_get_recent_liked_movie(target): 7 | usr_test = 3 8 | a = target(usr_test) 9 | atf = correct_like_fn(usr_test) 10 | 11 | assert a == atf, f"Wrong values. Expected {atf}, got {a}" 12 | 13 | usr_test = 74 14 | a = target(usr_test) 15 | atf = correct_like_fn(usr_test) 16 | 17 | assert a == atf, f"Wrong values. Expected {atf}, got {a}" 18 | 19 | print("\033[92m All tests passed.") 20 | 21 | 22 | def test_get_movie_genre(target): 23 | usr_test = 2 24 | a = target(usr_test) 25 | atf = correct_genre_fn(usr_test) 26 | 27 | assert isinstance(a, list), f"Wrong type. Expected list, got {type(a)}" 28 | assert a == atf, f"Wrong values. Expected {atf}, got {a}" 29 | 30 | print("\033[92m All tests passed.") 31 | -------------------------------------------------------------------------------- /src/utils/data_split.py: -------------------------------------------------------------------------------- 1 | """Module to handle data splitting""" 2 | 3 | import numpy as np 4 | import random 5 | from typing import Tuple, Union 6 | 7 | 8 | def split_ratings( 9 | ratings: np.ndarray, val_size: Union[float, int] 10 | ) -> Tuple[np.ndarray, np.ndarray]: 11 | """Function to create a validation set of ratings out of a sparse matrix 12 | 13 | Parameters 14 | ---------- 15 | ratings : np.ndarray 16 | The matrix of ratings, can be sparse, full of zeros or nan values. 17 | val_size : float or int 18 | The size of the validation set. 19 | If float, the size is expressed in percentage of total size of the ratings array. 20 | if int, the size is expressed in raw number ratings in the validation set. 21 | 22 | Returns 23 | ------- 24 | Tuple[np.ndarray, np.ndarray] 25 | The tuple of training and validation ratings. 26 | """ 27 | # Get the couples of indices with significant values 28 | rows, cols = np.where(ratings > 0) 29 | val_ratings = np.zeros(ratings.shape) 30 | train_ratings = ratings.copy() 31 | 32 | if val_size < 1: # Hence it is a percentage 33 | val_size = int(rows * val_size) 34 | 35 | val_ids = random.sample(range(len(rows)), val_size) 36 | 37 | for row, col in zip(rows[val_ids], cols[val_ids]): 38 | train_ratings[row, col] = 0 39 | val_ratings[row, col] = ratings[row, col] 40 | 41 | return train_ratings, val_ratings 42 | -------------------------------------------------------------------------------- /src/old_lectures/utils/data_split.py: -------------------------------------------------------------------------------- 1 | """Module to handle data splitting""" 2 | 3 | import numpy as np 4 | import random 5 | from typing import Tuple, Union 6 | 7 | 8 | def split_ratings( 9 | ratings: np.ndarray, val_size: Union[float, int] 10 | ) -> Tuple[np.ndarray, np.ndarray]: 11 | """Function to create a validation set of ratings out of a sparse matrix 12 | 13 | Parameters 14 | ---------- 15 | ratings : np.ndarray 16 | The matrix of ratings, can be sparse, full of zeros or nan values. 17 | val_size : float or int 18 | The size of the validation set. 19 | If float, the size is expressed in percentage of total size of the ratings array. 20 | if int, the size is expressed in raw number ratings in the validation set. 21 | 22 | Returns 23 | ------- 24 | Tuple[np.ndarray, np.ndarray] 25 | The tuple of training and validation ratings. 26 | """ 27 | # Get the couples of indices with significant values 28 | rows, cols = np.where(ratings > 0) 29 | val_ratings = np.zeros(ratings.shape) 30 | train_ratings = ratings.copy() 31 | 32 | if val_size < 1: # Hence it is a percentage 33 | val_size = int(rows * val_size) 34 | 35 | val_ids = random.sample(range(len(rows)), val_size) 36 | 37 | for row, col in zip(rows[val_ids], cols[val_ids]): 38 | train_ratings[row, col] = 0 39 | val_ratings[row, col] = ratings[row, col] 40 | 41 | return train_ratings, val_ratings 42 | -------------------------------------------------------------------------------- /src/old_lectures/11.DeepLove.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# Introduction to Recommender Systems\n", 9 | "\n", 10 | "

\n", 11 | " \"cover-image\"\n", 12 | "

\n", 13 | "\n", 14 | "---\n", 15 | "\n", 16 | "# DeepLove: A movie recommender system for couples\n", 17 | "\n", 18 | "The main idea here is to play with the idea of a recommender system for couples. The idea is to recommend movies to couples based on their preferences.\n", 19 | "The recommender system will be based on the average of users preferences, trying to recommend the most compatible movies for both users in the couple.\n", 20 | "\n", 21 | "We will implement the recommender system by steps:\n", 22 | "\n", 23 | "1. Creation of a function to get the average of two movies.\n", 24 | "2. Creation of a function to get the most compatible movies for a user.\n", 25 | "3. Creation of a method to encode users features.\n", 26 | "4. Put all together and create a recommender system for couples.\n" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": null, 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [] 35 | } 36 | ], 37 | "metadata": { 38 | "kernelspec": { 39 | "display_name": "Python 3", 40 | "language": "python", 41 | "name": "python3" 42 | }, 43 | "language_info": { 44 | "name": "python", 45 | "version": "3.9.6" 46 | }, 47 | "orig_nbformat": 4, 48 | "vscode": { 49 | "interpreter": { 50 | "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" 51 | } 52 | } 53 | }, 54 | "nbformat": 4, 55 | "nbformat_minor": 2 56 | } 57 | -------------------------------------------------------------------------------- /src/06.HybridRecommenders.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Introduction to Recommender Systems\n", 8 | "\n", 9 | "

\n", 10 | " \"cover-image\"\n", 11 | "

\n", 12 | "\n", 13 | "---\n", 14 | "\n", 15 | "# Hybrid Recommenders\n", 16 | "\n", 17 | "Hybrid recommender systems combine multiple recommendation approaches to leverage their individual strengths and overcome their limitations. Common hybrid approaches include:\n", 18 | "\n", 19 | "- Weighted: Combines scores from different recommenders using weighted averages\n", 20 | "- Switching: Chooses between different recommenders based on the context\n", 21 | "- Feature Combination: Uses features from multiple sources as input to a single recommender\n", 22 | "- Cascade: Applies recommenders sequentially, with each refining previous recommendations\n", 23 | "- Feature Augmentation: One recommender's output becomes input features for another\n", 24 | "\n", 25 | "The main benefits of hybrid recommenders include:\n", 26 | "- Better accuracy by combining complementary approaches\n", 27 | "- Reduced cold-start problems by using multiple data sources\n", 28 | "- More robust recommendations that are less sensitive to data sparsity\n", 29 | "- Ability to capture both user preferences and item characteristics" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "metadata": {}, 36 | "outputs": [], 37 | "source": [] 38 | } 39 | ], 40 | "metadata": { 41 | "kernelspec": { 42 | "display_name": "rec-sys", 43 | "language": "python", 44 | "name": "python3" 45 | }, 46 | "language_info": { 47 | "name": "python", 48 | "version": "3.9.21" 49 | } 50 | }, 51 | "nbformat": 4, 52 | "nbformat_minor": 2 53 | } 54 | -------------------------------------------------------------------------------- /scripts/generate_synthetic_data.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Output file 4 | OUTPUT_FILE="synthetic_patients.csv" 5 | 6 | # Default number of synthetic patients 7 | NUM_PATIENTS=100 8 | 9 | # Define arrays of possible values 10 | GENDERS=("Male" "Female" "Non-Binary") 11 | CONDITIONS=("Diabetes" "Hypertension" "Asthma" "Arthritis" "Depression" "Obesity" "No Chronic Condition") 12 | PREFERRED_FORMATS=("Articles" "Videos" "Podcasts" "Infographics") 13 | 14 | # Help function 15 | show_help() { 16 | echo "Usage: $0 [OPTIONS]" 17 | echo "" 18 | echo "Generate a synthetic patient dataset." 19 | echo "" 20 | echo "Options:" 21 | echo " -n, --num-patients Specify the number of patients to generate (default: 100)." 22 | echo " -o, --output Specify the output CSV file (default: synthetic_patients.csv)." 23 | echo " -h, --help Show this help message and exit." 24 | echo "" 25 | exit 0 26 | } 27 | 28 | # Parse command-line arguments 29 | while [[ "$#" -gt 0 ]]; do 30 | case $1 in 31 | -n | --num-patients) 32 | NUM_PATIENTS="$2" 33 | shift 34 | ;; 35 | -o | --output) 36 | OUTPUT_FILE="$2" 37 | shift 38 | ;; 39 | -h | --help) show_help ;; 40 | *) 41 | echo "Unknown option: $1" 42 | show_help 43 | ;; 44 | esac 45 | shift 46 | done 47 | 48 | # Write header to CSV 49 | echo "PatientID,Age,Gender,Condition,PreferredFormat" >"$OUTPUT_FILE" 50 | 51 | # Generate random patients 52 | for ((i = 1; i <= NUM_PATIENTS; i++)); do 53 | # Randomly generate values 54 | AGE=$((RANDOM % 60 + 18)) # Age between 18 and 77 55 | GENDER=${GENDERS[$RANDOM % ${#GENDERS[@]}]} 56 | CONDITION=${CONDITIONS[$RANDOM % ${#CONDITIONS[@]}]} 57 | FORMAT=${PREFERRED_FORMATS[$RANDOM % ${#PREFERRED_FORMATS[@]}]} 58 | 59 | # Write patient data to CSV 60 | echo "$i,$AGE,$GENDER,$CONDITION,$FORMAT" >>"$OUTPUT_FILE" 61 | done 62 | 63 | echo "✅ Synthetic patient data generated: $OUTPUT_FILE" 64 | -------------------------------------------------------------------------------- /src/tests/test_nn_content_based.py: -------------------------------------------------------------------------------- 1 | """Tests for the content-based recommender implementation.""" 2 | from tensorflow.keras.activations import relu, linear 3 | from tensorflow.keras.layers import Dense 4 | 5 | import numpy as np 6 | 7 | 8 | def test_tower(target): 9 | num_outputs = 32 10 | i = 0 11 | assert ( 12 | len(target.layers) == 3 13 | ), f"Wrong number of layers. Expected 3 but got {len(target.layers)}" 14 | expected = [ 15 | [Dense, [None, 256], relu], 16 | [Dense, [None, 128], relu], 17 | [Dense, [None, num_outputs], linear], 18 | ] 19 | 20 | for layer in target.layers: 21 | assert ( 22 | type(layer) == expected[i][0] 23 | ), f"Wrong type in layer {i}. Expected {expected[i][0]} but got {type(layer)}" 24 | assert ( 25 | layer.output.shape.as_list() == expected[i][1] 26 | ), f"Wrong number of units in layer {i}. Expected {expected[i][1]} but got {layer.output.shape.as_list()}" 27 | assert ( 28 | layer.activation == expected[i][2] 29 | ), f"Wrong activation in layer {i}. Expected {expected[i][2]} but got {layer.activation}" 30 | i = i + 1 31 | 32 | print("\033[92mAll tests passed!") 33 | 34 | 35 | def test_sq_dist(target): 36 | a1 = np.array([1.0, 2.0, 3.0]) 37 | b1 = np.array([1.0, 2.0, 3.0]) 38 | c1 = target(a1, b1) 39 | a2 = np.array([1.1, 2.1, 3.1]) 40 | b2 = np.array([1.0, 2.0, 3.0]) 41 | c2 = target(a2, b2) 42 | a3 = np.array([0, 1]) 43 | b3 = np.array([1, 0]) 44 | c3 = target(a3, b3) 45 | a4 = np.array([1, 1, 1, 1, 1]) 46 | b4 = np.array([0, 0, 0, 0, 0]) 47 | c4 = target(a4, b4) 48 | 49 | assert np.isclose(c1, 0), f"Wrong value. Expected {0}, got {c1}" 50 | assert np.isclose(c2, 0.03), f"Wrong value. Expected {0.03}, got {c2}" 51 | assert np.isclose(c3, 2), f"Wrong value. Expected {2}, got {c3}" 52 | assert np.isclose(c4, 5), f"Wrong value. Expected {5}, got {c4}" 53 | 54 | print("\033[92mAll tests passed!") 55 | -------------------------------------------------------------------------------- /src/old_lectures/tests/test_nn_content_based.py: -------------------------------------------------------------------------------- 1 | """Tests for the content-based recommender implementation.""" 2 | from tensorflow.keras.activations import relu, linear 3 | from tensorflow.keras.layers import Dense 4 | 5 | import numpy as np 6 | 7 | 8 | def test_tower(target): 9 | num_outputs = 32 10 | i = 0 11 | assert ( 12 | len(target.layers) == 3 13 | ), f"Wrong number of layers. Expected 3 but got {len(target.layers)}" 14 | expected = [ 15 | [Dense, [None, 256], relu], 16 | [Dense, [None, 128], relu], 17 | [Dense, [None, num_outputs], linear], 18 | ] 19 | 20 | for layer in target.layers: 21 | assert ( 22 | type(layer) == expected[i][0] 23 | ), f"Wrong type in layer {i}. Expected {expected[i][0]} but got {type(layer)}" 24 | assert ( 25 | layer.output.shape.as_list() == expected[i][1] 26 | ), f"Wrong number of units in layer {i}. Expected {expected[i][1]} but got {layer.output.shape.as_list()}" 27 | assert ( 28 | layer.activation == expected[i][2] 29 | ), f"Wrong activation in layer {i}. Expected {expected[i][2]} but got {layer.activation}" 30 | i = i + 1 31 | 32 | print("\033[92mAll tests passed!") 33 | 34 | 35 | def test_sq_dist(target): 36 | a1 = np.array([1.0, 2.0, 3.0]) 37 | b1 = np.array([1.0, 2.0, 3.0]) 38 | c1 = target(a1, b1) 39 | a2 = np.array([1.1, 2.1, 3.1]) 40 | b2 = np.array([1.0, 2.0, 3.0]) 41 | c2 = target(a2, b2) 42 | a3 = np.array([0, 1]) 43 | b3 = np.array([1, 0]) 44 | c3 = target(a3, b3) 45 | a4 = np.array([1, 1, 1, 1, 1]) 46 | b4 = np.array([0, 0, 0, 0, 0]) 47 | c4 = target(a4, b4) 48 | 49 | assert np.isclose(c1, 0), f"Wrong value. Expected {0}, got {c1}" 50 | assert np.isclose(c2, 0.03), f"Wrong value. Expected {0.03}, got {c2}" 51 | assert np.isclose(c3, 2), f"Wrong value. Expected {2}, got {c3}" 52 | assert np.isclose(c4, 5), f"Wrong value. Expected {5}, got {c4}" 53 | 54 | print("\033[92mAll tests passed!") 55 | -------------------------------------------------------------------------------- /src/utils/data_utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | 4 | 5 | def load_data(): 6 | df_rating = pd.read_csv( 7 | "http://files.grouplens.org/datasets/movielens/ml-100k/u1.base", 8 | sep="\t", 9 | engine="python", 10 | header=None, 11 | ) 12 | df_rating.columns = ["UserId", "MovieId", "Rating", "Timestamp"] 13 | df_rating_test = pd.read_csv( 14 | "http://files.grouplens.org/datasets/movielens/ml-100k/u1.test", 15 | sep="\t", 16 | engine="python", 17 | header=None, 18 | ) 19 | 20 | df_users = pd.read_csv( 21 | "http://files.grouplens.org/datasets/movielens/ml-100k/u.user", 22 | sep="|", 23 | engine="python", 24 | header=None, 25 | ) 26 | df_users.columns = ["UserId", "Age", "Gender", "Occupation", "ZipCode"] 27 | df_users.set_index("UserId", inplace=True) 28 | df_items = pd.read_csv( 29 | "http://files.grouplens.org/datasets/movielens/ml-100k/u.item", 30 | sep="|", 31 | engine="python", 32 | encoding="ISO-8859-1", 33 | header=None, 34 | ) 35 | df_items.columns = [ 36 | "MovieId", 37 | "Title", 38 | "Date", 39 | "VideoReleaseDate", 40 | "Url", 41 | "unknown", 42 | "Action", 43 | "Adventure", 44 | "Animation", 45 | "Children", 46 | "Comedy", 47 | "Crime", 48 | "Documentary", 49 | "Drama", 50 | "Fantasy", 51 | "Film-Noir", 52 | "Horror", 53 | "Musical", 54 | "Mystery", 55 | "Romance", 56 | "Sci-Fi", 57 | "Thriller", 58 | "War", 59 | "Western", 60 | ] 61 | df_items.set_index("MovieId", inplace=True) 62 | 63 | # Pivot rating table in order to get rating matrix 64 | df_matrix = df_rating.pivot(index="MovieId", columns="UserId", values="Rating") 65 | 66 | n_users = len(df_users) 67 | n_items = len(df_items) 68 | 69 | return df_rating, df_rating_test, df_users, df_items, df_matrix, n_users, n_items 70 | -------------------------------------------------------------------------------- /src/utils/solutions/dataset_reduction.py: -------------------------------------------------------------------------------- 1 | """Solution module for the dataset reduction exercise.""" 2 | 3 | """ 4 | What This Solution Does 5 | Filters out movies with fewer than 50 ratings 6 | Filters out users who rated fewer than 20 movies 7 | Compares dataset size before and after reduction 8 | Plots rating distributions to check if the dataset remains representative 9 | This method removes sparsity while keeping useful data, making it more efficient for training recommenders. 10 | """ 11 | 12 | import pandas as pd 13 | 14 | # Load the dataset (MovieLens 100K) 15 | ratings = pd.read_csv( 16 | "ml-100k/u.data", sep="\t", names=["UserId", "MovieId", "Rating", "Timestamp"] 17 | ) 18 | 19 | # Step 1: Count how many ratings each movie received 20 | movie_counts = ratings.groupby("MovieId").size() 21 | 22 | # Step 2: Count how many ratings each user gave 23 | user_counts = ratings.groupby("UserId").size() 24 | 25 | # Step 3: Apply filters 26 | min_movie_ratings = 50 # Keep movies with at least 50 ratings 27 | min_user_ratings = 20 # Keep users who rated at least 20 movies 28 | 29 | filtered_ratings = ratings[ 30 | (ratings["MovieId"].isin(movie_counts[movie_counts >= min_movie_ratings].index)) 31 | & (ratings["UserId"].isin(user_counts[user_counts >= min_user_ratings].index)) 32 | ] 33 | 34 | # Step 4: Compare dataset sizes before and after reduction 35 | print(f"Original dataset size: {ratings.shape[0]}") 36 | print(f"Reduced dataset size: {filtered_ratings.shape[0]}") 37 | print( 38 | f"Reduction percentage: {(1 - filtered_ratings.shape[0] / ratings.shape[0]) * 100:.2f}%" 39 | ) 40 | 41 | # Step 5: Show distribution of ratings before and after reduction 42 | import matplotlib.pyplot as plt 43 | 44 | plt.figure(figsize=(10, 5)) 45 | plt.hist(ratings["Rating"], bins=5, alpha=0.5, label="Original", density=True) 46 | plt.hist(filtered_ratings["Rating"], bins=5, alpha=0.5, label="Reduced", density=True) 47 | plt.legend() 48 | plt.xlabel("Rating") 49 | plt.ylabel("Density") 50 | plt.title("Distribution of Ratings Before and After Reduction") 51 | plt.show() 52 | -------------------------------------------------------------------------------- /src/old_lectures/utils/solutions/dataset_reduction.py: -------------------------------------------------------------------------------- 1 | """Solution module for the dataset reduction exercise.""" 2 | 3 | """ 4 | What This Solution Does 5 | Filters out movies with fewer than 50 ratings 6 | Filters out users who rated fewer than 20 movies 7 | Compares dataset size before and after reduction 8 | Plots rating distributions to check if the dataset remains representative 9 | This method removes sparsity while keeping useful data, making it more efficient for training recommenders. 10 | """ 11 | 12 | import pandas as pd 13 | 14 | # Load the dataset (MovieLens 100K) 15 | ratings = pd.read_csv( 16 | "ml-100k/u.data", sep="\t", names=["UserId", "MovieId", "Rating", "Timestamp"] 17 | ) 18 | 19 | # Step 1: Count how many ratings each movie received 20 | movie_counts = ratings.groupby("MovieId").size() 21 | 22 | # Step 2: Count how many ratings each user gave 23 | user_counts = ratings.groupby("UserId").size() 24 | 25 | # Step 3: Apply filters 26 | min_movie_ratings = 50 # Keep movies with at least 50 ratings 27 | min_user_ratings = 20 # Keep users who rated at least 20 movies 28 | 29 | filtered_ratings = ratings[ 30 | (ratings["MovieId"].isin(movie_counts[movie_counts >= min_movie_ratings].index)) 31 | & (ratings["UserId"].isin(user_counts[user_counts >= min_user_ratings].index)) 32 | ] 33 | 34 | # Step 4: Compare dataset sizes before and after reduction 35 | print(f"Original dataset size: {ratings.shape[0]}") 36 | print(f"Reduced dataset size: {filtered_ratings.shape[0]}") 37 | print( 38 | f"Reduction percentage: {(1 - filtered_ratings.shape[0] / ratings.shape[0]) * 100:.2f}%" 39 | ) 40 | 41 | # Step 5: Show distribution of ratings before and after reduction 42 | import matplotlib.pyplot as plt 43 | 44 | plt.figure(figsize=(10, 5)) 45 | plt.hist(ratings["Rating"], bins=5, alpha=0.5, label="Original", density=True) 46 | plt.hist(filtered_ratings["Rating"], bins=5, alpha=0.5, label="Reduced", density=True) 47 | plt.legend() 48 | plt.xlabel("Rating") 49 | plt.ylabel("Density") 50 | plt.title("Distribution of Ratings Before and After Reduction") 51 | plt.show() 52 | -------------------------------------------------------------------------------- /src/old_lectures/utils/data_utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | 4 | 5 | def load_data(): 6 | df_rating = pd.read_csv( 7 | "http://files.grouplens.org/datasets/movielens/ml-100k/u1.base", 8 | sep="\t", 9 | engine="python", 10 | header=None, 11 | ) 12 | df_rating.columns = ["UserId", "MovieId", "Rating", "Timestamp"] 13 | df_rating_test = pd.read_csv( 14 | "http://files.grouplens.org/datasets/movielens/ml-100k/u1.test", 15 | sep="\t", 16 | engine="python", 17 | header=None, 18 | ) 19 | 20 | df_users = pd.read_csv( 21 | "http://files.grouplens.org/datasets/movielens/ml-100k/u.user", 22 | sep="|", 23 | engine="python", 24 | header=None, 25 | ) 26 | df_users.columns = ["UserId", "Age", "Gender", "Occupation", "ZipCode"] 27 | df_users.set_index("UserId", inplace=True) 28 | df_items = pd.read_csv( 29 | "http://files.grouplens.org/datasets/movielens/ml-100k/u.item", 30 | sep="|", 31 | engine="python", 32 | encoding="ISO-8859-1", 33 | header=None, 34 | ) 35 | df_items.columns = [ 36 | "MovieId", 37 | "Title", 38 | "Date", 39 | "VideoReleaseDate", 40 | "Url", 41 | "unknown", 42 | "Action", 43 | "Adventure", 44 | "Animation", 45 | "Children", 46 | "Comedy", 47 | "Crime", 48 | "Documentary", 49 | "Drama", 50 | "Fantasy", 51 | "Film-Noir", 52 | "Horror", 53 | "Musical", 54 | "Mystery", 55 | "Romance", 56 | "Sci-Fi", 57 | "Thriller", 58 | "War", 59 | "Western", 60 | ] 61 | df_items.set_index("MovieId", inplace=True) 62 | 63 | # Pivot rating table in order to get rating matrix 64 | df_matrix = df_rating.pivot(index="MovieId", columns="UserId", values="Rating") 65 | 66 | n_users = len(df_users) 67 | n_items = len(df_items) 68 | 69 | return df_rating, df_rating_test, df_users, df_items, df_matrix, n_users, n_items 70 | -------------------------------------------------------------------------------- /src/utils/solutions/serendipity_recommender.py: -------------------------------------------------------------------------------- 1 | """Solution script for serendipity recommender""" 2 | 3 | import pandas as pd 4 | 5 | # Load datasets 6 | df_ratings = pd.read_csv("ratings.csv") # Ensure this file is in the working directory 7 | df_movies = pd.read_csv("movies.csv", index_col="MovieId") # MovieId as index 8 | 9 | # Step 1: Compute Movie Popularity (Number of Ratings) 10 | movie_popularity = df_ratings.groupby("MovieId").size().reset_index(name="NumRatings") 11 | 12 | # Step 2: Compute Average Rating for Each Movie 13 | movie_avg_rating = ( 14 | df_ratings.groupby("MovieId")["Rating"].mean().reset_index(name="AvgRating") 15 | ) 16 | 17 | # Step 3: Merge Popularity and Ratings with Movie Titles 18 | movies_stats = movie_popularity.merge(movie_avg_rating, on="MovieId") 19 | movies_stats = movies_stats.merge( 20 | df_movies[["Title"]], left_on="MovieId", right_index=True 21 | ) 22 | 23 | # Step 4: Define Serendipity Criteria 24 | # Popular Movies: High number of ratings (e.g., top 10% most rated) 25 | popularity_threshold = movies_stats["NumRatings"].quantile(0.90) 26 | popular_movies = movies_stats[movies_stats["NumRatings"] >= popularity_threshold] 27 | 28 | # Hidden Gems: High rating but low number of ratings (e.g., bottom 50% in popularity) 29 | hidden_gems = movies_stats[ 30 | (movies_stats["NumRatings"] <= movies_stats["NumRatings"].median()) 31 | & (movies_stats["AvgRating"] >= movies_stats["AvgRating"].quantile(0.75)) 32 | ] 33 | 34 | # Step 5: Mix Popular and Serendipitous Movies 35 | num_recommendations = 10 # Set the number of final recommendations 36 | popular_sample = popular_movies.sample( 37 | min(len(popular_movies), num_recommendations // 2) 38 | ) 39 | hidden_gems_sample = hidden_gems.sample(min(len(hidden_gems), num_recommendations // 2)) 40 | 41 | serendipity_recommendations = ( 42 | pd.concat([popular_sample, hidden_gems_sample]) 43 | .sample(frac=1) 44 | .reset_index(drop=True) 45 | ) 46 | 47 | # Step 6: Display Recommendations 48 | print("🎬 Serendipity-Based Movie Recommendations 🎬") 49 | print(serendipity_recommendations[["Title", "NumRatings", "AvgRating"]]) 50 | -------------------------------------------------------------------------------- /src/old_lectures/utils/solutions/serendipity_recommender.py: -------------------------------------------------------------------------------- 1 | """Solution script for serendipity recommender""" 2 | 3 | import pandas as pd 4 | 5 | # Load datasets 6 | df_ratings = pd.read_csv("ratings.csv") # Ensure this file is in the working directory 7 | df_movies = pd.read_csv("movies.csv", index_col="MovieId") # MovieId as index 8 | 9 | # Step 1: Compute Movie Popularity (Number of Ratings) 10 | movie_popularity = df_ratings.groupby("MovieId").size().reset_index(name="NumRatings") 11 | 12 | # Step 2: Compute Average Rating for Each Movie 13 | movie_avg_rating = ( 14 | df_ratings.groupby("MovieId")["Rating"].mean().reset_index(name="AvgRating") 15 | ) 16 | 17 | # Step 3: Merge Popularity and Ratings with Movie Titles 18 | movies_stats = movie_popularity.merge(movie_avg_rating, on="MovieId") 19 | movies_stats = movies_stats.merge( 20 | df_movies[["Title"]], left_on="MovieId", right_index=True 21 | ) 22 | 23 | # Step 4: Define Serendipity Criteria 24 | # Popular Movies: High number of ratings (e.g., top 10% most rated) 25 | popularity_threshold = movies_stats["NumRatings"].quantile(0.90) 26 | popular_movies = movies_stats[movies_stats["NumRatings"] >= popularity_threshold] 27 | 28 | # Hidden Gems: High rating but low number of ratings (e.g., bottom 50% in popularity) 29 | hidden_gems = movies_stats[ 30 | (movies_stats["NumRatings"] <= movies_stats["NumRatings"].median()) 31 | & (movies_stats["AvgRating"] >= movies_stats["AvgRating"].quantile(0.75)) 32 | ] 33 | 34 | # Step 5: Mix Popular and Serendipitous Movies 35 | num_recommendations = 10 # Set the number of final recommendations 36 | popular_sample = popular_movies.sample( 37 | min(len(popular_movies), num_recommendations // 2) 38 | ) 39 | hidden_gems_sample = hidden_gems.sample(min(len(hidden_gems), num_recommendations // 2)) 40 | 41 | serendipity_recommendations = ( 42 | pd.concat([popular_sample, hidden_gems_sample]) 43 | .sample(frac=1) 44 | .reset_index(drop=True) 45 | ) 46 | 47 | # Step 6: Display Recommendations 48 | print("🎬 Serendipity-Based Movie Recommendations 🎬") 49 | print(serendipity_recommendations[["Title", "NumRatings", "AvgRating"]]) 50 | -------------------------------------------------------------------------------- /src/utils/solutions/als.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | from pyspark.sql import SparkSession 3 | from pyspark.sql.functions import col 4 | from pyspark.ml import Pipeline 5 | from pyspark.ml.feature import StringIndexer, VectorAssembler 6 | from pyspark.ml.recommendation import ALS 7 | from pyspark.ml.evaluation import RegressionEvaluator 8 | 9 | 10 | spark = SparkSession.builder.appName("Spark_ML_Pipeline").getOrCreate() 11 | 12 | # Load the dataset 13 | df = spark.read.csv("data/books_ratings.csv", header=True, inferSchema=True) 14 | 15 | # Preprocess data 16 | indexer = StringIndexer(inputCol="reviewerID", outputCol="reviewerID_index") 17 | df = indexer.fit(df).transform(df) 18 | 19 | # Convert userId and bookId into numerical indices 20 | user_indexer = StringIndexer(inputCol="userId", outputCol="userIndex") 21 | book_indexer = StringIndexer(inputCol="bookId", outputCol="bookIndex") 22 | 23 | # Assemble features into a vector 24 | assembler = VectorAssembler(inputCols=["userIndex", "bookIndex"], outputCol="features") 25 | 26 | # Split data into training and test sets 27 | (training, test) = df.randomSplit([0.8, 0.2], seed=42) 28 | 29 | 30 | # Define the ALS model 31 | als = ALS( 32 | maxIter=10, 33 | regParam=0.01, 34 | userCol="userIndex", 35 | itemCol="bookIndex", 36 | ratingCol="rating", 37 | coldStartStrategy="drop", 38 | ) 39 | 40 | # Create a pipeline 41 | pipeline = Pipeline(stages=[user_indexer, book_indexer, als]) 42 | model = pipeline.fit(training) 43 | 44 | # Make predictions 45 | predictions = model.transform(test) 46 | 47 | # Evaluate the model 48 | evaluator = RegressionEvaluator(metricName="rmse", labelCol="rating", predictionCol="prediction") 49 | rmse = evaluator.evaluate(predictions) 50 | print(f"Root Mean Squared Error (RMSE): {rmse}") 51 | 52 | # Bonus: Experiment with different ALS hyperparameters 53 | als_tuned = ALS( 54 | maxIter=15, regParam=0.05, rank=30, 55 | userCol="userIndex", itemCol="bookIndex", ratingCol="rating", coldStartStrategy="drop" 56 | ) 57 | 58 | # Retrain the model 59 | model_tuned = als_tuned.fit(training) 60 | predictions_tuned = model_tuned.transform(test) 61 | rmse_tuned = evaluator.evaluate(predictions_tuned) 62 | print(f"Tuned RMSE: {rmse_tuned:.2f}") -------------------------------------------------------------------------------- /src/old_lectures/utils/solutions/als.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | from pyspark.sql import SparkSession 3 | from pyspark.sql.functions import col 4 | from pyspark.ml import Pipeline 5 | from pyspark.ml.feature import StringIndexer, VectorAssembler 6 | from pyspark.ml.recommendation import ALS 7 | from pyspark.ml.evaluation import RegressionEvaluator 8 | 9 | 10 | spark = SparkSession.builder.appName("Spark_ML_Pipeline").getOrCreate() 11 | 12 | # Load the dataset 13 | df = spark.read.csv("data/books_ratings.csv", header=True, inferSchema=True) 14 | 15 | # Preprocess data 16 | indexer = StringIndexer(inputCol="reviewerID", outputCol="reviewerID_index") 17 | df = indexer.fit(df).transform(df) 18 | 19 | # Convert userId and bookId into numerical indices 20 | user_indexer = StringIndexer(inputCol="userId", outputCol="userIndex") 21 | book_indexer = StringIndexer(inputCol="bookId", outputCol="bookIndex") 22 | 23 | # Assemble features into a vector 24 | assembler = VectorAssembler(inputCols=["userIndex", "bookIndex"], outputCol="features") 25 | 26 | # Split data into training and test sets 27 | (training, test) = df.randomSplit([0.8, 0.2], seed=42) 28 | 29 | 30 | # Define the ALS model 31 | als = ALS( 32 | maxIter=10, 33 | regParam=0.01, 34 | userCol="userIndex", 35 | itemCol="bookIndex", 36 | ratingCol="rating", 37 | coldStartStrategy="drop", 38 | ) 39 | 40 | # Create a pipeline 41 | pipeline = Pipeline(stages=[user_indexer, book_indexer, als]) 42 | model = pipeline.fit(training) 43 | 44 | # Make predictions 45 | predictions = model.transform(test) 46 | 47 | # Evaluate the model 48 | evaluator = RegressionEvaluator(metricName="rmse", labelCol="rating", predictionCol="prediction") 49 | rmse = evaluator.evaluate(predictions) 50 | print(f"Root Mean Squared Error (RMSE): {rmse}") 51 | 52 | # Bonus: Experiment with different ALS hyperparameters 53 | als_tuned = ALS( 54 | maxIter=15, regParam=0.05, rank=30, 55 | userCol="userIndex", itemCol="bookIndex", ratingCol="rating", coldStartStrategy="drop" 56 | ) 57 | 58 | # Retrain the model 59 | model_tuned = als_tuned.fit(training) 60 | predictions_tuned = model_tuned.transform(test) 61 | rmse_tuned = evaluator.evaluate(predictions_tuned) 62 | print(f"Tuned RMSE: {rmse_tuned:.2f}") -------------------------------------------------------------------------------- /src/FinalProject/project_2024/README.md: -------------------------------------------------------------------------------- 1 | # Project Assignment: Movie Pairing Recommender System 2 | 3 | ## Objective 4 | 5 | Develop a recommender system that pairs two movies based on complementary genres, themes, or viewer preferences, similar to the concept used on [Date Night Movies](https://datenightmovies.com/spider-man-no-way-home+mona-lisa-smile). 6 | 7 | ## Dataset 8 | 9 | You can use the following datasets: 10 | 11 | - **MovieLens Dataset**: [MovieLens](https://grouplens.org/datasets/movielens/) 12 | - **IMDb Dataset**: [IMDb Datasets](https://www.imdb.com/interfaces/) 13 | 14 | ## Tasks 15 | 16 | 1. **Data Collection and Preprocessing** 17 | - Download the MovieLens and IMDb datasets. 18 | - Merge datasets to include movie ratings, genres, and metadata. 19 | 20 | 2. **Feature Engineering** 21 | - Extract relevant features, you can choose the basic ones or create composite ones. A few examples are genres, directors, cast, and ratings. 22 | - Create a user-item interaction matrix for collaborative filtering. 23 | - Understand how to combine user data to get data for the couple of users. 24 | 25 | 3. **Model Development** 26 | - Implement a recommender system algorithm (e.g., matrix factorization) to predict the rating of a movie by a couple of users. 27 | 28 | 4. **Recommendation Algorithm** 29 | - Develop an algorithm to suggest one movie that might be liked by the couple of users. You can use the criteria you prefer to create a "couple score" for each movie and then sort the movies by the score. 30 | 31 | 5. **Evaluation** 32 | - Split the data into training and testing sets. 33 | - Evaluate the model, choose the metric you prefer. 34 | 35 | **Important note**: There are quite few free choices in the project. This is intentional, it is expected the different developers might have different approaches. The important thing is to *always* be able to explain your approach and why you chose the specific tools/frameworks/methodologies. 36 | 37 | ## Deliverables 38 | 39 | - **Code**: Well-documented code in a GitHub repository. I expect for each of you a *link* to a GitHub repository. 40 | - **Report**: A detailed report explaining the methodology, experiments, results, and conclusions. (This can be included in the GitHub repository README.md) 41 | 42 | ## Evaluation Criteria 43 | 44 | - **Functionality**: Does the system provide relevant and complementary movie recommendations? 45 | - **Accuracy**: How well does the system perform in terms of the chose metric? Was the metric a good measure of the quality of the recommendations? 46 | - **Documentation**: Quality and clarity of the code documentation and report. 47 | 48 | This project will give you practical experience in building a real-world recommender system, integrating data from multiple sources. Good luck! 49 | -------------------------------------------------------------------------------- /src/utils/collab_filter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from typing import Tuple 4 | 5 | 6 | def normalizeRatings(Y: np.ndarray, R: np.ndarray, axis: int = 1) -> Tuple: 7 | """ 8 | Preprocess data by subtracting mean rating for every movie (every row). 9 | Only include real ratings: R(i,j)=1. 10 | 11 | [Ynorm, Ymean] = normalizeRatings(Y, R) normalized Y so that each movie 12 | has a rating of 0 on average. Unrated moves then have a mean rating (0) 13 | Returns the mean rating in Ymean. 14 | 15 | Parameters 16 | ---------- 17 | Y : np.ndarray 18 | The rating array to normalise. 19 | R : np.ndarray 20 | The array indicating whether a user rated a movie. 21 | axis : int 22 | The numpy axis to use for taking the average rating. 23 | 24 | Returns 25 | ------- 26 | Tuple 27 | The normalised array of ratings and the mean rating. 28 | 29 | """ 30 | Ymean = (np.sum(Y * R, axis=axis) / (np.sum(R, axis=axis) + 1e-12)).reshape(-1, 1) 31 | 32 | if axis == 0: 33 | Ynorm = Y.T - np.multiply(Ymean, R.T) 34 | else: 35 | Ynorm = Y - np.multiply(Ymean, R) 36 | 37 | return (Ynorm, Ymean) 38 | 39 | 40 | def minmaxNormalise(Y: np.ndarray) -> Tuple: 41 | """Preprocess data by normalising rating for every movie (every row). 42 | It rescale ratings in the range [0,1] 43 | 44 | Parameters 45 | ---------- 46 | Y : np.ndarray 47 | The rating array to normalise. 48 | 49 | Returns 50 | ------- 51 | Tuple 52 | The normalised array of ratings and the max rating. 53 | """ 54 | Y_scaled = Y / Y.max() 55 | return Y_scaled, Y.max() 56 | 57 | 58 | def load_precalc_params_small() -> Tuple: 59 | file = open("../data/small_movies_X.csv", "rb") 60 | X = np.loadtxt(file, delimiter=",") 61 | 62 | file = open("../data/small_movies_W.csv", "rb") 63 | W = np.loadtxt(file, delimiter=",") 64 | 65 | file = open("../data/small_movies_b.csv", "rb") 66 | b = np.loadtxt(file, delimiter=",") 67 | b = b.reshape(1, -1) 68 | num_movies, num_features = X.shape 69 | num_users, _ = W.shape 70 | return (X, W, b, num_movies, num_features, num_users) 71 | 72 | 73 | def load_ratings_small() -> Tuple: 74 | file = open("../data/small_movies_Y.csv", "rb") 75 | Y = np.loadtxt(file, delimiter=",") 76 | 77 | file = open("../data/small_movies_R.csv", "rb") 78 | R = np.loadtxt(file, delimiter=",") 79 | return (Y, R) 80 | 81 | 82 | def load_Movie_List_pd() -> Tuple[list, pd.DataFrame]: 83 | """returns df with and index of movies in the order they are in in the Y matrix""" 84 | df = pd.read_csv( 85 | "../data/small_movie_list.csv", 86 | header=0, 87 | index_col=0, 88 | delimiter=",", 89 | quotechar='"', 90 | ) 91 | mlist = df["title"].to_list() 92 | return (mlist, df) 93 | -------------------------------------------------------------------------------- /src/old_lectures/utils/collab_filter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from typing import Tuple 4 | 5 | 6 | def normalizeRatings(Y: np.ndarray, R: np.ndarray, axis: int = 1) -> Tuple: 7 | """ 8 | Preprocess data by subtracting mean rating for every movie (every row). 9 | Only include real ratings: R(i,j)=1. 10 | 11 | [Ynorm, Ymean] = normalizeRatings(Y, R) normalized Y so that each movie 12 | has a rating of 0 on average. Unrated moves then have a mean rating (0) 13 | Returns the mean rating in Ymean. 14 | 15 | Parameters 16 | ---------- 17 | Y : np.ndarray 18 | The rating array to normalise. 19 | R : np.ndarray 20 | The array indicating whether a user rated a movie. 21 | axis : int 22 | The numpy axis to use for taking the average rating. 23 | 24 | Returns 25 | ------- 26 | Tuple 27 | The normalised array of ratings and the mean rating. 28 | 29 | """ 30 | Ymean = (np.sum(Y * R, axis=axis) / (np.sum(R, axis=axis) + 1e-12)).reshape(-1, 1) 31 | 32 | if axis == 0: 33 | Ynorm = Y.T - np.multiply(Ymean, R.T) 34 | else: 35 | Ynorm = Y - np.multiply(Ymean, R) 36 | 37 | return (Ynorm, Ymean) 38 | 39 | 40 | def minmaxNormalise(Y: np.ndarray) -> Tuple: 41 | """Preprocess data by normalising rating for every movie (every row). 42 | It rescale ratings in the range [0,1] 43 | 44 | Parameters 45 | ---------- 46 | Y : np.ndarray 47 | The rating array to normalise. 48 | 49 | Returns 50 | ------- 51 | Tuple 52 | The normalised array of ratings and the max rating. 53 | """ 54 | Y_scaled = Y / Y.max() 55 | return Y_scaled, Y.max() 56 | 57 | 58 | def load_precalc_params_small() -> Tuple: 59 | file = open("../data/small_movies_X.csv", "rb") 60 | X = np.loadtxt(file, delimiter=",") 61 | 62 | file = open("../data/small_movies_W.csv", "rb") 63 | W = np.loadtxt(file, delimiter=",") 64 | 65 | file = open("../data/small_movies_b.csv", "rb") 66 | b = np.loadtxt(file, delimiter=",") 67 | b = b.reshape(1, -1) 68 | num_movies, num_features = X.shape 69 | num_users, _ = W.shape 70 | return (X, W, b, num_movies, num_features, num_users) 71 | 72 | 73 | def load_ratings_small() -> Tuple: 74 | file = open("../data/small_movies_Y.csv", "rb") 75 | Y = np.loadtxt(file, delimiter=",") 76 | 77 | file = open("../data/small_movies_R.csv", "rb") 78 | R = np.loadtxt(file, delimiter=",") 79 | return (Y, R) 80 | 81 | 82 | def load_Movie_List_pd() -> Tuple[list, pd.DataFrame]: 83 | """returns df with and index of movies in the order they are in in the Y matrix""" 84 | df = pd.read_csv( 85 | "../data/small_movie_list.csv", 86 | header=0, 87 | index_col=0, 88 | delimiter=",", 89 | quotechar='"', 90 | ) 91 | mlist = df["title"].to_list() 92 | return (mlist, df) 93 | -------------------------------------------------------------------------------- /src/FinalProject/README.md: -------------------------------------------------------------------------------- 1 | # Final project 2 | 3 | Here we propose a final project for the course. 4 | 5 | --- 6 | 7 | ## Goals and motivations 8 | 9 | This is meant as an extended exercise collecting and summarising the content of the whole course. 10 | The aim is to give each student the freedom to choose the best solution he is comfortable with and to justify the choice with some data-driven consideration. 11 | 12 | ## Project scheme 13 | 14 | Here we describe how the project should be developed, or better what are the expected inputs and outputs. 15 | Each student should deliver a project that corresponds to the project scheme. 16 | We are inspired by [Kaggle Competitions](https://www.kaggle.com/competitions), so we will use the same format. 17 | 18 | ### Inputs 19 | 20 | Data are provided by the course. 21 | The idea is to use such data to solve a problem. 22 | 23 | We will use the following data structures: 24 | 25 | - **DataProject**: a directory containing one or more csv files. 26 | - `train.csv`: training data with labels. 27 | - `test.csv`: test data with no labels. 28 | - `sample_submission.csv`: sample submission. 29 | - **Data description**: a csv file containing a description of the data. 30 | 31 | ### Outputs 32 | 33 | These are the expected outputs of the project. 34 | 35 | - **Submission**: a csv file containing the results of the project, according to the sample submission format. 36 | - **FinalProject_Notebook**: a notebook file containing analysis, relevant choices and results comments and explanations. 37 | - **_Optional_**: 38 | - **{NAME}\_model.joblib**: a file containing the trained model in the form of a pipeline. 39 | - **{NAME}\_model.h5**: a file containing the trained model in the form of a keras model. 40 | - **{NAME}\_model**: a directory containing the trained model in the form of a tensorflow SavedModel. 41 | 42 | --- 43 | 44 | #### Hint to save the model 45 | 46 | ##### Sklearn pipeline 47 | 48 | One can save the model pipeline (so all the relevant feature engineering and preprocessing steps can be executed automatically) in a file with the following example code: 49 | 50 | ```python 51 | from sklearn.externals import joblib 52 | pipe = Pipeline([ 53 | ('scaler', StandardScaler()), 54 | ('model', LogisticRegression()) 55 | ]) 56 | 57 | pipe.fit(X_train, y_train) 58 | pipe.predict(X_test) # Not compulsory to save the model. 59 | 60 | joblib.dump(pipe, '{NAME}_model.joblib') 61 | ``` 62 | 63 | ##### Tensorflow and keras models 64 | 65 | For tensorflow and keras models there are a few different ways to save the model on a file. 66 | One can have a look at [this useful link](https://www.tensorflow.org/tutorials/keras/save_and_load) with examples from official documentation. 67 | 68 | One of the most popular and intuitive way of saving the model is using the keras api of tensorflow. 69 | 70 | ```python 71 | # Create and train a new model instance. 72 | model = create_model() 73 | model.fit(train_images, train_labels, epochs=5) 74 | 75 | # Save the entire model as a SavedModel. 76 | model.save('path_to_model_dir/my_model') 77 | ``` 78 | -------------------------------------------------------------------------------- /src/FinalProject/project_2023/proposedSolution/README.md: -------------------------------------------------------------------------------- 1 | # Proposed Solution 2 | 3 | The aim of the final project was to give the opportunity to apply the knowledge acquired during the course to a real-world problem. 4 | 5 | The solution proposed here is a hybrid recommender system that integrates collaborative filtering with content-based recommendations to improve overall recommendation quality. 6 | 7 | ## Solution Outline 8 | 9 | ### Understanding the Business Problem 10 | 11 | - **Objective**: Enhance user experience by providing personalised restaurant recommendations. 12 | - **Key Questions**: 13 | - How can we use customer location, restaurant information, and order history to predict restaurant preferences? 14 | - What factors influence a customer's decision to order from a specific restaurant? 15 | 16 | ### Data Exploration and Preparation 17 | 18 | - **Data Collection**: Download and load the data files provided. 19 | - **Data Understanding**: 20 | - Analyse the datasets to understand the features and the relationships between them. 21 | - Identify missing values, outliers, and categorical variables that need encoding. 22 | - **Data Cleaning**: 23 | - Handle missing values and outliers. 24 | - Encode categorical variables. 25 | - Normalise or standardise numerical features if necessary. 26 | 27 | ### Feature Engineering 28 | 29 | - **Feature Creation**: 30 | - Generate new features that might be helpful for the model, such as distance between customer location and restaurant, order frequency, and popular times for ordering. 31 | - **Feature Selection**: 32 | - Use correlation analysis, mutual information, or feature importance from model to select relevant features. 33 | 34 | ### Model Development 35 | 36 | - **Model Selection**: 37 | - Consider models suitable for recommendation systems, such as collaborative filtering, content-based filtering, and hybrid models. 38 | - **Model Training**: 39 | - Split the data into training and validation sets. 40 | - Train models and tune hyperparameters using cross-validation. 41 | - **Model Evaluation**: 42 | - Evaluate model performance using the F1 score as the primary metric. 43 | - Consider also measuring precision and recall to understand model behaviour. 44 | 45 | ### Model Refinement and Finalisation 46 | 47 | - **Model Refinement**: 48 | - Use insights from the evaluation phase to refine the model. This may include feature engineering adjustments or trying different model architectures. 49 | - **Model Testing**: 50 | - Test the final model on a separate test set to estimate how it will perform in real-world scenarios. 51 | 52 | ### Deployment and Monitoring 53 | 54 | - **Deployment**: 55 | - Deploy the model in a simulated or real environment where the client can use it to make recommendations. 56 | - **Monitoring and Maintenance**: 57 | - Monitor the model's performance over time to catch any degradation in prediction quality. 58 | - Plan for periodic retraining of the model with new data. 59 | 60 | ### Presentation and Documentation 61 | 62 | - **Presentation**: 63 | - Prepare a presentation of your findings, methodology, model performance, and recommendations for the client and data science team. 64 | - **Documentation**: 65 | - Document the project, including data exploration findings, model development process, final model configuration, and deployment strategy. 66 | -------------------------------------------------------------------------------- /src/exercises/BookRecommender.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Introduction to Recommender Systems\n", 8 | "\n", 9 | "

\n", 10 | " \"cover-image\"\n", 11 | "

\n", 12 | "\n", 13 | "---\n", 14 | "\n", 15 | "# The Exercise\n", 16 | "\n", 17 | "In this exercise, you will implement a simple recommender system using the GoodRead dataset. The dataset contains information about books, authors, and user ratings. The goal is to recommend books to users based on their ratings.\n", 18 | "\n", 19 | "## The Dataset\n", 20 | "\n", 21 | "The dataset is available at this link: [GoodReads Dataset](https://github.com/zygmuntz/goodbooks-10k/releases/download/v1.0/goodbooks-10k.zip). It contains the following files:\n", 22 | "\n", 23 | "- `books.csv`: Contains information about books.\n", 24 | "- `ratings.csv`: Contains user ratings for books.\n", 25 | "- `book_tags.csv`: Contains tags assigned to books.\n", 26 | "\n", 27 | "## The Task\n", 28 | "\n", 29 | "You need to implement a simple recommender system that recommends books to users based on their ratings.\n", 30 | "\n", 31 | "### Steps\n", 32 | "\n", 33 | "1. Download the dataset.\n", 34 | "2. Perfom data analysis.\n", 35 | "3. Justify all the choices you make as results of some data analysis.\n", 36 | "4. Implement the recommender system.\n", 37 | "\n", 38 | "### Tasks\n", 39 | "\n", 40 | "While implementing the recommender system, you need to perform the following tasks (that are also a guideline for the implementation).\n", 41 | "\n", 42 | "#### Data Analysis\n", 43 | "\n", 44 | "- Load and explore the dataset.\n", 45 | "- Analyse the distribution of ratings.\n", 46 | "- Visualise the number of ratings per book and per user.\n", 47 | "- Check for missing values and decide how to handle them.\n", 48 | "\n", 49 | "\n", 50 | "#### Feature Engineering\n", 51 | "\n", 52 | "- Encode User_ID and Book_Title as integer indices for the model.\n", 53 | "- Create a feature to represent the popularity of books based on the number of ratings.\n", 54 | "- Optionally, incorporate author information if it improves the model.\n", 55 | "\n", 56 | "#### Building the Recommender System\n", 57 | "\n", 58 | "- Split the data into training and test sets.\n", 59 | "- Implement a collaborative filtering model using matrix factorization.\n", 60 | "- Train the model and evaluate its performance using RMSE (Root Mean Square Error) on the test set.\n", 61 | "- Generate book recommendations for a set of users.- \n", 62 | "\n", 63 | "#### Recommendations\n", 64 | "\n", 65 | "- Write a function to display the top N recommended books for a given user.\n", 66 | "- Discuss how different features and the size of the dataset affect the model's performance." 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [] 75 | } 76 | ], 77 | "metadata": { 78 | "language_info": { 79 | "name": "python" 80 | } 81 | }, 82 | "nbformat": 4, 83 | "nbformat_minor": 2 84 | } 85 | -------------------------------------------------------------------------------- /src/FinalProject/project_2023/README.md: -------------------------------------------------------------------------------- 1 | # Final Project 2 | 3 |

4 | cover-image 5 |

6 | 7 | The objective of this project is to build a recommendation engine to predict what restaurants customers are most likely to order from given the customer location, restaurant information, and the customer order history. 8 | 9 | You should imagine that this is a client project and that you are working with a team of data scientists to build a recommendation engine. You will be expected to present your work to the client and to the data science team. 10 | 11 | This solution will allow your client, an app-based food delivery service, to customise restaurant recommendations for each of their customers and ensure a more positive overall user experience. 12 | 13 | ## Data 14 | 15 | There are ~$10,000$ customers in the test set. These are the customers you will need to recommend a vendor to. Each customer can order from multiple locations, identified by the variable `LOC_NUM`. 16 | 17 | There are ~$35,000$ customers in the train set. 18 | Some of these customers have made orders at at least one of $100$ vendors. 19 | 20 | As said, the aim of this project is to build a recommendation engine to predict what restaurants customers are most likely to order from, given the customer location, the restaurant, and the customer order history. 21 | 22 | Data files are available at [this link](https://mega.nz/file/ZRhgESqR#iuO6pBaZbeEttJ_BGmwbSh2XTg4tnf_zXrzSXcq5W6M) and are structured as follows: 23 | 24 | * `test_customers.csv`- customer id’s in the test set. 25 | * `test_locations.csv` - latitude and longitude for the different locations of each customer. 26 | * `train_locations.csv` - customer id’s in the test set. 27 | * `train_customers.csv` - latitude and longitude for the different locations of each customer. 28 | * `orders.csv` - orders that the customers `train_customers.csv` from made. 29 | * `vendors.csv` - vendors that customers can order from. 30 | * `VariableDefinitions.txt` - Variable definitions for the datasets 31 | * `SampleSubmission.csv` - is an example of what your submission file should look like. The order of the rows does not matter, but the names of CID X LOC_NUM X VENDOR must be correct. The column "target" is your prediction. 32 | 33 | ## Evaluation 34 | 35 | The error metric for this competition is the $F_1$ score, which ranges from 0 (total failure) to 1 (perfect score). Hence, the closer your score is to $1$, the better your model. 36 | 37 | * **F1 Score**: A performance score that combines both precision and recall. It is a harmonic mean of these two variables. The formula is given as: 38 | 39 | $$F_1 = 2 \frac{PR}{P + R}\, .$$ 40 | 41 | * **Precision**: This is an indicator of the number of items correctly identified as positive out of total items identified as positive. The formula is given as: 42 | 43 | $$P = \frac{TP}{TP+FP}\, .$$ 44 | 45 | * **Recall** / Sensitivity / True Positive Rate (TPR): This is an indicator of the number of items correctly identified as positive out of total actual positives. The formula is given as: 46 | 47 | $$R = \frac{TP}{TP+FN}\, .$$ 48 | 49 | Where: 50 | 51 | TP=True Positive 52 | FP=False Positive 53 | TN=True Negative 54 | FN=False Negative 55 | 56 | Your submission file should look like: 57 | 58 | ```csv 59 | CID X LOC_NUM X VENDOR target 60 | A7B8IGM X 0 X 105 0 61 | NS70FA9 X 0 X 105 1 62 | WTWOE69 X 0 X 105 0 63 | ``` 64 | 65 | Where $1$ indicates that a customer will order from that restaurant and $0$ that they will not order from that restaurant. 66 | -------------------------------------------------------------------------------- /src/tests/test_coll_filter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def test_cofi_cost_func(target): 5 | num_users_r = 4 6 | num_movies_r = 5 7 | num_features_r = 3 8 | 9 | X_r = np.ones((num_movies_r, num_features_r)) 10 | W_r = np.ones((num_users_r, num_features_r)) 11 | b_r = np.zeros((1, num_users_r)) 12 | Y_r = np.zeros((num_movies_r, num_users_r)) 13 | R_r = np.zeros((num_movies_r, num_users_r)) 14 | 15 | J = target(X_r, W_r, b_r, Y_r, R_r, 2) 16 | assert not np.isclose( 17 | J, 13.5 18 | ), f"Wrong value. Got {J}. Did you multiply the regularization term by lambda_?" 19 | assert np.isclose( 20 | J, 27 21 | ), f"Wrong value. Expected {27}, got {J}. Check the regularization term" 22 | 23 | X_r = np.ones((num_movies_r, num_features_r)) 24 | W_r = np.ones((num_users_r, num_features_r)) 25 | b_r = np.ones((1, num_users_r)) 26 | Y_r = np.ones((num_movies_r, num_users_r)) 27 | R_r = np.ones((num_movies_r, num_users_r)) 28 | 29 | # Evaluate cost function 30 | J = target(X_r, W_r, b_r, Y_r, R_r, 0) 31 | 32 | assert np.isclose( 33 | J, 90 34 | ), f"Wrong value. Expected {90}, got {J}. Check the term without the regularization" 35 | 36 | X_r = np.ones((num_movies_r, num_features_r)) 37 | W_r = np.ones((num_users_r, num_features_r)) 38 | b_r = np.ones((1, num_users_r)) 39 | Y_r = np.zeros((num_movies_r, num_users_r)) 40 | R_r = np.ones((num_movies_r, num_users_r)) 41 | 42 | # Evaluate cost function 43 | J = target(X_r, W_r, b_r, Y_r, R_r, 0) 44 | 45 | assert np.isclose( 46 | J, 160 47 | ), f"Wrong value. Expected {160}, got {J}. Check the term without the regularization" 48 | 49 | X_r = np.ones((num_movies_r, num_features_r)) 50 | W_r = np.ones((num_users_r, num_features_r)) 51 | b_r = np.ones((1, num_users_r)) 52 | Y_r = np.ones((num_movies_r, num_users_r)) 53 | R_r = np.ones((num_movies_r, num_users_r)) 54 | 55 | # Evaluate cost function 56 | J = target(X_r, W_r, b_r, Y_r, R_r, 1) 57 | 58 | assert np.isclose( 59 | J, 103.5 60 | ), f"Wrong value. Expected {103.5}, got {J}. Check the term without the regularization" 61 | 62 | num_users_r = 3 63 | num_movies_r = 4 64 | num_features_r = 4 65 | 66 | # np.random.seed(247) 67 | X_r = np.array( 68 | [ 69 | [0.36618032, 0.9075415, 0.8310605, 0.08590986], 70 | [0.62634721, 0.38234325, 0.85624346, 0.55183039], 71 | [0.77458727, 0.35704147, 0.31003294, 0.20100006], 72 | [0.34420469, 0.46103436, 0.88638208, 0.36175401], 73 | ] 74 | ) # np.random.rand(num_movies_r, num_features_r) 75 | W_r = np.array( 76 | [ 77 | [0.04786854, 0.61504665, 0.06633146, 0.38298908], 78 | [0.16515965, 0.22320207, 0.89826005, 0.14373251], 79 | [0.1274051, 0.22757303, 0.96865613, 0.70741111], 80 | ] 81 | ) # np.random.rand(num_users_r, num_features_r) 82 | b_r = np.array( 83 | [[0.14246472, 0.30110933, 0.56141144]] 84 | ) # np.random.rand(1, num_users_r) 85 | Y_r = np.array( 86 | [ 87 | [0.20651685, 0.60767914, 0.86344527], 88 | [0.82665019, 0.00944765, 0.4376798], 89 | [0.81623732, 0.26776794, 0.03757507], 90 | [0.37232161, 0.19890823, 0.13026598], 91 | ] 92 | ) # np.random.rand(num_movies_r, num_users_r) 93 | R_r = np.array( 94 | [[1, 0, 1], [1, 0, 0], [1, 0, 0], [0, 1, 0]] 95 | ) # (np.random.rand(num_movies_r, num_users_r) > 0.4) * 1 96 | 97 | # Evaluate cost function 98 | J = target(X_r, W_r, b_r, Y_r, R_r, 3) 99 | 100 | assert np.isclose( 101 | J, 13.621929978531858, atol=1e-8 102 | ), f"Wrong value. Expected {13.621929978531858}, got {J}." 103 | 104 | print("\033[92mAll tests passed!") 105 | -------------------------------------------------------------------------------- /src/old_lectures/tests/test_coll_filter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def test_cofi_cost_func(target): 5 | num_users_r = 4 6 | num_movies_r = 5 7 | num_features_r = 3 8 | 9 | X_r = np.ones((num_movies_r, num_features_r)) 10 | W_r = np.ones((num_users_r, num_features_r)) 11 | b_r = np.zeros((1, num_users_r)) 12 | Y_r = np.zeros((num_movies_r, num_users_r)) 13 | R_r = np.zeros((num_movies_r, num_users_r)) 14 | 15 | J = target(X_r, W_r, b_r, Y_r, R_r, 2) 16 | assert not np.isclose( 17 | J, 13.5 18 | ), f"Wrong value. Got {J}. Did you multiply the regularization term by lambda_?" 19 | assert np.isclose( 20 | J, 27 21 | ), f"Wrong value. Expected {27}, got {J}. Check the regularization term" 22 | 23 | X_r = np.ones((num_movies_r, num_features_r)) 24 | W_r = np.ones((num_users_r, num_features_r)) 25 | b_r = np.ones((1, num_users_r)) 26 | Y_r = np.ones((num_movies_r, num_users_r)) 27 | R_r = np.ones((num_movies_r, num_users_r)) 28 | 29 | # Evaluate cost function 30 | J = target(X_r, W_r, b_r, Y_r, R_r, 0) 31 | 32 | assert np.isclose( 33 | J, 90 34 | ), f"Wrong value. Expected {90}, got {J}. Check the term without the regularization" 35 | 36 | X_r = np.ones((num_movies_r, num_features_r)) 37 | W_r = np.ones((num_users_r, num_features_r)) 38 | b_r = np.ones((1, num_users_r)) 39 | Y_r = np.zeros((num_movies_r, num_users_r)) 40 | R_r = np.ones((num_movies_r, num_users_r)) 41 | 42 | # Evaluate cost function 43 | J = target(X_r, W_r, b_r, Y_r, R_r, 0) 44 | 45 | assert np.isclose( 46 | J, 160 47 | ), f"Wrong value. Expected {160}, got {J}. Check the term without the regularization" 48 | 49 | X_r = np.ones((num_movies_r, num_features_r)) 50 | W_r = np.ones((num_users_r, num_features_r)) 51 | b_r = np.ones((1, num_users_r)) 52 | Y_r = np.ones((num_movies_r, num_users_r)) 53 | R_r = np.ones((num_movies_r, num_users_r)) 54 | 55 | # Evaluate cost function 56 | J = target(X_r, W_r, b_r, Y_r, R_r, 1) 57 | 58 | assert np.isclose( 59 | J, 103.5 60 | ), f"Wrong value. Expected {103.5}, got {J}. Check the term without the regularization" 61 | 62 | num_users_r = 3 63 | num_movies_r = 4 64 | num_features_r = 4 65 | 66 | # np.random.seed(247) 67 | X_r = np.array( 68 | [ 69 | [0.36618032, 0.9075415, 0.8310605, 0.08590986], 70 | [0.62634721, 0.38234325, 0.85624346, 0.55183039], 71 | [0.77458727, 0.35704147, 0.31003294, 0.20100006], 72 | [0.34420469, 0.46103436, 0.88638208, 0.36175401], 73 | ] 74 | ) # np.random.rand(num_movies_r, num_features_r) 75 | W_r = np.array( 76 | [ 77 | [0.04786854, 0.61504665, 0.06633146, 0.38298908], 78 | [0.16515965, 0.22320207, 0.89826005, 0.14373251], 79 | [0.1274051, 0.22757303, 0.96865613, 0.70741111], 80 | ] 81 | ) # np.random.rand(num_users_r, num_features_r) 82 | b_r = np.array( 83 | [[0.14246472, 0.30110933, 0.56141144]] 84 | ) # np.random.rand(1, num_users_r) 85 | Y_r = np.array( 86 | [ 87 | [0.20651685, 0.60767914, 0.86344527], 88 | [0.82665019, 0.00944765, 0.4376798], 89 | [0.81623732, 0.26776794, 0.03757507], 90 | [0.37232161, 0.19890823, 0.13026598], 91 | ] 92 | ) # np.random.rand(num_movies_r, num_users_r) 93 | R_r = np.array( 94 | [[1, 0, 1], [1, 0, 0], [1, 0, 0], [0, 1, 0]] 95 | ) # (np.random.rand(num_movies_r, num_users_r) > 0.4) * 1 96 | 97 | # Evaluate cost function 98 | J = target(X_r, W_r, b_r, Y_r, R_r, 3) 99 | 100 | assert np.isclose( 101 | J, 13.621929978531858, atol=1e-8 102 | ), f"Wrong value. Expected {13.621929978531858}, got {J}." 103 | 104 | print("\033[92mAll tests passed!") 105 | -------------------------------------------------------------------------------- /src/exercises/HybridNN.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Introduction to Recommender Systems\n", 8 | "\n", 9 | "

\n", 10 | " \"cover-image\"\n", 11 | "

\n", 12 | "\n", 13 | "---\n", 14 | "\n", 15 | "# Exercise: Hybrid Movie Recommender System\n", 16 | "\n", 17 | "## Objective\n", 18 | "Create a hybrid recommender system that combines both content-based filtering (using neural networks) and collaborative filtering approaches to provide movie recommendations.\n", 19 | "\n", 20 | "## Data\n", 21 | "The data to use is the notorious [disease symptom description dataset](https://www.kaggle.com/datasets/itachi9604/disease-symptom-description-dataset/data) available on kaggle.\n", 22 | "\n", 23 | "Before starting, try to think about the correspondence between disease, symptoms and users, items. How would you define users, items, and interactions in this context?\n", 24 | "\n", 25 | "## Tasks\n", 26 | "### 1. Data Preparation and Feature Engineering\n", 27 | "- Use the MovieLens dataset provided in the lecture\n", 28 | "- Create additional features for movies beyond the existing ones:\n", 29 | "- Extract year from release date as a separate feature\n", 30 | "- Create genre interaction features (e.g., Action-SciFi, Drama-Romance)\n", 31 | "- Add popularity metrics (number of ratings, average rating)\n", 32 | "### 2. Neural Network Architecture Design\n", 33 | "- Design a neural network architecture that:\n", 34 | "- Takes both movie content features and user features as input\n", 35 | "- Has at least 3 hidden layers with different activation functions\n", 36 | "- Uses dropout layers to prevent overfitting\n", 37 | "- Implements batch normalization\n", 38 | "- Outputs a predicted rating\n", 39 | "### 3. Training and Evaluation\n", 40 | "- Split the data into training, validation, and test sets\n", 41 | "- Implement a custom training loop that:\n", 42 | "- Uses mini-batch gradient descent\n", 43 | "- Implements early stopping\n", 44 | "- Tracks both training and validation loss\n", 45 | "- Evaluate the model using multiple metrics:\n", 46 | "- Mean Squared Error (MSE)\n", 47 | "- Mean Absolute Error (MAE)\n", 48 | "- Precision@K and Recall@K\n", 49 | "### 4. Hybrid Recommendation System\n", 50 | "- Combine the neural network predictions with collaborative filtering:\n", 51 | "- Use the neural network for content-based predictions\n", 52 | "- Implement a simple collaborative filtering component\n", 53 | "- Create a weighted combination of both approaches\n", 54 | "- Experiment with different weighting schemes and evaluate their impact\n", 55 | "### 5. Visualization and Analysis\n", 56 | "- Create visualizations showing:\n", 57 | "- Training/validation loss curves\n", 58 | "- Feature importance analysis\n", 59 | "- Comparison of pure content-based vs. hybrid approach\n", 60 | "- Sample recommendations with explanations\n", 61 | "\n", 62 | "## Deliverables\n", 63 | "- A Jupyter notebook with:\n", 64 | " * Complete implementation\n", 65 | " * Visualizations\n", 66 | " * Performance analysis\n", 67 | " * Discussion of results\n", 68 | "- A brief report (max 2 pages) explaining:\n", 69 | " * Design decisions\n", 70 | " * Challenges faced\n", 71 | " * Performance comparison\n", 72 | " * Potential improvements\n", 73 | "\n", 74 | "## Bonus Challenge\n", 75 | "Implement attention mechanisms in the neural network to better capture the importance of different features in the recommendation process." 76 | ] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "metadata": {}, 81 | "source": [] 82 | } 83 | ], 84 | "metadata": { 85 | "language_info": { 86 | "name": "python" 87 | } 88 | }, 89 | "nbformat": 4, 90 | "nbformat_minor": 2 91 | } 92 | -------------------------------------------------------------------------------- /src/FinalProject/project_2025/README.md: -------------------------------------------------------------------------------- 1 | # Project Assignment: Short Video Recommender System (KuaiRec) 2 | 3 | ## Objective 4 | 5 | Develop a recommender system that suggests short videos to users based on user preferences, interaction histories, and video content using the **KuaiRec dataset**. The challenge is to create a personalised and scalable recommendation engine similar to those used in platforms like TikTok or Kuaishou. 6 | 7 | ## Dataset 8 | 9 | We will use the **KuaiRec dataset**, a large-scale, fully-observed dataset collected from the Kuaishou short-video platform. 10 | 11 | It contains: 12 | 13 | - **User interactions** (views, likes, etc.) 14 | - **Video metadata** (video ID, tags, etc.) 15 | - **Timestamps** 16 | 17 | More info: [KuaiRec Paper](https://arxiv.org/abs/2202.10842) 18 | 19 | The dataset will be preprocessed and provided in this format: 20 | 21 | - `interactions_train.csv`: historical user-item interactions for training. 22 | - `interactions_test.csv`: user-item pairs to score during testing. 23 | - `sample_submission.csv`: a template showing the expected output format. 24 | - `video_metadata.csv`: metadata including tags or content-related features. 25 | 26 | ### Download the dataset 27 | 28 | You can download the dataset via a wget command: 29 | 30 | ```bash 31 | wget https://nas.chongminggao.top:4430/datasets/KuaiRec.zip --no-check-certificate 32 | unzip KuaiRec.zip 33 | ``` 34 | 35 | ### Dataset description 36 | 37 | KuaiRec contains millions of user-item interactions as well as side information including the item categories and a social network. Six files are included in the download data: 38 | 39 | ```bash 40 | KuaiRec 41 | ├── data 42 | │ ├── big_matrix.csv 43 | │ ├── small_matrix.csv 44 | │ ├── social_network.csv 45 | │ ├── user_features.csv 46 | │ ├── item_daily_features.csv 47 | │ └── item_categories.csv 48 | │ └── kuairec_caption_category.csv 49 | ``` 50 | 51 | ## Tasks 52 | 53 | 1. **Data Preprocessing** 54 | - Load and inspect the dataset. 55 | - Handle missing or inconsistent data. 56 | - Merge metadata for content-based models if necessary. 57 | 58 | 2. **Feature Engineering** 59 | - Create meaningful features from interaction and metadata (e.g., content tags, user activity history). 60 | - Build user-item interaction matrix. 61 | - Optionally extract time-based or popularity-based features. 62 | 63 | 3. **Model Development** 64 | - Choose a recommendation approach: 65 | - Collaborative filtering (e.g., ALS, Matrix Factorisation) 66 | - Content-based filtering 67 | - Sequence-aware models 68 | - Hybrid approaches 69 | - Train and validate your model on the training set. 70 | 71 | 4. **Recommendation Algorithm** 72 | - Predict which videos are likely to be enjoyed by each user in the test set. 73 | - Generate a top-N ranked list of recommendations for each user. 74 | 75 | 5. **Evaluation** 76 | - Choose suitable metrics (e.g., Precision@K, Recall@K, MAP, NDCG). 77 | - Evaluate performance and provide interpretations. 78 | 79 | **Important note**: This project leaves room for creativity. Different students might take different paths in preprocessing, modelling, and evaluation. What matters is your ability to justify each step with solid reasoning. 80 | 81 | ## Deliverables 82 | 83 | I expect you to send me an email with a link to your GitHub repo. If the repo is private, please add me as a collaborator. 84 | 85 | - **Code**: Well-documented code in a GitHub repository. Submit a *link* to the repo. 86 | - **Report**: A detailed README.md explaining the methodology, experiments, results, and conclusions. 87 | 88 | **Important Note**: Please name your repo as `FinalProject_2025_`. Not your GitHub username, or your nickname, use your real name, otherwise it will be hard for me to find your repo. 89 | 90 | ## Evaluation Criteria 91 | 92 | - **Functionality**: Does your recommender provide high-quality and relevant video suggestions? 93 | - **Accuracy**: Did you choose meaningful metrics? How well does the model perform according to them? 94 | - **Documentation**: Clear, organised code and explanations of each design choice. 95 | 96 | This final project is designed to mimic real-world recommender system challenges. It’s your chance to build something scalable and practical. Good luck! 🚀 97 | -------------------------------------------------------------------------------- /src/utils/non_pers_rec.py: -------------------------------------------------------------------------------- 1 | """Module to collect functions and objects for non-personalised recommendations lectures.""" 2 | import pandas as pd 3 | import logging 4 | 5 | from typing import List 6 | 7 | from .style.colours import Colour 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | df_rating = pd.read_csv( 12 | "http://files.grouplens.org/datasets/movielens/ml-100k/u1.base", 13 | sep="\t", 14 | engine="python", 15 | header=None, 16 | ) 17 | df_rating.columns = ["UserId", "MovieId", "Rating", "Timestamp"] 18 | df_rating_test = pd.read_csv( 19 | "http://files.grouplens.org/datasets/movielens/ml-100k/u1.test", 20 | sep="\t", 21 | engine="python", 22 | header=None, 23 | ) 24 | 25 | df_users = pd.read_csv( 26 | "http://files.grouplens.org/datasets/movielens/ml-100k/u.user", 27 | sep="|", 28 | engine="python", 29 | header=None, 30 | ) 31 | df_users.columns = ["UserId", "Age", "Gender", "Occupation", "ZipCode"] 32 | df_users.set_index("UserId", inplace=True) 33 | df_items = pd.read_csv( 34 | "http://files.grouplens.org/datasets/movielens/ml-100k/u.item", 35 | sep="|", 36 | engine="python", 37 | encoding="ISO-8859-1", 38 | header=None, 39 | ) 40 | df_items.columns = [ 41 | "MovieId", 42 | "Title", 43 | "Date", 44 | "VideoReleaseDate", 45 | "Url", 46 | "unknown", 47 | "Action", 48 | "Adventure", 49 | "Animation", 50 | "Children", 51 | "Comedy", 52 | "Crime", 53 | "Documentary", 54 | "Drama", 55 | "Fantasy", 56 | "Film-Noir", 57 | "Horror", 58 | "Musical", 59 | "Mystery", 60 | "Romance", 61 | "Sci-Fi", 62 | "Thriller", 63 | "War", 64 | "Western", 65 | ] 66 | df_items.set_index("MovieId", inplace=True) 67 | 68 | genre_cols = df_items.columns[7:] 69 | 70 | genre_series = df_items[genre_cols].apply( 71 | lambda row: row[row == 1].index.tolist(), axis=1 72 | ) 73 | 74 | 75 | def recommend_one(): 76 | """Function to return the recommendations based on the most popular criterion.""" 77 | return df_items.loc[[df_items.score.argmax() + 1]] 78 | 79 | 80 | def recommend_n(n_recommendations: int = 10) -> pd.DataFrame: 81 | """Function to return recommendations based on the most popular criterion. 82 | Parameters 83 | ---------- 84 | n_recommendations: int 85 | Number of recommendations to return. 86 | default: 10 87 | 88 | Returns 89 | ------- 90 | pd.DataFrame 91 | The dataframe containing the recommendations in order of preference. 92 | """ 93 | return df_items.sort_values(by="score", ascending=False).iloc[:n_recommendations] 94 | 95 | 96 | def get_recent_liked_movie(user_id: int, threshold: float = 4.0) -> int: 97 | """Function to get the id of the movie that the user has liked most recently. 98 | 99 | Parameters 100 | ---------- 101 | user_id : int 102 | The id of the user we are interested in. 103 | threshold : float 104 | The rating threshold, to determine whether a user appreciated the movie. 105 | default: 4.0 106 | 107 | Returns 108 | ------- 109 | int 110 | The movie id that the user has liked most recently. 111 | """ 112 | # check if user has liked movie above threshold 113 | usr_liked_movies = df_rating[ 114 | (df_rating.UserId == user_id) & (df_rating.Rating >= threshold) 115 | ] 116 | 117 | # if there is no movie the user has liked then recommend the most popular movies. 118 | if usr_liked_movies.empty: 119 | logger.warning( 120 | Colour.RED 121 | + f"The user has not liked any movie above {threshold}" 122 | + Colour.ENDC 123 | ) 124 | return recommend_n() 125 | 126 | # Calculate the max timestamp, to get the last appreciated movies. 127 | max_timestmp = usr_liked_movies.Timestamp.max() 128 | # If there is more than one movie at the same timestamp then get the most liked one. 129 | usr_liked_movies_last = usr_liked_movies[usr_liked_movies.Timestamp == max_timestmp] 130 | return ( 131 | usr_liked_movies_last.sort_values(by="Rating", ascending=False).iloc[0].MovieId 132 | ) 133 | 134 | 135 | def get_genre(movie_id: int) -> List[str]: 136 | """Function to get the genre of the inserted movie. 137 | 138 | Parameters 139 | ---------- 140 | movie_id : int 141 | The id of the movie whose genre is to be returned. 142 | 143 | Returns 144 | ------- 145 | list of str 146 | the genres of the inserted movie. 147 | """ 148 | return genre_series.loc[movie_id] 149 | -------------------------------------------------------------------------------- /src/old_lectures/utils/non_pers_rec.py: -------------------------------------------------------------------------------- 1 | """Module to collect functions and objects for non-personalised recommendations lectures.""" 2 | import pandas as pd 3 | import logging 4 | 5 | from typing import List 6 | 7 | from .style.colours import Colour 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | df_rating = pd.read_csv( 12 | "http://files.grouplens.org/datasets/movielens/ml-100k/u1.base", 13 | sep="\t", 14 | engine="python", 15 | header=None, 16 | ) 17 | df_rating.columns = ["UserId", "MovieId", "Rating", "Timestamp"] 18 | df_rating_test = pd.read_csv( 19 | "http://files.grouplens.org/datasets/movielens/ml-100k/u1.test", 20 | sep="\t", 21 | engine="python", 22 | header=None, 23 | ) 24 | 25 | df_users = pd.read_csv( 26 | "http://files.grouplens.org/datasets/movielens/ml-100k/u.user", 27 | sep="|", 28 | engine="python", 29 | header=None, 30 | ) 31 | df_users.columns = ["UserId", "Age", "Gender", "Occupation", "ZipCode"] 32 | df_users.set_index("UserId", inplace=True) 33 | df_items = pd.read_csv( 34 | "http://files.grouplens.org/datasets/movielens/ml-100k/u.item", 35 | sep="|", 36 | engine="python", 37 | encoding="ISO-8859-1", 38 | header=None, 39 | ) 40 | df_items.columns = [ 41 | "MovieId", 42 | "Title", 43 | "Date", 44 | "VideoReleaseDate", 45 | "Url", 46 | "unknown", 47 | "Action", 48 | "Adventure", 49 | "Animation", 50 | "Children", 51 | "Comedy", 52 | "Crime", 53 | "Documentary", 54 | "Drama", 55 | "Fantasy", 56 | "Film-Noir", 57 | "Horror", 58 | "Musical", 59 | "Mystery", 60 | "Romance", 61 | "Sci-Fi", 62 | "Thriller", 63 | "War", 64 | "Western", 65 | ] 66 | df_items.set_index("MovieId", inplace=True) 67 | 68 | genre_cols = df_items.columns[7:] 69 | 70 | genre_series = df_items[genre_cols].apply( 71 | lambda row: row[row == 1].index.tolist(), axis=1 72 | ) 73 | 74 | 75 | def recommend_one(): 76 | """Function to return the recommendations based on the most popular criterion.""" 77 | return df_items.loc[[df_items.score.argmax() + 1]] 78 | 79 | 80 | def recommend_n(n_recommendations: int = 10) -> pd.DataFrame: 81 | """Function to return recommendations based on the most popular criterion. 82 | Parameters 83 | ---------- 84 | n_recommendations: int 85 | Number of recommendations to return. 86 | default: 10 87 | 88 | Returns 89 | ------- 90 | pd.DataFrame 91 | The dataframe containing the recommendations in order of preference. 92 | """ 93 | return df_items.sort_values(by="score", ascending=False).iloc[:n_recommendations] 94 | 95 | 96 | def get_recent_liked_movie(user_id: int, threshold: float = 4.0) -> int: 97 | """Function to get the id of the movie that the user has liked most recently. 98 | 99 | Parameters 100 | ---------- 101 | user_id : int 102 | The id of the user we are interested in. 103 | threshold : float 104 | The rating threshold, to determine whether a user appreciated the movie. 105 | default: 4.0 106 | 107 | Returns 108 | ------- 109 | int 110 | The movie id that the user has liked most recently. 111 | """ 112 | # check if user has liked movie above threshold 113 | usr_liked_movies = df_rating[ 114 | (df_rating.UserId == user_id) & (df_rating.Rating >= threshold) 115 | ] 116 | 117 | # if there is no movie the user has liked then recommend the most popular movies. 118 | if usr_liked_movies.empty: 119 | logger.warning( 120 | Colour.RED 121 | + f"The user has not liked any movie above {threshold}" 122 | + Colour.ENDC 123 | ) 124 | return recommend_n() 125 | 126 | # Calculate the max timestamp, to get the last appreciated movies. 127 | max_timestmp = usr_liked_movies.Timestamp.max() 128 | # If there is more than one movie at the same timestamp then get the most liked one. 129 | usr_liked_movies_last = usr_liked_movies[usr_liked_movies.Timestamp == max_timestmp] 130 | return ( 131 | usr_liked_movies_last.sort_values(by="Rating", ascending=False).iloc[0].MovieId 132 | ) 133 | 134 | 135 | def get_genre(movie_id: int) -> List[str]: 136 | """Function to get the genre of the inserted movie. 137 | 138 | Parameters 139 | ---------- 140 | movie_id : int 141 | The id of the movie whose genre is to be returned. 142 | 143 | Returns 144 | ------- 145 | list of str 146 | the genres of the inserted movie. 147 | """ 148 | return genre_series.loc[movie_id] 149 | -------------------------------------------------------------------------------- /src/README.md: -------------------------------------------------------------------------------- 1 | # 📚 Recommender Systems Course - Lecture Breakdown 2 | 3 | This directory contains materials for each lecture in the **Recommender Systems** course. The course consists of **8 lectures**, each 3 hours long, covering the fundamentals, evaluation metrics, classical approaches, hybrid models, and modern deep learning techniques. 4 | 5 | ## 📖 Course Lectures 6 | 7 | ### 1️⃣ **Introduction to Recommender Systems** 8 | 9 | 📌 Overview of recommender systems and their real-world applications 10 | 📌 Types of recommender systems (content-based, collaborative filtering, hybrid) 11 | 📌 Business impact and challenges in recommendation 12 | 📌 Datasets: MovieLens, Netflix Prize, Amazon Reviews 13 | 📌 Hands-on: Setting up a simple rule-based recommender 14 | 15 | 📂 **Materials:** `Lecture1_Intro/` 16 | 17 | --- 18 | 19 | ### 2️⃣ **Evaluation Metrics for Recommender Systems** 20 | 21 | 📌 Offline vs. online evaluation 22 | 📌 Accuracy metrics: Precision, Recall, MAP, NDCG 23 | 📌 Error-based metrics: RMSE, MAE 24 | 📌 Beyond accuracy: diversity, novelty, serendipity, coverage 25 | 📌 A/B testing and online evaluation 26 | 📌 Hands-on: Implementing evaluation metrics in Python 27 | 28 | 📂 **Materials:** `Lecture2_Evaluation/` 29 | 30 | --- 31 | 32 | ### 3️⃣ **Content-Based Filtering** 33 | 34 | 📌 How content-based filtering works 35 | 📌 Feature extraction: TF-IDF, embeddings for text, images, audio 36 | 📌 Cosine similarity and nearest neighbours 37 | 📌 Strengths and weaknesses of content-based methods 38 | 📌 Hands-on: Implementing a TF-IDF-based movie recommender 39 | 40 | 📂 **Materials:** `Lecture3_ContentBased/` 41 | 42 | --- 43 | 44 | ### 4️⃣ **Collaborative Filtering** 45 | 46 | 📌 User-based vs. item-based collaborative filtering 47 | 📌 Pearson correlation and similarity measures 48 | 📌 Model-based methods: Matrix factorisation (SVD, ALS) 49 | 📌 Cold start and sparsity issues 50 | 📌 Hands-on: Implementing collaborative filtering with user-item data 51 | 52 | 📂 **Materials:** `Lecture4_CollaborativeFiltering/` 53 | 54 | --- 55 | 56 | ### 5️⃣ **Hybrid Recommender Systems** 57 | 58 | 📌 Why hybrid models? 59 | 📌 Strategies: weighted, switching, feature combination 60 | 📌 Netflix Prize: How Netflix optimised recommendations 61 | 📌 Hands-on: Implementing a hybrid recommender 62 | 63 | 📂 **Materials:** `Lecture5_Hybrid/` 64 | 65 | --- 66 | 67 | ### 6️⃣ **LensKit Library for Recommender Systems** 68 | 69 | 📌 Introduction to LensKit and its advantages 70 | 📌 Implementing content-based and collaborative filtering using LensKit 71 | 📌 Evaluating recommendation models with LensKit 72 | 📌 Hands-on: Training and evaluating models in LensKit 73 | 74 | 📂 **Materials:** `Lecture6_LensKit/` 75 | 76 | --- 77 | 78 | ### 7️⃣ **Matrix Factorisation & Advanced Techniques** 79 | 80 | 📌 Matrix factorisation fundamentals: SVD, ALS 81 | 📌 Factorisation Machines and Bayesian Personalised Ranking 82 | 📌 Implicit feedback handling 83 | 📌 Hands-on: Implementing matrix factorisation with Surprise 84 | 85 | 📂 **Materials:** `Lecture7_MatrixFactorization/` 86 | 87 | --- 88 | 89 | ### 8️⃣ **Deep Neural Networks for Recommender Systems** 90 | 91 | 📌 Neural Collaborative Filtering (NCF) 92 | 📌 Autoencoders and Variational Autoencoders (VAEs) 93 | 📌 RNNs for sequential recommendations 94 | 📌 Transformers in recommender systems 95 | 📌 Hands-on: Building a deep learning-based recommender 96 | 97 | 📂 **Materials:** `Lecture8_DeepLearning/` 98 | 99 | --- 100 | 101 | ## 🎯 Final Project 102 | 103 | 📌 Build and evaluate a custom recommender system 104 | 📌 Apply concepts from previous lectures 105 | 📌 Present results and insights 106 | 107 | 📂 **Materials:** `FinalProject/` 108 | 109 | --- 110 | 111 | ## 📚 References 112 | 113 | This course is built upon a mix of theoretical foundations, industry best practices, and hands-on implementations from various sources. Below are key references used throughout the lectures: 114 | 115 | ### 📖 **Books** 116 | 117 | - Ricci, F., Rokach, L., & Shapira, B. (2015). *Recommender Systems Handbook*. Springer. 118 | - Aggarwal, C. C. (2016). *Recommender Systems: The Textbook*. Springer. 119 | - Okura, K., Tagami, Y., Ono, S., & Tajima, A. (2017). *Deep Neural Networks for YouTube Recommendations*. arXiv. 120 | 121 | ### 📄 **Academic Papers** 122 | 123 | - Resnick, P., & Varian, H. R. (1997). *Recommender Systems*. Communications of the ACM, 40(3), 56-58. 124 | - Sarwar, B. M., Karypis, G., Konstan, J. A., & Riedl, J. (2001). *Item-Based Collaborative Filtering Recommendation Algorithms*. WWW Conference. 125 | - He, X., Liao, L., Zhang, H., Nie, L., Hu, X., & Chua, T. S. (2017). *Neural Collaborative Filtering*. WWW Conference. 126 | - Koren, Y., Bell, R., & Volinsky, C. (2009). *Matrix Factorization Techniques for Recommender Systems*. IEEE Computer. 127 | 128 | ### 🔨 **Libraries & Tools** 129 | 130 | - **[LensKit](https://lkpy.lenskit.org/)** - A Python toolkit for building and experimenting with recommender systems. 131 | - **[Surprise](https://surpriselib.com/)** - A scikit-based Python library for collaborative filtering. 132 | - **[TensorFlow Recommenders](https://www.tensorflow.org/recommenders/)** - TensorFlow-based deep learning models for recommendation tasks. 133 | 134 | ### 📂 **Datasets** 135 | 136 | - **[MovieLens](https://grouplens.org/datasets/movielens/)** - Widely used dataset for evaluating recommender systems. 137 | - **[Netflix Prize](https://www.netflixprize.com/)** - Historic dataset from the Netflix recommendation competition. 138 | - **[Amazon Reviews](https://nijianmo.github.io/amazon/index.html)** - Large-scale e-commerce recommendation dataset. 139 | 140 | ### 🎓 **Online Courses & Tutorials** 141 | 142 | - **[Coursera: Recommender Systems Specialization](https://www.coursera.org/specializations/recommender-systems)** - University of Minnesota. 143 | - **[Fast.ai: Deep Learning for Recommender Systems](https://course.fast.ai/)** - Advanced deep learning applications. 144 | - **[Google's Recommender Systems Course](https://developers.google.com/machine-learning/recommendation)** - Introduction to modern recommender techniques. 145 | 146 | --- 147 | 148 | 📌 *If you find useful references or additional resources that complement this course, feel free to contribute by adding them here!* 149 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Recommender Systems 4 | 5 | This is the repository for the Recommender Systems course. 6 | 7 |

8 | image 9 |

10 | 11 | ## Introduction 12 | 13 | Recommender systems or _recommender engines_ are a set of algorithms that have in common the idea of _suggesting_ a "product" to a user. 14 | 15 | It is difficult to determine when this ancient idea was transferred to the IT field, but we know that it has profoundly changed the way we relate to the digital world. Just think of Google, Amazon, Netflix, YouTube, etc., all of these companies base their successes on particular recommendation systems that are particularly efficient. 16 | 17 | The extensive use of these systems has contributed greatly to the emergence of the phenomenon known as the " information bubbles"[[1]](#1). 18 | Indeed, the increasing presence of people on social networks and their tendency to inform themselves through these channels has produced important social and political effects, as shown for example in [[2]](#2) or [[3]](#3). 19 | 20 | Other problems with the use of recommender systems have emerged when it has been found that these systems can lead to increased levels of anxiety and depression in predisposed individuals [[4]](#4) and generally ruin the online experience, or how they make it much easier for fake news [[5]](#5) and conspiracy theories [[6]](#6) to spread. 21 | 22 | Of course, there are not only negative consequences of using these systems. 23 | Many companies have been able to publicize themselves online more effectively (the advertisements being targeted to the "right" users) and at the same time the average user during his online presence has been able to see only products of his interest. 24 | 25 | Studies are underway on the possibility of building personalized therapies for each patient, with definitely promising results [[7]](#7). 26 | 27 | In conclusion, recommender systems are probably among the applications of machine learning whose study is most useful not only to the professional but also to the ordinary citizen, given their enormous influence in shaping today's society. 28 | For these reasons, understanding and studying how these systems work is important and interesting. 29 | 30 | We refer you to the various modules and the lecture index (see below) for timely details; in the meantime, we _recommend_ good learning and good work! 31 | 32 | --- 33 | 34 | ## Installation 35 | 36 | I strongly recommend creating a virtual environment to isolate package dependencies. 37 | Depending on the operating system, there are various guides and tutorials on how to do this. [Here](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/) I point to a cross-platform one. 38 | 39 | The recommended version of Python is `3.7` (or higher). 40 | 41 | Once you have set up your environment, at your favorite command prompt, run 42 | 43 | ```bash 44 | pip install -r requirements.txt 45 | ``` 46 | 47 | this will install the packages and libraries needed for the course in the appropriate versions. 48 | 49 | ## Interacting with online notebooks 50 | 51 | The free _Binder_ service, allows you to access an already configured environment and run notebooks. Just click on the badge below to start the environment. 52 | 53 |

54 | 55 |

56 | 57 | ## Table of Contents of lectures 58 | 59 | [Here](src/README.md) you can find a more detailed index of the various modules. 60 | 61 | --- 62 | 63 | ## Your lecturer 64 | 65 | ### [Oscar de Felice](https://oscar-defelice.github.io/) 66 | 67 | ![Oscar](https://oscar-defelice.github.io/images/OscarAboutMe.png) 68 | 69 | I am a theoretical physicist and programming and AI enthusiast. 70 | 71 | I write articles on Medium (very unsystematically), you can read them [here](https://oscar-defelice.medium.com/). 72 | I also have a [github profile](https://github.com/oscar-defelice) where I put my personal and open-source projects. 73 | 74 | 📫 [Contact me!](mailto:oscar.defelice@gmail.com) 75 | 76 | [![github](https://img.shields.io/badge/GitHub-100000?style=plastic&logo=github&logoColor=white)](https://github.com/oscar-defelice) 77 | [![Website](https://img.shields.io/badge/oscar--defelice-oscar-orange?style=plastic&logo=netlify&logoColor=informational&link=oscar-defelice.github.io)](https://oscar-defelice.github.io) 78 | [![Twitter Badge](https://img.shields.io/badge/-@OscardeFelice-1ca0f1?style=plastic&labelColor=1ca0f1&logo=twitter&logoColor=white&link=https://twitter.com/oscardefelice)](https://twitter.com/OscardeFelice) 79 | [![Linkedin Badge](https://img.shields.io/badge/-oscardefelice-blue?style=plastic&logo=Linkedin&logoColor=white&link=https://linkedin.com/in/oscar-de-felice-5ab72383/)](https://linkedin.com/in/oscar-de-felice-5ab72383/) 80 | 81 | ## Other courses 82 | 83 | Here you can find more material about other lectures and courses on Machine Learning topics. 84 | 85 | 1. [Introduction to Data Science](https://oscar-defelice.github.io/DSAcademy-lectures) 🧮 86 | 2. [Statistical Learning](https://oscar-defelice.github.io/ML-lectures) 📈 87 | 3. [Deep Learning](https://oscar-defelice.github.io/DeepLearning-lectures) 🦾 88 | 4. [Time Series](https://oscar-defelice.github.io/TimeSeries-lectures) ⌛ 89 | 5. [Computer Vision Hands-On](https://oscar-defelice.github.io/Computer-Vision-Hands-on) 👀️ 90 | 91 | ## References 92 | 93 | [1] 94 | Van Alstyne, Marshall; Brynjolfsson, Erik (March 1997). 95 | ["Electronic Communities: Global Village or Cyberbalkans?"](http://web.mit.edu/marshall/www/papers/CyberBalkans.pdf) 96 | 97 | [2] 98 | Hern (2017). 99 | ["How social media filter bubbles and algorithms influence the election"](https://www.theguardian.com/technology/2017/may/22/social-media-election-facebook-filter-bubbles) 100 | 101 | [3] 102 | Baer, Drake (2017). 103 | ["The ‘Filter Bubble’ Explains Why Trump Won and You Didn’t See It Coming"](http://nymag.com/scienceofus/2016/11/how-facebook-and-the-filter-bubble-pushed-trump-to-victory.html) 104 | 105 | [4] 106 | Lazar, Shira (June 1, 2011). 107 | ["Algorithms and the Filter Bubble Ruining Your Online Experience?"](http://www.huffingtonpost.com/shira-lazar/algorithms-and-the-filter_b_869473.html) 108 | 109 | [5] 110 | Meredith, Sam (10 April 2018). 111 | ["Facebook-Cambridge Analytica: A timeline of the data hijacking scandal"](https://www.cnbc.com/2018/04/10/facebook-cambridge-analytica-a-timeline-of-the-data-hijacking-scandal.html) 112 | 113 | [6] 114 | Catalina Albeanu (17 November 2016). 115 | ["Bursting the filter bubble after the US election: Is the media doomed to fail?"](https://www.journalism.co.uk/news/bursting-the-filter-bubble-after-the-us-election/s2/a692918/) 116 | 117 | [7] 118 | Felix Gräßer, Stefanie Beckert, Denise Küster, Jochen Schmitt, Susanne Abraham, Hagen Malberg, and Sebastian Zaunseder (2017). 119 | ["Therapy Decision Support Based on Recommender System Methods"](https://www.hindawi.com/journals/jhe/2017/8659460/) 120 | -------------------------------------------------------------------------------- /README_IT.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Recommender Systems 4 | 5 | Questo è il repository del corso Recommender Systems. 6 | 7 |

8 | image 9 |

10 | 11 | ## Introduzione 12 | 13 | I sistemi di raccomandazione (_recommender systems_ o _recommender engines_ in inglese) sono un insieme di algoritmi che hanno in comune l'idea di _suggerire_ ad un utente un "prodotto". 14 | 15 | È difficile stabilire quando quest'idea antichissima è stata trasferita all'ambito informatico, ma sappiamo che ha profondamente cambiato il nostro modo di rapportarci al mondo digitale. Basti pensare a Google, ad Amazon, Netflix, YouTube, etc., tutte queste compagnie fondano i loro successi su particolari sistemi di raccomandazione particolarmente efficienti. 16 | 17 | L'uso esteso di questi sistemi ha contribuito in modo determinante all'affermarsi del fenomeno noto come delle " bolle di informazione"[[1]](#1). 18 | Infatti, la sempre più massiccia presenza delle persone sui social network, e la loro tendenza ad informarsi tramite questi canali ha prodotto importanti effetti sociali e politici, come si mostra ad esempio in [[2]](#2) o [[3]](#3). 19 | 20 | Altre problematiche nell'uso dei recommender systems sono emerse quando si è constatato come questi sistemi possano portare ad aumentare i livelli di ansia e depressione in soggetti predisposti [[4]](#4) e rovinare in generale l'esperienza online, oppure come rendano molto più semplice il diffondersi di notizie false [[5]](#5) e teorie cospiratorie [[6]](#6). 21 | 22 | Ovviamente, non ci sono solo conseguenze negative dell'uso di questi sistemi. 23 | Molte aziende hanno potuto publicizzarsi online in maniera più efficace (essendo le pubblicità mirate agli utenti "giusti") e contemporaneamente l'utente medio durante la sua presenza online ha potuto vedere solo prodotti di suo interesse. 24 | 25 | Sono in corso studi sulla possibilità di costruire terapie personalizzate per ogni paziente, con risultati decisamente promettenti [[7]](#7). 26 | 27 | In conclusione, i recommender systems sono probabilmente tra le applicazioni del machine learning il cui studio è più utile non solo al professionista, ma anche al semplice cittadino, data la loro enorme influenza nel plasmare la società odierna. 28 | Per queste ragioni, comprendere e studiare il funzionamento di questi sistemi è importante ed interessante. 29 | 30 | Rimandiamo ai vari moduli e all'indice delle lezioni (si veda più in basso) per dettagli puntuali, nel frattempo, vi _raccomandiamo_ buon apprendimento e buon lavoro! 31 | 32 | --- 33 | 34 | ## Installazione 35 | 36 | Consiglio fortemente di creare un ambiente virtuale per isolare le dipendenze dei pacchetti. 37 | A seconda del sistema operativo esistono varie guide e tutorial su come fare. [Qui](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/) ne indico una multipiattaforma. 38 | 39 | La versione di Python consigliata è la `3.7` (o superiore). 40 | 41 | Una volta configurato il proprio ambiente, nel vostro prompt di comandi preferito, eseguire 42 | 43 | ```bash 44 | pip install -r requirements.txt 45 | ``` 46 | 47 | questo installera i pacchetti e le librerie necessarie al corso nelle versioni opportune. 48 | 49 | ## Interagire con i notebook online 50 | 51 | Il servizio gratuito _Binder_, permette di accedere ad un ambiente già configurato ed eseguire i notebook. Basta cliccare sul badge qui sotto per avviare l'ambiente. 52 | 53 |

54 | 55 |

56 | 57 | ## Indice delle lezioni 58 | 59 | [Qui](src/README.md) puoi trovare un indice più dettagliato dei vari moduli. 60 | 61 | --- 62 | 63 | ## Docente 64 | 65 | ### [Oscar de Felice](https://oscar-defelice.github.io/) 66 | 67 | ![Oscar](https://oscar-defelice.github.io/images/OscarAboutMe.png) 68 | 69 | Sono un fisico teorico e appassionato di programmazione e IA. 70 | 71 | Scrivo articoli su Medium (molto poco sistematicamente), puoi leggerli [qui](https://oscar-defelice.medium.com/). 72 | Ho anche un [profilo github](https://github.com/oscar-defelice) dove metto i miei progetti personali ed open-source. 73 | 74 | 📫 [Contattami!](mailto:oscar.defelice@gmail.com) 75 | 76 | [![github](https://img.shields.io/badge/GitHub-100000?style=plastic&logo=github&logoColor=white)](https://github.com/oscar-defelice) 77 | [![Website](https://img.shields.io/badge/oscar--defelice-oscar-orange?style=plastic&logo=netlify&logoColor=informational&link=oscar-defelice.github.io)](https://oscar-defelice.github.io) 78 | [![Twitter Badge](https://img.shields.io/badge/-@OscardeFelice-1ca0f1?style=plastic&labelColor=1ca0f1&logo=twitter&logoColor=white&link=https://twitter.com/oscardefelice)](https://twitter.com/OscardeFelice) 79 | [![Linkedin Badge](https://img.shields.io/badge/-oscardefelice-blue?style=plastic&logo=Linkedin&logoColor=white&link=https://linkedin.com/in/oscar-de-felice-5ab72383/)](https://linkedin.com/in/oscar-de-felice-5ab72383/) 80 | 81 | ## Altri corsi 82 | 83 | Qui puoi trovare i materiali di altri miei corsi su argomenti di Machine Learning. 84 | 85 | 1. [Introduction to Data Science](https://oscar-defelice.github.io/DSAcademy-lectures) 🧮 86 | 2. [Statistical Learning](https://oscar-defelice.github.io/ML-lectures) 📈 87 | 3. [Deep Learning](https://oscar-defelice.github.io/DeepLearning-lectures) 🦾 88 | 4. [Time Series](https://oscar-defelice.github.io/TimeSeries-lectures) ⌛ 89 | 5. [Computer Vision Hands-On](https://oscar-defelice.github.io/Computer-Vision-Hands-on) 👀️ 90 | 91 | ## Referenze 92 | 93 | [1] 94 | Van Alstyne, Marshall; Brynjolfsson, Erik (March 1997). 95 | ["Electronic Communities: Global Village or Cyberbalkans?"](http://web.mit.edu/marshall/www/papers/CyberBalkans.pdf) 96 | 97 | [2] 98 | Hern (2017). 99 | ["How social media filter bubbles and algorithms influence the election"](https://www.theguardian.com/technology/2017/may/22/social-media-election-facebook-filter-bubbles) 100 | 101 | [3] 102 | Baer, Drake (2017). 103 | ["The ‘Filter Bubble’ Explains Why Trump Won and You Didn’t See It Coming"](http://nymag.com/scienceofus/2016/11/how-facebook-and-the-filter-bubble-pushed-trump-to-victory.html) 104 | 105 | [4] 106 | Lazar, Shira (June 1, 2011). 107 | ["Algorithms and the Filter Bubble Ruining Your Online Experience?"](http://www.huffingtonpost.com/shira-lazar/algorithms-and-the-filter_b_869473.html) 108 | 109 | [5] 110 | Meredith, Sam (10 April 2018). 111 | ["Facebook-Cambridge Analytica: A timeline of the data hijacking scandal"](https://www.cnbc.com/2018/04/10/facebook-cambridge-analytica-a-timeline-of-the-data-hijacking-scandal.html) 112 | 113 | [6] 114 | Catalina Albeanu (17 November 2016). 115 | ["Bursting the filter bubble after the US election: Is the media doomed to fail?"](https://www.journalism.co.uk/news/bursting-the-filter-bubble-after-the-us-election/s2/a692918/) 116 | 117 | [7] 118 | Felix Gräßer, Stefanie Beckert, Denise Küster, Jochen Schmitt, Susanne Abraham, Hagen Malberg, and Sebastian Zaunseder (2017). 119 | ["Therapy Decision Support Based on Recommender System Methods"](https://www.hindawi.com/journals/jhe/2017/8659460/) 120 | -------------------------------------------------------------------------------- /src/old_lectures/01.Introduction.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# Introduction to Recommender Systems\n", 9 | "\n", 10 | "

\n", 11 | " \"cover-image\"\n", 12 | "

\n", 13 | "\n", 14 | "---\n", 15 | "\n", 16 | "# Introduction\n", 17 | "\n", 18 | "## The Power of Recommendation Systems\n", 19 | "\n", 20 | "Recommendation systems are one of the most useful applications of machine learning and nowadays it seems to take more and more place in our lives. There are many web-services like YouTube, Amazon, Netflix or Spotify running powerful recommendation engines.\n", 21 | "\n", 22 | "In a general way, _recommendation systems are algorithms which suggests relevant items to users_. For example: movies to watch on your Netflix account, or products to buy on your Amazon account, or videos to watch on YouTube, or music to listen on Spotify, or anything else depending on the industry.\n", 23 | "\n", 24 | "Nowadays, customers are faced with multiple choices because there are millions of products available online and recommendation sections help them to find desired ones. It is something we cannot imagine modern e-Commerce or online media without it.\n", 25 | "\n", 26 | "## Personalised vs non-personalised recommender systems\n", 27 | "\n", 28 | "The most general split we can do about recommender systems is in two types:\n", 29 | "\n", 30 | "1. Personalised\n", 31 | "2. Non-Personalised\n", 32 | "\n", 33 | "### Personalised recommendations\n", 34 | "\n", 35 | "Giving a personalised recommendation to the user requires to know specific information about this user. You should know what are the features of products that this user likes or dislikes according to his past behaviour and purchasing history on your web-site.\n", 36 | "\n", 37 | "For example: You should know what kind of movies I liked based on my historical movie ratings (for example I like Sci-Fi movies) and according to this information you can recommend moves that I might like. You can find movies which have high chance to be liked by me in a two ways:\n", 38 | "\n", 39 | "1. _Item to item similarity_: Suggest me to watch other movies which are similar to the movies I already liked (which items are similar to the items I already liked).\n", 40 | "2. _User to user similarity_: Suggest me to watch other movies that users which are similar to me have already liked and I have not seen yet (which user is similar to me according to my and his historical behaviour/interest).\n", 41 | "\n", 42 | "To summarise what personalised recommendation system tries to do in a simple way, before we deep dive into this topic in the next lectures.\n", 43 | "\n", 44 | "* Predicts the rating the user may give to the products which he has not tried yet. Predictions are made based on user’s taste and preferences which is designed according to his historical behaviour on your web-site (purchased items, ratings or some other interactions).\n", 45 | "* Sorts the products according to the predicted rating in descending order and recommends top N items from this list to the user\n", 46 | "\n", 47 | "So as you can see in personalised systems users individual likes and dislikes (historical ratings) are considered to generate customised recommendations for them. There can be two kind of users rating:\n", 48 | "\n", 49 | "1. **Explicit Ratings**: If user can rate something that he purchased on your web-site, you have explicit ratings. It is direct information from users, so you are $100\\%$ accurate how they liked products/services which they purchased. For example on Amazon one can rate items it has purchased.\n", 50 | "2. **Implicit Ratings**: If you do not have web-site like Amazon where users can directly rate some items or if your customers do not use this functionality and you have many items that are unrated, you can use _implicit ratings_. Imagine, you have an online gambling web-site where people can play some games, you can think about things which might means that they liked a game or not. For instance: time or money spent on this game compared to another game. Or if you have a web-site where you are selling the tickets of bus, theatre, events or something else you can say that if user purchased something it also means that they liked it without extra explorations.\n", 51 | "\n", 52 | "A further logical split of recommender system models can be the one making reference to three categories: **content based systems**, **collaborative filtering systems**, and **hybrid systems** (which use a combination of the other two).\n", 53 | "\n", 54 | "

\n", 55 | " \"image\"\n", 56 | "

\n", 57 | "\n", 58 | "**Content based systems** use item features in order to recommend objects with similar properties. \n", 59 | "On the other hand, **Collaborative filtering systems** build a model from users' past behaviours, as well as decision made by similar users.\n", 60 | "\n", 61 | "### Non-Personalised Recommendations\n", 62 | "\n", 63 | "Non-Personalised recommendations means we do not need to know specific information about the users preferences. So if the historical data of users ratings or purchases are not available one cannot generate customised recommendation for them. That does not mean that this kind of recommendations are less important. There are several examples of non-personalised recommendations that show interesting content.\n", 64 | "\n", 65 | "

\n", 66 | " \"image\"\n", 67 | "

\n", 68 | "\n", 69 | "The most simple non-personalised recommendations are based on items popularity. A recommendation comes from what people like. \n", 70 | "For example: you are suggesting to watch the movie _Titanic_ for all of your customers because _Titanic_ is one of the most popular movie and you hope that it will be also interesting for those who have not seen yet. \n", 71 | "\n", 72 | "I am sure you have seen recommendations of popular items like this:\n", 73 | "\n", 74 | "1. Best-seller\n", 75 | "2. Most popular\n", 76 | "3. Trending hot\n", 77 | "4. Best-liked\n", 78 | "5. Selling fast\n", 79 | "\n", 80 | "There are other kinds of non-personalised recommendations which are commonly used in e-commerce. They look more like a rule: \n", 81 | "\n", 82 | "> “People who buy X also buy Y”. \n", 83 | "\n", 84 | "For example: People who bought phone also bought phone cover. So if you are buying a phone, they will likely recommend you to add the corresponding phone cover in your basket.\n", 85 | "\n", 86 | "This kind of recommendation is non-personalised because they are not using your individual ratings/taste or preferences to recommend you the phone cover. Instead, they know that phone and phone cover are associated items, because they are frequently bought together.\n" 87 | ] 88 | } 89 | ], 90 | "metadata": { 91 | "kernelspec": { 92 | "display_name": "Python 3", 93 | "language": "python", 94 | "name": "python3" 95 | }, 96 | "language_info": { 97 | "name": "python", 98 | "version": "3.9.6" 99 | }, 100 | "orig_nbformat": 4, 101 | "vscode": { 102 | "interpreter": { 103 | "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" 104 | } 105 | } 106 | }, 107 | "nbformat": 4, 108 | "nbformat_minor": 2 109 | } 110 | -------------------------------------------------------------------------------- /src/utils/solutions/knn_recommender.py: -------------------------------------------------------------------------------- 1 | # KNN-Based Recommender System on Simulated Search Engine Corpus 2 | 3 | # ✅ Import Libraries 4 | import pandas as pd 5 | import numpy as np 6 | from sklearn.feature_extraction.text import TfidfVectorizer 7 | from sklearn.neighbors import NearestNeighbors 8 | from sklearn.metrics.pairwise import cosine_similarity 9 | import matplotlib.pyplot as plt 10 | 11 | # ✅ 1. Load the Corpus 12 | # (Assuming 'documents' is a list of 150 documents generated earlier) 13 | 14 | # Simulated document corpus 15 | # Replace with actual corpus if available 16 | documents = [ 17 | "Machine learning is evolving rapidly with new research.", 18 | "Quantum computing holds the key to future computational power.", 19 | "Natural language processing enables machines to understand human text.", 20 | "Climate change poses significant global challenges.", 21 | "Cybersecurity is critical in the digital age.", 22 | "Data science blends statistics and computer science for insights.", 23 | "Artificial intelligence is reshaping modern industries.", 24 | "Neural networks mimic human brain functions in AI.", 25 | "Graph theory is vital in network analysis.", 26 | "Space exploration pushes the boundaries of human knowledge.", 27 | ] 28 | 29 | # ✅ 2. Vectorize Documents and Queries 30 | vectorizer = TfidfVectorizer() 31 | doc_vectors = vectorizer.fit_transform(documents) 32 | 33 | # Example queries 34 | queries = [ 35 | "machine learning", 36 | "quantum computing", 37 | "natural language processing", 38 | "climate change", 39 | "cybersecurity", 40 | "data science", 41 | "artificial intelligence", 42 | "neural networks", 43 | "graph theory", 44 | "space exploration", 45 | ] 46 | 47 | # Vectorize queries 48 | query_vectors = vectorizer.transform(queries) 49 | 50 | # ✅ 3. Initialize KNN 51 | knn = NearestNeighbors(n_neighbors=5, metric="cosine") 52 | knn.fit(doc_vectors) 53 | 54 | 55 | # ✅ 4. Function to Get Top-N Recommendations 56 | # 💡 Complete this function to return top-N nearest documents 57 | def knn_recommender(query_vector, doc_vectors, top_n=5): 58 | """Return top-N recommendations for a query using KNN.""" 59 | distances, indices = knn.kneighbors(query_vector, n_neighbors=top_n) 60 | return distances, indices 61 | 62 | 63 | # ✅ 5. Test KNN with an Example Query 64 | query_index = 0 # "machine learning" 65 | query_vec = query_vectors[query_index] 66 | 67 | # Call the KNN recommender 68 | # 💡 Complete the function call below 69 | distances, indices = knn_recommender(query_vec, doc_vectors, top_n=5) 70 | 71 | # Display recommendations 72 | print(f"\n🔍 Top 5 Recommendations for Query: '{queries[query_index]}'") 73 | for i, idx in enumerate(indices[0]): 74 | relevance_score = 1 - distances[0][i] # Cosine similarity 75 | print(f"{i+1}. Doc {idx+1} (Relevance Score: {relevance_score:.4f})") 76 | print(f"Content: {documents[idx]}\n") 77 | 78 | # ✅ 6. Evaluate Using Graded Relevance 79 | # 💡 Complete the evaluation metrics 80 | 81 | 82 | def precision_recall_at_k(graded_relevance, k, threshold=0.3): 83 | """Compute Precision@K and Recall@K.""" 84 | relevance_at_k = graded_relevance[:k] 85 | relevant_at_k = sum(score >= threshold for score in relevance_at_k) 86 | precision = relevant_at_k / k 87 | recall = ( 88 | relevant_at_k / sum(score >= threshold for score in graded_relevance) 89 | if sum(score >= threshold for score in graded_relevance) > 0 90 | else 0 91 | ) 92 | return precision, recall 93 | 94 | 95 | # Graded relevance (cosine similarity) 96 | cosine_similarities = cosine_similarity(query_vec, doc_vectors).flatten() 97 | 98 | # 💡 Compute Precision@5 and Recall@5 99 | precision, recall = precision_recall_at_k(cosine_similarities[indices[0]], k=5) 100 | print(f"Precision@5: {precision:.2f}") 101 | print(f"Recall@5: {recall:.2f}") 102 | 103 | 104 | # ✅ 7. NDCG@K (Graded Relevance) 105 | # 💡 Complete the NDCG function 106 | def ndcg_at_k(graded_relevance, k): 107 | """Compute NDCG@K for ranked documents.""" 108 | r = np.asfarray(graded_relevance)[:k] 109 | dcg = np.sum(r / np.log2(np.arange(2, r.size + 2))) 110 | ideal_r = sorted(graded_relevance, reverse=True)[:k] 111 | idcg = np.sum(np.array(ideal_r) / np.log2(np.arange(2, len(ideal_r) + 2))) 112 | return dcg / idcg if idcg > 0 else 0 113 | 114 | 115 | # Calculate NDCG@5 116 | ndcg = ndcg_at_k(cosine_similarities[indices[0]], k=5) 117 | print(f"NDCG@5 (Graded): {ndcg:.2f}") 118 | 119 | # ✅ 8. Visualize NDCG Scores Across Queries 120 | ndcg_scores = [] 121 | 122 | for i, query in enumerate(queries): 123 | query_vec = query_vectors[i] 124 | distances, indices = knn_recommender(query_vec, doc_vectors, top_n=5) 125 | graded_relevance = 1 - distances[0] 126 | ndcg = ndcg_at_k(graded_relevance, k=5) 127 | ndcg_scores.append(ndcg) 128 | 129 | # Plot the results 130 | plt.figure(figsize=(10, 6)) 131 | plt.barh(queries, ndcg_scores, color="skyblue") 132 | plt.xlabel("NDCG@5 (Graded)") 133 | plt.title("KNN Recommender: NDCG@5 Scores Across Queries") 134 | plt.show() 135 | 136 | # ✅ STUDENT TASKS: 137 | # 1. Complete the knn_recommender function. 138 | # 2. Implement the evaluation functions. 139 | # 3. Test different K values in KNN. 140 | # 4. Experiment with TF-IDF parameters (e.g., ngram_range). 141 | # 5. Bonus: Implement user-defined relevance thresholds. 142 | 143 | 144 | def precision_recall_at_k( 145 | graded_relevance: list[float], 146 | ground_truth: list[float], 147 | k: int, 148 | threshold: float = 0.3, 149 | ) -> tuple[float, float]: 150 | """precision_recall_at_k 151 | 152 | Parameters 153 | ---------- 154 | graded_relevance : list[float] 155 | The graded relevance scores (e.g., from TF-IDF or cosine similarity) of the documents. 156 | ground_truth : list[float] 157 | The ground truth relevance scores for the documents (e.g., binary or graded). 158 | k : int 159 | The number of top documents to consider. 160 | threshold : float, optional 161 | The relevance threshold for a document to be considered highly relevant, by default 0.3 162 | 163 | Returns 164 | ------- 165 | tuple[float, float] 166 | The precision and recall at k. 167 | """ 168 | # Select top-k documents based on graded relevance 169 | relevance_at_k = graded_relevance[:k] 170 | 171 | # Count true positives (documents that are both recommended and relevant in ground truth) 172 | true_positives = sum( 173 | 1 174 | for idx, score in enumerate(relevance_at_k) 175 | if score >= threshold and ground_truth[idx] > 0 176 | ) 177 | 178 | # Precision: proportion of recommended documents that are relevant 179 | precision = true_positives / k 180 | 181 | # Recall: proportion of all relevant documents retrieved in top-k 182 | total_relevant = sum(1 for score in ground_truth if score > 0) 183 | recall = true_positives / total_relevant if total_relevant > 0 else 0 184 | 185 | return precision, recall 186 | 187 | 188 | def average_precision_at_k( 189 | graded_relevance: list[float], k: int, threshold: float = 0.3 190 | ) -> float: 191 | """average_precision_at_k 192 | 193 | Parameters 194 | ---------- 195 | graded_relevance : list[float] 196 | The graded relevance scores of the documents. 197 | k : int 198 | The number of top documents to consider. 199 | threshold : float, optional 200 | The relevance threshold for a document to be considered highly relevant, by default 0.3 201 | 202 | Returns 203 | ------- 204 | float 205 | The average precision at k. 206 | """ 207 | precision_at_k = [] 208 | for i in range(1, k + 1): 209 | precision, _ = precision_recall_at_k(graded_relevance, i, threshold) 210 | precision_at_k.append(precision) 211 | return sum(precision_at_k) / k 212 | 213 | 214 | def ndcg_at_k( 215 | graded_relevance: list[float], ground_truth: list[float], k: int 216 | ) -> float: 217 | """Compute Normalized Discounted Cumulative Gain (NDCG) at rank k comparing TF-IDF scores to ground truth. 218 | 219 | Parameters 220 | ----------- 221 | graded_relevance : list[float] 222 | The graded relevance scores of the documents. 223 | ground_truth : list[float] 224 | The ground truth relevance scores of the documents. 225 | k : int 226 | The number of top documents to consider. 227 | 228 | Returns 229 | ------- 230 | float 231 | The NDCG@k score. 232 | """ 233 | r = np.asfarray(graded_relevance)[:k] # TF-IDF relevance scores for the top-k items 234 | dcg = np.sum(r / np.log2(np.arange(2, r.size + 2))) 235 | 236 | # Ideal DCG using ground truth relevance scores 237 | ideal_r = sorted(ground_truth, reverse=True)[:k] 238 | idcg = np.sum(np.array(ideal_r) / np.log2(np.arange(2, len(ideal_r) + 2))) 239 | 240 | return dcg / idcg if idcg > 0 else 0 241 | -------------------------------------------------------------------------------- /src/old_lectures/utils/solutions/knn_recommender.py: -------------------------------------------------------------------------------- 1 | # KNN-Based Recommender System on Simulated Search Engine Corpus 2 | 3 | # ✅ Import Libraries 4 | import pandas as pd 5 | import numpy as np 6 | from sklearn.feature_extraction.text import TfidfVectorizer 7 | from sklearn.neighbors import NearestNeighbors 8 | from sklearn.metrics.pairwise import cosine_similarity 9 | import matplotlib.pyplot as plt 10 | 11 | # ✅ 1. Load the Corpus 12 | # (Assuming 'documents' is a list of 150 documents generated earlier) 13 | 14 | # Simulated document corpus 15 | # Replace with actual corpus if available 16 | documents = [ 17 | "Machine learning is evolving rapidly with new research.", 18 | "Quantum computing holds the key to future computational power.", 19 | "Natural language processing enables machines to understand human text.", 20 | "Climate change poses significant global challenges.", 21 | "Cybersecurity is critical in the digital age.", 22 | "Data science blends statistics and computer science for insights.", 23 | "Artificial intelligence is reshaping modern industries.", 24 | "Neural networks mimic human brain functions in AI.", 25 | "Graph theory is vital in network analysis.", 26 | "Space exploration pushes the boundaries of human knowledge.", 27 | ] 28 | 29 | # ✅ 2. Vectorize Documents and Queries 30 | vectorizer = TfidfVectorizer() 31 | doc_vectors = vectorizer.fit_transform(documents) 32 | 33 | # Example queries 34 | queries = [ 35 | "machine learning", 36 | "quantum computing", 37 | "natural language processing", 38 | "climate change", 39 | "cybersecurity", 40 | "data science", 41 | "artificial intelligence", 42 | "neural networks", 43 | "graph theory", 44 | "space exploration", 45 | ] 46 | 47 | # Vectorize queries 48 | query_vectors = vectorizer.transform(queries) 49 | 50 | # ✅ 3. Initialize KNN 51 | knn = NearestNeighbors(n_neighbors=5, metric="cosine") 52 | knn.fit(doc_vectors) 53 | 54 | 55 | # ✅ 4. Function to Get Top-N Recommendations 56 | # 💡 Complete this function to return top-N nearest documents 57 | def knn_recommender(query_vector, doc_vectors, top_n=5): 58 | """Return top-N recommendations for a query using KNN.""" 59 | distances, indices = knn.kneighbors(query_vector, n_neighbors=top_n) 60 | return distances, indices 61 | 62 | 63 | # ✅ 5. Test KNN with an Example Query 64 | query_index = 0 # "machine learning" 65 | query_vec = query_vectors[query_index] 66 | 67 | # Call the KNN recommender 68 | # 💡 Complete the function call below 69 | distances, indices = knn_recommender(query_vec, doc_vectors, top_n=5) 70 | 71 | # Display recommendations 72 | print(f"\n🔍 Top 5 Recommendations for Query: '{queries[query_index]}'") 73 | for i, idx in enumerate(indices[0]): 74 | relevance_score = 1 - distances[0][i] # Cosine similarity 75 | print(f"{i+1}. Doc {idx+1} (Relevance Score: {relevance_score:.4f})") 76 | print(f"Content: {documents[idx]}\n") 77 | 78 | # ✅ 6. Evaluate Using Graded Relevance 79 | # 💡 Complete the evaluation metrics 80 | 81 | 82 | def precision_recall_at_k(graded_relevance, k, threshold=0.3): 83 | """Compute Precision@K and Recall@K.""" 84 | relevance_at_k = graded_relevance[:k] 85 | relevant_at_k = sum(score >= threshold for score in relevance_at_k) 86 | precision = relevant_at_k / k 87 | recall = ( 88 | relevant_at_k / sum(score >= threshold for score in graded_relevance) 89 | if sum(score >= threshold for score in graded_relevance) > 0 90 | else 0 91 | ) 92 | return precision, recall 93 | 94 | 95 | # Graded relevance (cosine similarity) 96 | cosine_similarities = cosine_similarity(query_vec, doc_vectors).flatten() 97 | 98 | # 💡 Compute Precision@5 and Recall@5 99 | precision, recall = precision_recall_at_k(cosine_similarities[indices[0]], k=5) 100 | print(f"Precision@5: {precision:.2f}") 101 | print(f"Recall@5: {recall:.2f}") 102 | 103 | 104 | # ✅ 7. NDCG@K (Graded Relevance) 105 | # 💡 Complete the NDCG function 106 | def ndcg_at_k(graded_relevance, k): 107 | """Compute NDCG@K for ranked documents.""" 108 | r = np.asfarray(graded_relevance)[:k] 109 | dcg = np.sum(r / np.log2(np.arange(2, r.size + 2))) 110 | ideal_r = sorted(graded_relevance, reverse=True)[:k] 111 | idcg = np.sum(np.array(ideal_r) / np.log2(np.arange(2, len(ideal_r) + 2))) 112 | return dcg / idcg if idcg > 0 else 0 113 | 114 | 115 | # Calculate NDCG@5 116 | ndcg = ndcg_at_k(cosine_similarities[indices[0]], k=5) 117 | print(f"NDCG@5 (Graded): {ndcg:.2f}") 118 | 119 | # ✅ 8. Visualize NDCG Scores Across Queries 120 | ndcg_scores = [] 121 | 122 | for i, query in enumerate(queries): 123 | query_vec = query_vectors[i] 124 | distances, indices = knn_recommender(query_vec, doc_vectors, top_n=5) 125 | graded_relevance = 1 - distances[0] 126 | ndcg = ndcg_at_k(graded_relevance, k=5) 127 | ndcg_scores.append(ndcg) 128 | 129 | # Plot the results 130 | plt.figure(figsize=(10, 6)) 131 | plt.barh(queries, ndcg_scores, color="skyblue") 132 | plt.xlabel("NDCG@5 (Graded)") 133 | plt.title("KNN Recommender: NDCG@5 Scores Across Queries") 134 | plt.show() 135 | 136 | # ✅ STUDENT TASKS: 137 | # 1. Complete the knn_recommender function. 138 | # 2. Implement the evaluation functions. 139 | # 3. Test different K values in KNN. 140 | # 4. Experiment with TF-IDF parameters (e.g., ngram_range). 141 | # 5. Bonus: Implement user-defined relevance thresholds. 142 | 143 | 144 | def precision_recall_at_k( 145 | graded_relevance: list[float], 146 | ground_truth: list[float], 147 | k: int, 148 | threshold: float = 0.3, 149 | ) -> tuple[float, float]: 150 | """precision_recall_at_k 151 | 152 | Parameters 153 | ---------- 154 | graded_relevance : list[float] 155 | The graded relevance scores (e.g., from TF-IDF or cosine similarity) of the documents. 156 | ground_truth : list[float] 157 | The ground truth relevance scores for the documents (e.g., binary or graded). 158 | k : int 159 | The number of top documents to consider. 160 | threshold : float, optional 161 | The relevance threshold for a document to be considered highly relevant, by default 0.3 162 | 163 | Returns 164 | ------- 165 | tuple[float, float] 166 | The precision and recall at k. 167 | """ 168 | # Select top-k documents based on graded relevance 169 | relevance_at_k = graded_relevance[:k] 170 | 171 | # Count true positives (documents that are both recommended and relevant in ground truth) 172 | true_positives = sum( 173 | 1 174 | for idx, score in enumerate(relevance_at_k) 175 | if score >= threshold and ground_truth[idx] > 0 176 | ) 177 | 178 | # Precision: proportion of recommended documents that are relevant 179 | precision = true_positives / k 180 | 181 | # Recall: proportion of all relevant documents retrieved in top-k 182 | total_relevant = sum(1 for score in ground_truth if score > 0) 183 | recall = true_positives / total_relevant if total_relevant > 0 else 0 184 | 185 | return precision, recall 186 | 187 | 188 | def average_precision_at_k( 189 | graded_relevance: list[float], k: int, threshold: float = 0.3 190 | ) -> float: 191 | """average_precision_at_k 192 | 193 | Parameters 194 | ---------- 195 | graded_relevance : list[float] 196 | The graded relevance scores of the documents. 197 | k : int 198 | The number of top documents to consider. 199 | threshold : float, optional 200 | The relevance threshold for a document to be considered highly relevant, by default 0.3 201 | 202 | Returns 203 | ------- 204 | float 205 | The average precision at k. 206 | """ 207 | precision_at_k = [] 208 | for i in range(1, k + 1): 209 | precision, _ = precision_recall_at_k(graded_relevance, i, threshold) 210 | precision_at_k.append(precision) 211 | return sum(precision_at_k) / k 212 | 213 | 214 | def ndcg_at_k( 215 | graded_relevance: list[float], ground_truth: list[float], k: int 216 | ) -> float: 217 | """Compute Normalized Discounted Cumulative Gain (NDCG) at rank k comparing TF-IDF scores to ground truth. 218 | 219 | Parameters 220 | ----------- 221 | graded_relevance : list[float] 222 | The graded relevance scores of the documents. 223 | ground_truth : list[float] 224 | The ground truth relevance scores of the documents. 225 | k : int 226 | The number of top documents to consider. 227 | 228 | Returns 229 | ------- 230 | float 231 | The NDCG@k score. 232 | """ 233 | r = np.asfarray(graded_relevance)[:k] # TF-IDF relevance scores for the top-k items 234 | dcg = np.sum(r / np.log2(np.arange(2, r.size + 2))) 235 | 236 | # Ideal DCG using ground truth relevance scores 237 | ideal_r = sorted(ground_truth, reverse=True)[:k] 238 | idcg = np.sum(np.array(ideal_r) / np.log2(np.arange(2, len(ideal_r) + 2))) 239 | 240 | return dcg / idcg if idcg > 0 else 0 241 | -------------------------------------------------------------------------------- /src/utils/recsysNN_utils.py: -------------------------------------------------------------------------------- 1 | """ Utilities for RecSysNN implementation """ 2 | 3 | from collections import defaultdict 4 | import csv 5 | import numpy as np 6 | 7 | import pickle 8 | 9 | import tabulate 10 | 11 | 12 | def load_data(): 13 | """called to load preprepared data for the lab""" 14 | item_train = np.genfromtxt("../data/content_item_train.csv", delimiter=",") 15 | user_train = np.genfromtxt("../data/content_user_train.csv", delimiter=",") 16 | y_train = np.genfromtxt("../data/content_y_train.csv", delimiter=",") 17 | with open( 18 | "../data/content_item_train_header.txt", newline="" 19 | ) as f: # csv reader handles quoted strings better 20 | item_features = list(csv.reader(f))[0] 21 | with open("../data/content_user_train_header.txt", newline="") as f: 22 | user_features = list(csv.reader(f))[0] 23 | item_vecs = np.genfromtxt("../data/content_item_vecs.csv", delimiter=",") 24 | 25 | movie_dict = defaultdict(dict) 26 | count = 0 27 | # with open('./data/movies.csv', newline='') as csvfile: 28 | with open("../data/content_movie_list.csv", newline="") as csvfile: 29 | reader = csv.reader(csvfile, delimiter=",", quotechar='"') 30 | for line in reader: 31 | if count == 0: 32 | count += 1 # skip header 33 | # print(line) print 34 | else: 35 | count += 1 36 | movie_id = int(line[0]) 37 | movie_dict[movie_id]["title"] = line[1] 38 | movie_dict[movie_id]["genres"] = line[2] 39 | 40 | with open("../data/content_user_to_genre.pickle", "rb") as f: 41 | user_to_genre = pickle.load(f) 42 | 43 | return ( 44 | item_train, 45 | user_train, 46 | y_train, 47 | item_features, 48 | user_features, 49 | item_vecs, 50 | movie_dict, 51 | user_to_genre, 52 | ) 53 | 54 | 55 | def pprint_train(x_train, features, vs, u_s, maxcount=5, user=True): 56 | """Prints user_train or item_train nicely""" 57 | if user: 58 | flist = [ 59 | ".0f", 60 | ".0f", 61 | ".1f", 62 | ".1f", 63 | ".1f", 64 | ".1f", 65 | ".1f", 66 | ".1f", 67 | ".1f", 68 | ".1f", 69 | ".1f", 70 | ".1f", 71 | ".1f", 72 | ".1f", 73 | ".1f", 74 | ".1f", 75 | ".1f", 76 | ] 77 | else: 78 | flist = [ 79 | ".0f", 80 | ".0f", 81 | ".1f", 82 | ".0f", 83 | ".0f", 84 | ".0f", 85 | ".0f", 86 | ".0f", 87 | ".0f", 88 | ".0f", 89 | ".0f", 90 | ".0f", 91 | ".0f", 92 | ".0f", 93 | ".0f", 94 | ".0f", 95 | ".0f", 96 | ] 97 | 98 | head = features[:vs] 99 | if vs < u_s: 100 | print("error, vector start {vs} should be greater then user start {u_s}") 101 | for i in range(u_s): 102 | head[i] = "[" + head[i] + "]" 103 | genres = features[vs:] 104 | hdr = head + genres 105 | disp = [split_str(hdr, 5)] 106 | count = 0 107 | for i in range(0, x_train.shape[0]): 108 | if count == maxcount: 109 | break 110 | count += 1 111 | disp.append( 112 | [ 113 | x_train[i, 0].astype(int), 114 | x_train[i, 1].astype(int), 115 | x_train[i, 2].astype(float), 116 | *x_train[i, 3:].astype(float), 117 | ] 118 | ) 119 | table = tabulate.tabulate( 120 | disp, tablefmt="html", headers="firstrow", floatfmt=flist, numalign="center" 121 | ) 122 | return table 123 | 124 | 125 | def split_str(ifeatures, smax): 126 | """split the feature name strings to tables fit""" 127 | ofeatures = [] 128 | for s in ifeatures: 129 | if not " " in s: # skip string that already have a space 130 | if len(s) > smax: 131 | mid = int(len(s) / 2) 132 | s = s[:mid] + " " + s[mid:] 133 | ofeatures.append(s) 134 | return ofeatures 135 | 136 | 137 | def print_pred_movies(y_p, item, movie_dict, maxcount=10): 138 | """print results of prediction of a new user. inputs are expected to be in 139 | sorted order, unscaled.""" 140 | count = 0 141 | disp = [["y_p", "movie id", "rating ave", "title", "genres"]] 142 | 143 | for i in range(0, y_p.shape[0]): 144 | if count == maxcount: 145 | break 146 | count += 1 147 | movie_id = item[i, 0].astype(int) 148 | disp.append( 149 | [ 150 | np.around(y_p[i, 0], 1), 151 | item[i, 0].astype(int), 152 | np.around(item[i, 2].astype(float), 1), 153 | movie_dict[movie_id]["title"], 154 | movie_dict[movie_id]["genres"], 155 | ] 156 | ) 157 | 158 | table = tabulate.tabulate(disp, tablefmt="html", headers="firstrow") 159 | return table 160 | 161 | 162 | def gen_user_vecs(user_vec, num_items): 163 | """given a user vector return: 164 | user predict maxtrix to match the size of item_vecs""" 165 | user_vecs = np.tile(user_vec, (num_items, 1)) 166 | return user_vecs 167 | 168 | 169 | # predict on everything, filter on print/use 170 | def predict_uservec(user_vecs, item_vecs, model, u_s, i_s, scaler): 171 | """given a scaled user vector, does the prediction on all movies in scaled print_item_vecs returns 172 | an array predictions sorted by predicted rating, 173 | arrays of user and item, sorted by predicted rating sorting index 174 | """ 175 | y_p = model.predict([user_vecs[:, u_s:], item_vecs[:, i_s:]]) 176 | y_pu = scaler.inverse_transform(y_p) 177 | 178 | if np.any(y_pu < 0): 179 | print("Error, expected all positive predictions") 180 | sorted_index = ( 181 | np.argsort(-y_pu, axis=0).reshape(-1).tolist() 182 | ) # negate to get largest rating first 183 | sorted_ypu = y_pu[sorted_index] 184 | sorted_items = item_vecs[sorted_index] 185 | sorted_user = user_vecs[sorted_index] 186 | return (sorted_index, sorted_ypu, sorted_items, sorted_user) 187 | 188 | 189 | def get_user_vecs(user_id, user_train, item_vecs, user_to_genre): 190 | """given a user_id, return: 191 | user train/predict matrix to match the size of item_vecs 192 | y vector with ratings for all rated movies and 0 for others of size item_vecs""" 193 | 194 | if not user_id in user_to_genre: 195 | print("error: unknown user id") 196 | return None 197 | else: 198 | user_vec_found = False 199 | for i in range(len(user_train)): 200 | if user_train[i, 0] == user_id: 201 | user_vec = user_train[i] 202 | user_vec_found = True 203 | break 204 | if not user_vec_found: 205 | print("error in get_user_vecs, did not find uid in user_train") 206 | num_items = len(item_vecs) 207 | user_vecs = np.tile(user_vec, (num_items, 1)) 208 | 209 | y = np.zeros(num_items) 210 | for i in range( 211 | num_items 212 | ): # walk through movies in item_vecs and get the movies, see if user has rated them 213 | movie_id = item_vecs[i, 0] 214 | if movie_id in user_to_genre[user_id]["movies"]: 215 | rating = user_to_genre[user_id]["movies"][movie_id] 216 | else: 217 | rating = 0 218 | y[i] = rating 219 | return (user_vecs, y) 220 | 221 | 222 | def get_item_genres(item_gvec, genre_features): 223 | """takes in the item's genre vector and list of genre names 224 | returns the feature names where gvec was 1""" 225 | offsets = np.nonzero(item_gvec)[0] 226 | genres = [genre_features[i] for i in offsets] 227 | return genres 228 | 229 | 230 | def print_existing_user(y_p, y, user, items, ivs, uvs, movie_dict, maxcount=10): 231 | """print results of prediction for a user who was in the database. 232 | Inputs are expected to be in sorted order, unscaled. 233 | """ 234 | count = 0 235 | disp = [ 236 | [ 237 | "y_p", 238 | "y", 239 | "user", 240 | "user genre ave", 241 | "movie rating ave", 242 | "movie id", 243 | "title", 244 | "genres", 245 | ] 246 | ] 247 | count = 0 248 | for i in range(0, y.shape[0]): 249 | if y[i, 0] != 0: # zero means not rated 250 | if count == maxcount: 251 | break 252 | count += 1 253 | movie_id = items[i, 0].astype(int) 254 | 255 | offsets = np.nonzero(items[i, ivs:] == 1)[0] 256 | genre_ratings = user[i, uvs + offsets] 257 | disp.append( 258 | [ 259 | y_p[i, 0], 260 | y[i, 0], 261 | user[i, 0].astype(int), # userid 262 | np.array2string( 263 | genre_ratings, 264 | formatter={"float_kind": lambda x: "%.1f" % x}, 265 | separator=",", 266 | suppress_small=True, 267 | ), 268 | items[i, 2].astype(float), # movie average rating 269 | movie_id, 270 | movie_dict[movie_id]["title"], 271 | movie_dict[movie_id]["genres"], 272 | ] 273 | ) 274 | 275 | table = tabulate.tabulate( 276 | disp, 277 | tablefmt="html", 278 | headers="firstrow", 279 | floatfmt=[".1f", ".1f", ".0f", ".2f", ".1f"], 280 | ) 281 | return table 282 | -------------------------------------------------------------------------------- /src/old_lectures/utils/recsysNN_utils.py: -------------------------------------------------------------------------------- 1 | """Utilities for RecSysNN implementation""" 2 | 3 | from collections import defaultdict 4 | import csv 5 | import numpy as np 6 | 7 | import pickle 8 | 9 | import tabulate 10 | 11 | 12 | def load_data(): 13 | """called to load preprepared data for the lab""" 14 | item_train = np.genfromtxt("../../data/content_item_train.csv", delimiter=",") 15 | user_train = np.genfromtxt("../../data/content_user_train.csv", delimiter=",") 16 | y_train = np.genfromtxt("../../data/content_y_train.csv", delimiter=",") 17 | with open( 18 | "../data/content_item_train_header.txt", newline="" 19 | ) as f: # csv reader handles quoted strings better 20 | item_features = list(csv.reader(f))[0] 21 | with open("../data/content_user_train_header.txt", newline="") as f: 22 | user_features = list(csv.reader(f))[0] 23 | item_vecs = np.genfromtxt("../../data/content_item_vecs.csv", delimiter=",") 24 | 25 | movie_dict = defaultdict(dict) 26 | count = 0 27 | # with open('./data/movies.csv', newline='') as csvfile: 28 | with open("../../data/content_movie_list.csv", newline="") as csvfile: 29 | reader = csv.reader(csvfile, delimiter=",", quotechar='"') 30 | for line in reader: 31 | if count == 0: 32 | count += 1 # skip header 33 | # print(line) print 34 | else: 35 | count += 1 36 | movie_id = int(line[0]) 37 | movie_dict[movie_id]["title"] = line[1] 38 | movie_dict[movie_id]["genres"] = line[2] 39 | 40 | with open("../../data/content_user_to_genre.pickle", "rb") as f: 41 | user_to_genre = pickle.load(f) 42 | 43 | return ( 44 | item_train, 45 | user_train, 46 | y_train, 47 | item_features, 48 | user_features, 49 | item_vecs, 50 | movie_dict, 51 | user_to_genre, 52 | ) 53 | 54 | 55 | def pprint_train(x_train, features, vs, u_s, maxcount=5, user=True): 56 | """Prints user_train or item_train nicely""" 57 | if user: 58 | flist = [ 59 | ".0f", 60 | ".0f", 61 | ".1f", 62 | ".1f", 63 | ".1f", 64 | ".1f", 65 | ".1f", 66 | ".1f", 67 | ".1f", 68 | ".1f", 69 | ".1f", 70 | ".1f", 71 | ".1f", 72 | ".1f", 73 | ".1f", 74 | ".1f", 75 | ".1f", 76 | ] 77 | else: 78 | flist = [ 79 | ".0f", 80 | ".0f", 81 | ".1f", 82 | ".0f", 83 | ".0f", 84 | ".0f", 85 | ".0f", 86 | ".0f", 87 | ".0f", 88 | ".0f", 89 | ".0f", 90 | ".0f", 91 | ".0f", 92 | ".0f", 93 | ".0f", 94 | ".0f", 95 | ".0f", 96 | ] 97 | 98 | head = features[:vs] 99 | if vs < u_s: 100 | print("error, vector start {vs} should be greater then user start {u_s}") 101 | for i in range(u_s): 102 | head[i] = "[" + head[i] + "]" 103 | genres = features[vs:] 104 | hdr = head + genres 105 | disp = [split_str(hdr, 5)] 106 | count = 0 107 | for i in range(0, x_train.shape[0]): 108 | if count == maxcount: 109 | break 110 | count += 1 111 | disp.append( 112 | [ 113 | x_train[i, 0].astype(int), 114 | x_train[i, 1].astype(int), 115 | x_train[i, 2].astype(float), 116 | *x_train[i, 3:].astype(float), 117 | ] 118 | ) 119 | table = tabulate.tabulate( 120 | disp, tablefmt="html", headers="firstrow", floatfmt=flist, numalign="center" 121 | ) 122 | return table 123 | 124 | 125 | def split_str(ifeatures, smax): 126 | """split the feature name strings to tables fit""" 127 | ofeatures = [] 128 | for s in ifeatures: 129 | if not " " in s: # skip string that already have a space 130 | if len(s) > smax: 131 | mid = int(len(s) / 2) 132 | s = s[:mid] + " " + s[mid:] 133 | ofeatures.append(s) 134 | return ofeatures 135 | 136 | 137 | def print_pred_movies(y_p, item, movie_dict, maxcount=10): 138 | """print results of prediction of a new user. inputs are expected to be in 139 | sorted order, unscaled.""" 140 | count = 0 141 | disp = [["y_p", "movie id", "rating ave", "title", "genres"]] 142 | 143 | for i in range(0, y_p.shape[0]): 144 | if count == maxcount: 145 | break 146 | count += 1 147 | movie_id = item[i, 0].astype(int) 148 | disp.append( 149 | [ 150 | np.around(y_p[i, 0], 1), 151 | item[i, 0].astype(int), 152 | np.around(item[i, 2].astype(float), 1), 153 | movie_dict[movie_id]["title"], 154 | movie_dict[movie_id]["genres"], 155 | ] 156 | ) 157 | 158 | table = tabulate.tabulate(disp, tablefmt="html", headers="firstrow") 159 | return table 160 | 161 | 162 | def gen_user_vecs(user_vec, num_items): 163 | """given a user vector return: 164 | user predict maxtrix to match the size of item_vecs""" 165 | user_vecs = np.tile(user_vec, (num_items, 1)) 166 | return user_vecs 167 | 168 | 169 | # predict on everything, filter on print/use 170 | def predict_uservec(user_vecs, item_vecs, model, u_s, i_s, scaler): 171 | """given a scaled user vector, does the prediction on all movies in scaled print_item_vecs returns 172 | an array predictions sorted by predicted rating, 173 | arrays of user and item, sorted by predicted rating sorting index 174 | """ 175 | y_p = model.predict([user_vecs[:, u_s:], item_vecs[:, i_s:]]) 176 | y_pu = scaler.inverse_transform(y_p) 177 | 178 | if np.any(y_pu < 0): 179 | print("Error, expected all positive predictions") 180 | sorted_index = ( 181 | np.argsort(-y_pu, axis=0).reshape(-1).tolist() 182 | ) # negate to get largest rating first 183 | sorted_ypu = y_pu[sorted_index] 184 | sorted_items = item_vecs[sorted_index] 185 | sorted_user = user_vecs[sorted_index] 186 | return (sorted_index, sorted_ypu, sorted_items, sorted_user) 187 | 188 | 189 | def get_user_vecs(user_id, user_train, item_vecs, user_to_genre): 190 | """given a user_id, return: 191 | user train/predict matrix to match the size of item_vecs 192 | y vector with ratings for all rated movies and 0 for others of size item_vecs""" 193 | 194 | if not user_id in user_to_genre: 195 | print("error: unknown user id") 196 | return None 197 | else: 198 | user_vec_found = False 199 | for i in range(len(user_train)): 200 | if user_train[i, 0] == user_id: 201 | user_vec = user_train[i] 202 | user_vec_found = True 203 | break 204 | if not user_vec_found: 205 | print("error in get_user_vecs, did not find uid in user_train") 206 | num_items = len(item_vecs) 207 | user_vecs = np.tile(user_vec, (num_items, 1)) 208 | 209 | y = np.zeros(num_items) 210 | for i in range( 211 | num_items 212 | ): # walk through movies in item_vecs and get the movies, see if user has rated them 213 | movie_id = item_vecs[i, 0] 214 | if movie_id in user_to_genre[user_id]["movies"]: 215 | rating = user_to_genre[user_id]["movies"][movie_id] 216 | else: 217 | rating = 0 218 | y[i] = rating 219 | return (user_vecs, y) 220 | 221 | 222 | def get_item_genres(item_gvec, genre_features): 223 | """takes in the item's genre vector and list of genre names 224 | returns the feature names where gvec was 1""" 225 | offsets = np.nonzero(item_gvec)[0] 226 | genres = [genre_features[i] for i in offsets] 227 | return genres 228 | 229 | 230 | def print_existing_user(y_p, y, user, items, ivs, uvs, movie_dict, maxcount=10): 231 | """print results of prediction for a user who was in the database. 232 | Inputs are expected to be in sorted order, unscaled. 233 | """ 234 | count = 0 235 | disp = [ 236 | [ 237 | "y_p", 238 | "y", 239 | "user", 240 | "user genre ave", 241 | "movie rating ave", 242 | "movie id", 243 | "title", 244 | "genres", 245 | ] 246 | ] 247 | count = 0 248 | for i in range(0, y.shape[0]): 249 | if y[i, 0] != 0: # zero means not rated 250 | if count == maxcount: 251 | break 252 | count += 1 253 | movie_id = items[i, 0].astype(int) 254 | 255 | offsets = np.nonzero(items[i, ivs:] == 1)[0] 256 | genre_ratings = user[i, uvs + offsets] 257 | disp.append( 258 | [ 259 | y_p[i, 0], 260 | y[i, 0], 261 | user[i, 0].astype(int), # userid 262 | np.array2string( 263 | genre_ratings, 264 | formatter={"float_kind": lambda x: "%.1f" % x}, 265 | separator=",", 266 | suppress_small=True, 267 | ), 268 | items[i, 2].astype(float), # movie average rating 269 | movie_id, 270 | movie_dict[movie_id]["title"], 271 | movie_dict[movie_id]["genres"], 272 | ] 273 | ) 274 | 275 | table = tabulate.tabulate( 276 | disp, 277 | tablefmt="html", 278 | headers="firstrow", 279 | floatfmt=[".1f", ".1f", ".0f", ".2f", ".1f"], 280 | ) 281 | return table 282 | -------------------------------------------------------------------------------- /src/04.ContentBasedFiltering.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "id": "HbeLYBblwZLC" 7 | }, 8 | "source": [ 9 | "# Introduction to Recommender Systems\n", 10 | "\n", 11 | "

\n", 12 | " \"cover-image\"\n", 13 | "

\n", 14 | "\n", 15 | "---\n", 16 | "\n", 17 | "# 🎓 Content-Based Filtering\n", 18 | "\n", 19 | "---\n", 20 | "\n", 21 | "## Introduction\n", 22 | "\n", 23 | "A detailed exploration of CBF, covering theory, equations, metrics, and ML-based training.\n", 24 | "\n", 25 | "# 📌 Content-Based Filtering (CBF): A Complete Guide\n", 26 | "*A detailed exploration of CBF, covering theory, equations, metrics, and ML-based training.*\n", 27 | "\n", 28 | "---\n", 29 | "\n", 30 | "## **1️⃣ Introduction: What is Content-Based Filtering?**\n", 31 | "Content-Based Filtering (**CBF**) is a **recommendation technique** that suggests items to users **based on item features** rather than other users' interactions. It is widely used in **search engines, personalized content delivery, and document recommendations**.\n", 32 | "\n", 33 | "### **🔹 How It Works**\n", 34 | "- **Each item (e.g., document, movie, product)** is represented by a **feature vector**.\n", 35 | "- The system **compares item features** to those of items a user has interacted with.\n", 36 | "- The system recommends **items similar to those the user liked in the past**.\n", 37 | "\n", 38 | "### **🔹 Key Characteristics**\n", 39 | "✔ **Does not rely on other users' preferences** (unlike collaborative filtering). \n", 40 | "✔ **Requires metadata or content features** (e.g., text, keywords, embeddings). \n", 41 | "✔ **Great for personalised recommendations** but **suffers from over-specialization**.\n", 42 | "\n", 43 | "### **🔹 Real-World Applications**\n", 44 | "✔ **Search engines**: Ranking documents based on query similarity. \n", 45 | "✔ **News recommendation**: Suggesting articles similar to ones a user has read. \n", 46 | "✔ **E-learning**: Recommending study materials similar to previous lessons. \n", 47 | "\n", 48 | "---\n", 49 | "\n", 50 | "## **2️⃣ Mathematical Foundations of Content-Based Filtering**\n", 51 | "CBF operates by representing items as **feature vectors** and measuring their **similarity**.\n", 52 | "\n", 53 | "### **🔹 Step 1: Representing Items as Feature Vectors**\n", 54 | "Let **N** items be represented as **d-dimensional vectors**:\n", 55 | "\n", 56 | "$$\n", 57 | "\\mathbf{x}_i = (x_{i1}, x_{i2}, ..., x_{id}) \\in \\mathbb{R}^d\n", 58 | "$$\n", 59 | "\n", 60 | "where:\n", 61 | "- $ x_i $ represents the **i-th document/item**.\n", 62 | "- Each element $ x_{ij} $ represents a **feature weight** (e.g., word frequency in TF-IDF).\n", 63 | "\n", 64 | "### **🔹 Step 2: Computing Similarity Between Items**\n", 65 | "The similarity between two items is calculated using **Cosine Similarity**:\n", 66 | "\n", 67 | "$$\n", 68 | "\\text{sim}(\\mathbf{x}_i, \\mathbf{x}_j) = \\frac{\\mathbf{x}_i \\cdot \\mathbf{x}_j}{\\|\\mathbf{x}_i\\| \\|\\mathbf{x}_j\\|}\n", 69 | "$$\n", 70 | "\n", 71 | "where:\n", 72 | "- $ \\mathbf{x}_i \\cdot \\mathbf{x}_j $ is the **dot product**.\n", 73 | "- $ \\|\\mathbf{x}_i\\| $ and $ \\|\\mathbf{x}_j\\| $ are the **vector magnitudes**.\n", 74 | "\n", 75 | "If **sim(x1, x2) = 1**, they are identical; if **sim(x1, x2) = 0**, they are unrelated.\n", 76 | "\n", 77 | "---\n", 78 | "\n", 79 | "## **3️⃣ Implementing a Basic Content-Based Recommender System**\n", 80 | "\n", 81 | "We first **vectorise documents using TF-IDF** and then **compute similarity scores**.\n", 82 | "\n", 83 | "### **🔹 Step 1: Feature Extraction (TF-IDF)**\n", 84 | "```python\n", 85 | "from sklearn.feature_extraction.text import TfidfVectoriser\n", 86 | "\n", 87 | "# Sample documents (text corpus)\n", 88 | "documents = [\n", 89 | " \"Deep learning revolutionises AI.\",\n", 90 | " \"AI is transforming industries.\",\n", 91 | " \"Bioinformatics integrates biology and data science.\",\n", 92 | " \"Natural language processing models are complex.\"\n", 93 | "]\n", 94 | "\n", 95 | "# Convert documents into TF-IDF vectors\n", 96 | "vectorizer = TfidfVectorizer(stop_words='english')\n", 97 | "doc_vectors = vectorizer.fit_transform(documents).toarray()\n", 98 | "```\n", 99 | "\n", 100 | "### **🔹 Step 2: Compute Similarity Scores**\n", 101 | "\n", 102 | "```python\n", 103 | "from sklearn.metrics.pairwise import cosine_similarity\n", 104 | "\n", 105 | "# Compute similarity matrix\n", 106 | "similarity_matrix = cosine_similarity(doc_vectors, doc_vectors)\n", 107 | "\n", 108 | "# Print similarity scores\n", 109 | "import pandas as pd\n", 110 | "df_sim = pd.DataFrame(similarity_matrix, index=documents, columns=documents)\n", 111 | "print(df_sim)\n", 112 | "```\n", 113 | "\n", 114 | "---\n", 115 | "\n", 116 | "## **4️⃣ Evaluating the Recommender System**\n", 117 | "\n", 118 | "Once recommendations are generated, we must evaluate their effectiveness. We have seen the several kinds of metrics used to evaluate recommender systems.\n", 119 | "\n", 120 | "### 🔹 Precision@K and Recall@K\n", 121 | "\n", 122 | "$$\n", 123 | "\\text{Precision@K} = \\frac{\\text{number of relevant recommended items in top-K}}{K}\n", 124 | "$$\n", 125 | "\n", 126 | "$$\n", 127 | "\\text{Recall@K} = \\frac{\\text{number of relevant recommended items in top-K}}{\\text{total number of relevant items}}\n", 128 | "$$\n", 129 | "\n", 130 | "### 🔹 Normalised discount cumulative gain (NDCG)\n", 131 | "\n", 132 | "$$\n", 133 | "\\text{NDCG@K} = \\frac{\\text{DCG@K}}{\\text{IDCG@K}}\n", 134 | "$$\n", 135 | "\n", 136 | "where, \n", 137 | "\n", 138 | "$$\n", 139 | "\\text{DCG@K} = \\sum_{i=1}^{K} \\frac{2^{rel_i} - 1}{\\log_2(i+1)}\n", 140 | "$$\n", 141 | "where, $rel_i$ is the ground truth relevance score of the $i^{th}$ item in the top-K list.\n", 142 | "\n", 143 | "---\n", 144 | "\n", 145 | "## **5️⃣ Train a ML model for content-based filtering**\n", 146 | "\n", 147 | "Instead of using cosine similarity as it is, we now train an ML model to predict item relevance.\n", 148 | "\n", 149 | "### 🔹 Step 1: Get user interaction data\n", 150 | "\n", 151 | "The first step is preparing the data for training. We will use the user-item interaction data for this purpose.\n", 152 | "These are contained in the dataframe `df_ranking` we imported a couple of lectures ago.\n", 153 | "\n", 154 | "### 🔹 Step 2: Train a model\n", 155 | "\n", 156 | "We will use a simple Logistic Regression model for this purpose. We will use the `LogisticRegression` class from the `sklearn.linear_model` module.\n", 157 | "\n", 158 | "### 🔹 Step 3: Evaluate the model\n", 159 | "\n", 160 | "We can make use of the metrics defined above to assess the performance of our model.\n", 161 | "\n", 162 | "---\n", 163 | "\n", 164 | "## **6️⃣ Learning-to-Rank: Optimising the Ranking Order**\n", 165 | "\n", 166 | "A more advanced and interesting approach is Learning-to-Rank (LTR), which directly optimizes ranking performance.\n", 167 | "\n", 168 | "### **🔹 Listwise Learning-to-Rank with XGBoost**\n", 169 | "\n", 170 | "XGBoost is a popular gradient boosting library that can be used for LTR. It is a powerful tool for regression and classification tasks, but it can also be used for ranking tasks.\n", 171 | "\n", 172 | "```python\n", 173 | "from xgboost import XGBRanker\n", 174 | "\n", 175 | "# Define group structure (how many docs per query)\n", 176 | "group = [len(df_interactions)]\n", 177 | "\n", 178 | "# Train an XGBoost Ranker\n", 179 | "ltr_model = XGBRanker(\n", 180 | " objective=\"rank:ndcg\",\n", 181 | " eval_metric=\"ndcg\",\n", 182 | " booster=\"gbtree\",\n", 183 | " eta=0.1,\n", 184 | " max_depth=3,\n", 185 | " n_estimators=50\n", 186 | ")\n", 187 | "\n", 188 | "ltr_model.fit(X, y, group)\n", 189 | "```\n", 190 | "\n", 191 | "\n", 192 | "We can use this model to predict and rank the movies for a given user.\n", 193 | "\n", 194 | "```python\n", 195 | "# Predict relevance scores\n", 196 | "predicted_scores = ltr_model.predict(X)\n", 197 | "\n", 198 | "# Rank documents based on predicted scores\n", 199 | "df_interactions[\"predicted_relevance\"] = predicted_scores\n", 200 | "df_interactions.sort_values(\"predicted_relevance\", ascending=False, inplace=True)\n", 201 | "\n", 202 | "print(df_interactions[[\"doc_id\", \"predicted_relevance\"]])\n", 203 | "```\n", 204 | "---\n", 205 | "\n", 206 | "## ** 7️⃣ Summary: Comparing Methods **\n", 207 | "\n", 208 | "| **Method** | **Pros** | **Cons** |\n", 209 | "|-----------|---------|---------|\n", 210 | "| **Cosine Similarity** | Simple, No Training Required | Cannot learn from user behaviour |\n", 211 | "| **Logistic Regression** | Learns from data | May not optimise ranking well |\n", 212 | "| **XGBoost Ranker (LTR)** | Optimised for ranking tasks | Requires labelled training data |\n", 213 | "\n", 214 | "🚀 **Next Steps:** \n", 215 | "1. **Expand to large datasets** (e.g., Wikipedia, ArXiv). \n", 216 | "2. **Use deep learning models (BERT Ranker)**. \n", 217 | "3. **Integrate hybrid filtering (content + collaborative filtering)**. \n" 218 | ] 219 | }, 220 | { 221 | "cell_type": "markdown", 222 | "metadata": { 223 | "id": "qr4u289CwZLE" 224 | }, 225 | "source": [ 226 | "## Packages \n", 227 | "We will use the now familiar NumPy and pandas Packages." 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": 1, 233 | "metadata": { 234 | "id": "_FNjoZPwwZLE" 235 | }, 236 | "outputs": [], 237 | "source": [ 238 | "import numpy as np\n", 239 | "import pandas as pd\n", 240 | "from sklearn.metrics import precision_score, recall_score, f1_score\n", 241 | "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", 242 | "from sklearn.feature_extraction.text import TfidfVectorizer\n", 243 | "from sklearn.neighbors import NearestNeighbors\n", 244 | "from sklearn.metrics.pairwise import cosine_similarity\n", 245 | "\n", 246 | "import random\n", 247 | "\n", 248 | "import matplotlib.pyplot as plt\n", 249 | "import seaborn as sns\n", 250 | "\n", 251 | "# set plot size\n", 252 | "plt.rcParams[\"figure.figsize\"] = (20, 13)\n", 253 | "sns.set_theme()\n", 254 | "%matplotlib inline\n", 255 | "%config InlineBackend.figure_format = \"retina\"" 256 | ] 257 | }, 258 | { 259 | "cell_type": "markdown", 260 | "metadata": {}, 261 | "source": [ 262 | "## 📚 Guided Exercise: Implementing Content-Based Filtering on a Books Recommendation Dataset\n", 263 | "\n", 264 | "The aim of this exercise is to implement a content-based filtering system for a books recommendation dataset. The dataset contains information about books, including their titles, authors, genres, and descriptions. The goal is to recommend books to users based on their preferences and the content of the books.\n", 265 | "\n", 266 | "### Step 1: Load the Dataset\n", 267 | "\n", 268 | "Load the dataset into a pandas DataFrame. The dataset is available at [this link](https://www.kaggle.com/datasets/arashnic/book-recommendation-dataset).\n", 269 | "\n", 270 | "There are 3 interesting files in the dataset: \n", 271 | "\n", 272 | "* books.csv: contains information about the books.\n", 273 | "* users.csv: contains information about the users.\n", 274 | "* ratings.csv: contains information about the ratings given by the users to the books.\n", 275 | "\n", 276 | "### Step 2: Preprocess the Data\n", 277 | "\n", 278 | "Preprocess the data to make it suitable for content-based filtering. This should include:\n", 279 | "\n", 280 | "* Handling missing values\n", 281 | "* Encoding categorical variables\n", 282 | "* Creating a content-based feature matrix\n", 283 | "\n", 284 | "### Step 3: Implement Content-Based Filtering\n", 285 | "\n", 286 | "Implement content-based filtering to recommend books to users. This should include:\n", 287 | "\n", 288 | "* Calculating the similarity between books (you can use the system you prefer)\n", 289 | "* Recommending books to users based on their preferences\n", 290 | "\n", 291 | "### Step 4: Evaluate the System\n", 292 | "\n", 293 | "Evaluate the performance of the content-based filtering system. This should include:\n", 294 | "\n", 295 | "* Calculating metrics such as precision, recall, and F1-score\n", 296 | "* Comparing the performance of the content-based filtering system with at least one other recommendation system.\n", 297 | "\n", 298 | "### Step 5: Visualise the Results\n", 299 | "\n", 300 | "Visualize the results of the content-based filtering system. This should include:\n", 301 | "\n", 302 | "* Creating visualisations to show the performance of the system\n", 303 | "* Creating visualisations to show the recommendations made by the system\n" 304 | ] 305 | } 306 | ], 307 | "metadata": { 308 | "colab": { 309 | "provenance": [] 310 | }, 311 | "kernelspec": { 312 | "display_name": "rec-sys", 313 | "language": "python", 314 | "name": "python3" 315 | }, 316 | "language_info": { 317 | "codemirror_mode": { 318 | "name": "ipython", 319 | "version": 3 320 | }, 321 | "file_extension": ".py", 322 | "mimetype": "text/x-python", 323 | "name": "python", 324 | "nbconvert_exporter": "python", 325 | "pygments_lexer": "ipython3", 326 | "version": "3.9.21" 327 | }, 328 | "orig_nbformat": 4 329 | }, 330 | "nbformat": 4, 331 | "nbformat_minor": 0 332 | } 333 | -------------------------------------------------------------------------------- /src/01.Introduction.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# Introduction to Recommender Systems\n", 9 | "\n", 10 | "

\n", 11 | " \"cover-image\"\n", 12 | "

\n", 13 | "\n", 14 | "---\n", 15 | "\n", 16 | "# Introduction\n", 17 | "\n", 18 | "## The Power of Recommendation Systems\n", 19 | "\n", 20 | "Recommendation systems are one of the most useful applications of machine learning and nowadays it seems to take more and more place in our lives. There are many web-services like YouTube, Amazon, Netflix or Spotify running powerful recommendation engines.\n", 21 | "\n", 22 | "In a general way, _recommendation systems are algorithms which suggests relevant items to users_. For example: movies to watch on your Netflix account, or products to buy on your Amazon account, or videos to watch on YouTube, or music to listen on Spotify, or anything else depending on the industry.\n", 23 | "\n", 24 | "Nowadays, customers are faced with multiple choices because there are millions of products available online and recommendation sections help them to find desired ones. It is something we cannot imagine modern e-Commerce or online media without it.\n", 25 | "\n", 26 | "## Why do we need recommender systems?\n", 27 | "\n", 28 | "In today's digital landscape, the sheer volume of information and options available to users has grown exponentially. This information explosion presents a significant challenge: it is virtually impossible for individuals to manually explore all the available choices. This issue is particularly evident in various domains where content and product offerings are vast.\n", 29 | "\n", 30 | "**Examples of Information Overload**:\n", 31 | "1. Streaming Services: Platforms like Netflix boast extensive catalogues, with over 6,000 movies and countless TV shows. Navigating through such a vast library to find something appealing can be overwhelming for users.\n", 32 | "\n", 33 | "2. E-commerce Platforms: Online marketplaces such as Amazon offer millions of products across numerous categories. The diversity and quantity of items make it difficult for shoppers to discover products that suit their needs and preferences.\n", 34 | "\n", 35 | "3. Music Streaming: Services like Spotify provide access to over 100 million tracks. With such an enormous collection, users often struggle to find new music that aligns with their tastes without some form of guidance.\n", 36 | "\n", 37 | "In response to this challenge, recommendation algorithms have become indispensable. These algorithms analyse user behaviour, preferences, and historical data to suggest relevant content or products. Without these intelligent systems, users would be left to sift through an overwhelming amount of information, leading to frustration and a poor user experience. By leveraging recommendation algorithms, platforms can enhance user satisfaction and engagement, making the digital landscape more navigable and enjoyable.\n", 38 | "\n", 39 | "## Different kinds of recommender systems\n", 40 | "\n", 41 | "Recommender systems can be categorised based on the techniques they employ to generate recommendations. Here are the primary types:\n", 42 | "\n", 43 | "**Content-Based Filtering**: This approach recommends items based on the features of the items themselves. For example, a movie recommendation system might suggest films similar to those a user has liked in the past, based on attributes like genre, director, or actors.\n", 44 | "\n", 45 | "**Collaborative Filtering**: This method relies on the interactions and preferences of multiple users to make recommendations. It can be further divided into:\n", 46 | "\n", 47 | "**User-Based Collaborative Filtering**: Recommends items by finding similarities between users. If User A and User B have similar tastes, items liked by User A can be recommended to User B.\n", 48 | "**Item-Based Collaborative Filtering**: Recommends items by finding similarities between items. If Item X and Item Y are liked by many of the same users, then users who like Item X might also like Item Y.\n", 49 | "**Hybrid Systems: These systems combine content-based and collaborative filtering methods to leverage the strengths of both approaches. By integrating different techniques, hybrid systems can provide more accurate and robust recommendations.\n", 50 | "\n", 51 | "**Context-Aware Recommender Systems**: These systems consider the context in which a recommendation is made, such as time, location, or the user's current activity. For example, a music streaming service might recommend different playlists based on whether the user is at home or at the gym.\n", 52 | "\n", 53 | "**Demographic-Based Systems**: These systems use demographic information about users, such as age, gender, or occupation, to make recommendations. For instance, a book recommendation system might suggest different titles to users based on their age group.\n", 54 | "\n", 55 | "**Knowledge-Based Systems**: These systems use explicit knowledge about items and user preferences to make recommendations. For example, a travel recommendation system might use information about destinations and user preferences for certain types of activities to suggest vacation spots.\n", 56 | "\n", 57 | "Each type of recommender system has its own strengths and is suited to different kinds of applications and data availability. The choice of system depends on the specific needs and constraints of the recommendation task at hand.\n", 58 | "\n", 59 | "## Personalised vs non-personalised recommender systems\n", 60 | "\n", 61 | "There are different kind of recommender systems. The most general split we can do about recommender systems is in two types:\n", 62 | "1. Personalised\n", 63 | "2. Non-Personalised\n", 64 | "\n", 65 | "### Personalised recommendations\n", 66 | "\n", 67 | "Giving a personalised recommendation to the user requires to know specific information about this user. You should know what are the features of products that this user likes or dislikes according to his past behaviour and purchasing history on your web-site.\n", 68 | "\n", 69 | "For example: You should know what kind of movies I liked based on my historical movie ratings (for example I like Sci-Fi movies) and according to this information you can recommend moves that I might like. You can find movies which have high chance to be liked by me in a two ways:\n", 70 | "\n", 71 | "1. _Item to item similarity_: Suggest me to watch other movies which are similar to the movies I already liked (which items are similar to the items I already liked).\n", 72 | "2. _User to user similarity_: Suggest me to watch other movies that users which are similar to me have already liked and I have not seen yet (which user is similar to me according to my and his historical behaviour/interest).\n", 73 | "\n", 74 | "To summarise what personalised recommendation system tries to do in a simple way, before we deep dive into this topic in the next lectures.\n", 75 | "\n", 76 | "* Predicts the rating the user may give to the products which he has not tried yet. Predictions are made based on user’s taste and preferences which is designed according to his historical behaviour on your web-site (purchased items, ratings or some other interactions).\n", 77 | "* Sorts the products according to the predicted rating in descending order and recommends top N items from this list to the user\n", 78 | "\n", 79 | "So as you can see in personalised systems users individual likes and dislikes (historical ratings) are considered to generate customised recommendations for them. There can be two kind of users rating:\n", 80 | "\n", 81 | "1. **Explicit Ratings**: If user can rate something that he purchased on your web-site, you have explicit ratings. It is direct information from users, so you are $100\\%$ accurate how they liked products/services which they purchased. For example on Amazon one can rate items it has purchased.\n", 82 | "2. **Implicit Ratings**: If you do not have web-site like Amazon where users can directly rate some items or if your customers do not use this functionality and you have many items that are unrated, you can use _implicit ratings_. Imagine, you have an online gambling web-site where people can play some games, you can think about things which might means that they liked a game or not. For instance: time or money spent on this game compared to another game. Or if you have a web-site where you are selling the tickets of bus, theatre, events or something else you can say that if user purchased something it also means that they liked it without extra explorations.\n", 83 | "\n", 84 | "A further logical split of recommender system models can be the one making reference to three categories: **content based systems**, **collaborative filtering systems**, and **hybrid systems** (which use a combination of the other two).\n", 85 | "\n", 86 | "

\n", 87 | " \"image\"\n", 88 | "

\n", 89 | "\n", 90 | "**Content based systems** use item features in order to recommend objects with similar properties. \n", 91 | "On the other hand, **Collaborative filtering systems** build a model from users' past behaviours, as well as decision made by similar users.\n", 92 | "\n", 93 | "### Non-Personalised Recommendations\n", 94 | "\n", 95 | "Non-Personalised recommendations means we do not need to know specific information about the users preferences. So if the historical data of users ratings or purchases are not available one cannot generate customised recommendation for them. That does not mean that this kind of recommendations are less important. There are several examples of non-personalised recommendations that show interesting content.\n", 96 | "\n", 97 | "

\n", 98 | " \"image\"\n", 99 | "

\n", 100 | "\n", 101 | "The most simple non-personalised recommendations are based on items popularity. A recommendation comes from what people like. \n", 102 | "For example: you are suggesting to watch the movie _Titanic_ for all of your customers because _Titanic_ is one of the most popular movie and you hope that it will be also interesting for those who have not seen yet. \n", 103 | "\n", 104 | "I am sure you have seen recommendations of popular items like this:\n", 105 | "\n", 106 | "1. Best-seller\n", 107 | "2. Most popular\n", 108 | "3. Trending hot\n", 109 | "4. Best-liked\n", 110 | "5. Selling fast\n", 111 | "\n", 112 | "There are other kinds of non-personalised recommendations which are commonly used in e-commerce. They look more like a rule: \n", 113 | "\n", 114 | "> “People who buy X also buy Y”. \n", 115 | "\n", 116 | "For example: People who bought phone also bought phone cover. So if you are buying a phone, they will likely recommend you to add the corresponding phone cover in your basket.\n", 117 | "\n", 118 | "This kind of recommendation is non-personalised because they are not using your individual ratings/taste or preferences to recommend you the phone cover. Instead, they know that phone and phone cover are associated items, because they are frequently bought together.\n", 119 | "\n", 120 | "## Primary Goals of Recommender Systems\n", 121 | "\n", 122 | "| Goal | Description | Example |\n", 123 | "|----------------|---------------------------------------------------|-----------------------------------------------------|\n", 124 | "| **Personalisation** | Tailoring content for each user | Netflix suggesting movies based on watch history |\n", 125 | "| **Discovery** | Helping users explore new items | Spotify recommending new artists |\n", 126 | "| **Efficiency** | Reducing search time and effort | Amazon showing the most relevant products first |\n", 127 | "| **Assortment** | Ensuring a diverse range of items | Netflix offering a variety of genres and languages |\n", 128 | "| **Cross-selling** | Suggesting complementary items to purchase together | Amazon suggesting phone covers when buying a phone |\n", 129 | "| **Upselling** | Encouraging users to buy higher-value items | Amazon suggesting a more expensive phone model |\n", 130 | "\n", 131 | "## Types of Recommender Systems\n", 132 | "\n", 133 | "| Approach | How It Works | Example |\n", 134 | "|----------------|---------------------------------------------------|------------------------------------------------------|\n", 135 | "| **User-Based CF** | Find users similar to you and recommend what they liked | Alice and Bob have similar watch histories, so Bob might like a movie Alice just watched |\n", 136 | "| **Item-Based CF** | Find similar items based on user interactions | People who watched *Inception* also watched *Interstellar* |\n", 137 | "| **Content-Based** | Recommend items similar to those the user liked before | If you liked *Inception*, you might like *Interstellar* because they share similar themes |\n", 138 | "| **Hybrid** | Combine multiple approaches to improve recommendations | Combining collaborative filtering and content-based methods to suggest movies |\n", 139 | "\n", 140 | "## Advanced topics\n", 141 | "\n", 142 | "We will cover a bunch of advanced topics in these lectures. In particular Deep Learning approaches to recommender systems.\n", 143 | "\n", 144 | "| Method | Description | Example |\n", 145 | "|----------------------------|---------------------------------------------------|----------------------------------|\n", 146 | "| **Neural Collaborative Filtering (NCF)** | Uses deep neural networks instead of matrix factorisation | Deep recommender models in TensorFlow/PyTorch |\n", 147 | "| **Autoencoders** | Learn compressed user-item representations | Netflix user embedding compression |\n", 148 | "| **Graph Neural Networks (GNNs)** | Capture relationships in a **user-item graph** | Pinterest’s PinSage model |\n", 149 | "| **Transformers** | Used in **sequence-aware recommendations** | YouTube/TikTok content ranking |\n", 150 | "| **Reinforcement Learning** | Learn from user interactions and feedback | Personalised news article recommendations |" 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": {}, 156 | "source": [] 157 | } 158 | ], 159 | "metadata": { 160 | "kernelspec": { 161 | "display_name": "Python 3", 162 | "language": "python", 163 | "name": "python3" 164 | }, 165 | "language_info": { 166 | "name": "python", 167 | "version": "3.9.6" 168 | }, 169 | "orig_nbformat": 4, 170 | "vscode": { 171 | "interpreter": { 172 | "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" 173 | } 174 | } 175 | }, 176 | "nbformat": 4, 177 | "nbformat_minor": 2 178 | } 179 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------