{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# Praktikum ML - Content Based Filtering\n",
    "\n",
    "\n",
    "Estimated time needed: **25** minutes\n",
    "    \n",
    "\n",
    "## Objectives\n",
    "\n",
    "After completing this lab you will be able to:\n",
    "\n",
    "* Create a recommendation system using Content Based filtering\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Recommendation systems are a collection of algorithms used to recommend items to users based on information taken from the user. These systems have become ubiquitous, and can be commonly seen in online stores, movies databases and job finders. In this notebook, we will explore Content-based recommendation systems and implement a simple version of one using Python and the Pandas library.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Table of contents\n",
    "\n",
    "<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
    "    <ol>\n",
    "        <li><a href=\"#ref1\">Acquiring the Data</a></li>\n",
    "        <li><a href=\"#ref2\">Preprocessing</a></li>\n",
    "        <li><a href=\"#ref3\">Content-Based Filtering</a></li>\n",
    "    </ol>\n",
    "</div>\n",
    "<br>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"ref1\"></a>\n",
    "# Acquiring the Data\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To acquire and extract the data, simply run the following Bash scripts:  \n",
    "Dataset acquired from [GroupLens](http://grouplens.org/datasets/movielens/). Let's download the dataset. To download the data, we will use **`!wget`** to download it from IBM Object Storage.  \n",
    "__Did you know?__ When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2025-12-02 05:05:17--  https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%205/data/moviedataset.zip\n",
      "Resolving cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)... 169.63.118.104\n",
      "Connecting to cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)|169.63.118.104|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 160301210 (153M) [application/zip]\n",
      "Saving to: ‘moviedataset.zip’\n",
      "\n",
      "moviedataset.zip     18%[==>                 ]  27.85M  1.36MB/s    eta 8m 40s "
     ]
    }
   ],
   "source": [
    "!wget -O moviedataset.zip https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%205/data/moviedataset.zip\n",
    "print('unziping ...')\n",
    "!unzip -o -j moviedataset.zip "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now you're ready to start working with the data!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"ref2\"></a>\n",
    "# Preprocessing\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, let's get all of the imports out of the way:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Dataframe manipulation library\n",
    "import pandas as pd\n",
    "#Math functions, we'll only need the sqrt function so let's import only that\n",
    "from math import sqrt\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's read each file into their Dataframes:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Storing the movie information into a pandas dataframe\n",
    "movies_df = pd.read_csv('movies.csv')\n",
    "#Storing the user information into a pandas dataframe\n",
    "ratings_df = pd.read_csv('ratings.csv')\n",
    "#Head is a function that gets the first N rows of a dataframe. N's default is 5.\n",
    "movies_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's also remove the year from the __title__ column by using pandas' replace function and store in a new __year__ column.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Using regular expressions to find a year stored between parentheses\n",
    "#We specify the parantheses so we don't conflict with movies that have years in their titles\n",
    "movies_df['year'] = movies_df.title.str.extract('(\\(\\d\\d\\d\\d\\))',expand=False)\n",
    "#Removing the parentheses\n",
    "movies_df['year'] = movies_df.year.str.extract('(\\d\\d\\d\\d)',expand=False)\n",
    "#Removing the years from the 'title' column\n",
    "movies_df['title'] = movies_df.title.str.replace('(\\(\\d\\d\\d\\d\\))', '')\n",
    "#Applying the strip function to get rid of any ending whitespace characters that may have appeared\n",
    "movies_df['title'] = movies_df['title'].apply(lambda x: x.strip())\n",
    "movies_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With that, let's also split the values in the __Genres__ column into a __list of Genres__ to simplify for future use. This can be achieved by applying Python's split string function on the correct column.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Every genre is separated by a | so we simply have to call the split function on |\n",
    "movies_df['genres'] = movies_df.genres.str.split('|')\n",
    "movies_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since keeping genres in a list format isn't optimal for the content-based recommendation system technique, we will use the One Hot Encoding technique to convert the list of genres to a vector where each column corresponds to one possible value of the feature. This encoding is needed for feeding categorical data. In this case, we store every different genre in columns that contain either 1 or 0. 1 shows that a movie has that genre and 0 shows that it doesn't. Let's also store this dataframe in another variable since genres won't be important for our first recommendation system.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Copying the movie dataframe into a new one since we won't need to use the genre information in our first case.\n",
    "moviesWithGenres_df = movies_df.copy()\n",
    "\n",
    "#For every row in the dataframe, iterate through the list of genres and place a 1 into the corresponding column\n",
    "for index, row in movies_df.iterrows():\n",
    "    for genre in row['genres']:\n",
    "        moviesWithGenres_df.at[index, genre] = 1\n",
    "#Filling in the NaN values with 0 to show that a movie doesn't have that column's genre\n",
    "moviesWithGenres_df = moviesWithGenres_df.fillna(0)\n",
    "moviesWithGenres_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, let's look at the ratings dataframe.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ratings_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every row in the ratings dataframe has a user id associated with at least one movie, a rating and a timestamp showing when they reviewed it. We won't be needing the timestamp column, so let's drop it to save memory.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Drop removes a specified row or column from a dataframe\n",
    "ratings_df = ratings_df.drop('timestamp', 1)\n",
    "ratings_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"ref3\"></a>\n",
    "# Content-Based recommendation system\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's take a look at how to implement __Content-Based__ or __Item-Item recommendation systems__. This technique attempts to figure out what a user's favourite aspects of an item is, and then recommends items that present those aspects. In our case, we're going to try to figure out the input's favorite genres from the movies and ratings given.\n",
    "\n",
    "Let's begin by creating an input user to recommend movies to:\n",
    "\n",
    "Notice: To add more movies, simply increase the amount of elements in the __userInput__. Feel free to add more in! Just be sure to write it in with capital letters and if a movie starts with a \"The\", like \"The Matrix\" then write it in like this: 'Matrix, The' .\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "userInput = [\n",
    "            {'title':'Breakfast Club, The', 'rating':5},\n",
    "            {'title':'Toy Story', 'rating':3.5},\n",
    "            {'title':'Jumanji', 'rating':2},\n",
    "            {'title':\"Pulp Fiction\", 'rating':5},\n",
    "            {'title':'Akira', 'rating':4.5}\n",
    "         ] \n",
    "inputMovies = pd.DataFrame(userInput)\n",
    "inputMovies"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Add movieId to input user\n",
    "With the input complete, let's extract the input movie's ID's from the movies dataframe and add them into it.\n",
    "\n",
    "We can achieve this by first filtering out the rows that contain the input movie's title and then merging this subset with the input dataframe. We also drop unnecessary columns for the input to save memory space.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Filtering out the movies by title\n",
    "inputId = movies_df[movies_df['title'].isin(inputMovies['title'].tolist())]\n",
    "#Then merging it so we can get the movieId. It's implicitly merging it by title.\n",
    "inputMovies = pd.merge(inputId, inputMovies)\n",
    "#Dropping information we won't use from the input dataframe\n",
    "inputMovies = inputMovies.drop('genres', 1).drop('year', 1)\n",
    "#Final input dataframe\n",
    "#If a movie you added in above isn't here, then it might not be in the original \n",
    "#dataframe or it might spelled differently, please check capitalisation.\n",
    "inputMovies"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We're going to start by learning the input's preferences, so let's get the subset of movies that the input has watched from the Dataframe containing genres defined with binary values.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Filtering out the movies from the input\n",
    "userMovies = moviesWithGenres_df[moviesWithGenres_df['movieId'].isin(inputMovies['movieId'].tolist())]\n",
    "userMovies"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll only need the actual genre table, so let's clean this up a bit by resetting the index and dropping the movieId, title, genres and year columns.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Resetting the index to avoid future issues\n",
    "userMovies = userMovies.reset_index(drop=True)\n",
    "#Dropping unnecessary issues due to save memory and to avoid issues\n",
    "userGenreTable = userMovies.drop('movieId', 1).drop('title', 1).drop('genres', 1).drop('year', 1)\n",
    "userGenreTable"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we're ready to start learning the input's preferences!\n",
    "\n",
    "To do this, we're going to turn each genre into weights. We can do this by using the input's reviews and multiplying them into the input's genre table and then summing up the resulting table by column. This operation is actually a dot product between a matrix and a vector, so we can simply accomplish by calling the Pandas \"dot\" function.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "inputMovies['rating']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Dot produt to get weights\n",
    "userProfile = userGenreTable.transpose().dot(inputMovies['rating'])\n",
    "#The user profile\n",
    "userProfile"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we have the weights for every of the user's preferences. This is known as the User Profile. Using this, we can recommend movies that satisfy the user's preferences.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's start by extracting the genre table from the original dataframe:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Now let's get the genres of every movie in our original dataframe\n",
    "genreTable = moviesWithGenres_df.set_index(moviesWithGenres_df['movieId'])\n",
    "#And drop the unnecessary information\n",
    "genreTable = genreTable.drop('movieId', 1).drop('title', 1).drop('genres', 1).drop('year', 1)\n",
    "genreTable.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "genreTable.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the input's profile and the complete list of movies and their genres in hand, we're going to take the weighted average of every movie based on the input profile and recommend the top twenty movies that most satisfy it.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Multiply the genres by the weights and then take the weighted average\n",
    "recommendationTable_df = ((genreTable*userProfile).sum(axis=1))/(userProfile.sum())\n",
    "recommendationTable_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Sort our recommendations in descending order\n",
    "recommendationTable_df = recommendationTable_df.sort_values(ascending=False)\n",
    "#Just a peek at the values\n",
    "recommendationTable_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now here's the recommendation table!\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#The final recommendation table\n",
    "movies_df.loc[movies_df['movieId'].isin(recommendationTable_df.head(20).keys())]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Advantages and Disadvantages of Content-Based Filtering\n",
    "\n",
    "##### Advantages\n",
    "* Learns user's preferences\n",
    "* Highly personalized for the user\n",
    "\n",
    "##### Disadvantages\n",
    "* Doesn't take into account what others think of the item, so low quality item recommendations might happen\n",
    "* Extracting data is not always intuitive\n",
    "* Determining what characteristics of the item the user dislikes or likes is not always obvious\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2>Want to learn more?</h2>\n",
    "\n",
    "IBM SPSS Modeler is a comprehensive analytics platform that has many machine learning algorithms. It has been designed to bring predictive intelligence to decisions made by individuals, by groups, by systems – by your enterprise as a whole. A free trial is available through this course, available here: <a href=\"https://www.ibm.com/analytics/spss-statistics-software?utm_source=skills_network&utm_content=in_lab_content_link&utm_id=Lab-IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork\">SPSS Modeler</a>\n",
    "\n",
    "Also, you can use Watson Studio to run these notebooks faster with bigger datasets. Watson Studio is IBM's leading cloud solution for data scientists, built by data scientists. With Jupyter notebooks, RStudio, Apache Spark and popular libraries pre-packaged in the cloud, Watson Studio enables data scientists to collaborate on their projects without having to install anything. Join the fast-growing community of Watson Studio users today with a free account at <a href=\"https://www.ibm.com/cloud/watson-studio?utm_source=skills_network&utm_content=in_lab_content_link&utm_id=Lab-IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork\">Watson Studio</a>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Thank you for completing this lab!\n",
    "\n",
    "\n",
    "## Author\n",
    "\n",
    "Saeed Aghabozorgi\n",
    "\n",
    "\n",
    "### Other Contributors\n",
    "\n",
    "<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a>\n",
    "\n",
    "## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n",
    "\n",
    "\n",
    "<!-- ## Change Log\n",
    "\n",
    "\n",
    "|  Date (YYYY-MM-DD) |  Version | Changed By  |  Change Description |\n",
    "|---|---|---|---|\n",
    "| 2020-11-03  | 2.1  | Lakshmi  | Updated URL of csv|\n",
    "| 2020-08-27  | 2.0  | Lavanya  |  Moved lab to course repo in GitLab |\n",
    "|   |   |   |   |\n",
    "|   |   |   |   |--!>\n",
    "\n",
    "\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  },
  "prev_pub_hash": "b5b85972d4f5eb7db7f566506fbbc694d61bf8a286a751e486938435c537a527"
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
