In this notebook, you will be putting your recommendation skills to use on real data from the IBM Watson Studio platform.
You may either submit your notebook through the workspace here, or you may work from your local machine and submit through the next page. Either way assure that your code passes the project RUBRIC. Please save regularly.
By following the table of contents, you will build out a number of different methods for making recommendations that can be used for different situations.
I. Exploratory Data Analysis
II. Rank Based Recommendations
III. User-User Based Collaborative Filtering
IV. Content Based Recommendations (EXTRA - NOT REQUIRED)
V. Matrix Factorization
VI. Extras & Concluding
At the end of the notebook, you will find directions for how to submit your work. Let's get started by importing the necessary libraries and reading in the data.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import project_tests as t
import pickle
import itertools
%matplotlib inline
user_interacts = pd.read_csv('data/user-item-interactions.csv').iloc[:, 1:]
articles = pd.read_csv('data/articles_community.csv').iloc[:, 1:]
# Show df to get an idea of the data
user_interacts.head()
article_id | title | ||
---|---|---|---|
0 | 1430.0 | using pixiedust for fast, flexible, and easier... | ef5f11f77ba020cd36e1105a00ab868bbdbf7fe7 |
1 | 1314.0 | healthcare python streaming application demo | 083cbdfa93c8444beaa4c5f5e0f5f9198e4f9e0b |
2 | 1429.0 | use deep learning for image classification | b96a4f2e92d8572034b1e9b28f9ac673765cd074 |
3 | 1338.0 | ml optimization using cognitive assistant | 06485706b34a5c9bf2a0ecdac41daf7e7654ceb7 |
4 | 1276.0 | deploy your python model as a restful api | f01220c46fc92c6e6b161b1849de11faacd7ccb2 |
# Show df_content to get an idea of the data
articles.head()
article_id | title | ||
---|---|---|---|
0 | 1430.0 | using pixiedust for fast, flexible, and easier... | ef5f11f77ba020cd36e1105a00ab868bbdbf7fe7 |
1 | 1314.0 | healthcare python streaming application demo | 083cbdfa93c8444beaa4c5f5e0f5f9198e4f9e0b |
2 | 1429.0 | use deep learning for image classification | b96a4f2e92d8572034b1e9b28f9ac673765cd074 |
3 | 1338.0 | ml optimization using cognitive assistant | 06485706b34a5c9bf2a0ecdac41daf7e7654ceb7 |
4 | 1276.0 | deploy your python model as a restful api | f01220c46fc92c6e6b161b1849de11faacd7ccb2 |
Use the dictionary and cells below to provide some insight into the descriptive statistics of the data.
1.
What is the distribution of how many articles a user interacts with in the dataset? Provide a visual and descriptive statistics to assist with giving a look at the number of times each user interacts with an article.
Each user is represented as a unique email, we could use describe to find out the descriptive statistics
num_interactions = user_interacts['email'].value_counts()
pd.DataFrame(num_interactions.describe())
count | 5148.000000 |
---|---|
mean | 8.930847 |
std | 16.802267 |
min | 1.000000 |
25% | 1.000000 |
50% | 3.000000 |
75% | 9.000000 |
max | 364.000000 |
Use histogram to visualize the distributions of number of interactions a user have with contents in this data set
num_interactions.hist(bins = 100, grid = False, figsize = (10, 7))
plt.title('distributions of number of interactions a user have with contents')
Text(0.5,1,'distributions of number of interactions a user have with contents')
Majority of users have very few interactions with the articles. It is very possible that majorities of the users are new users
# Fill in the median and maximum number of user_article interactions below
median_val = 3 # 50% of individuals interact with ____ number of articles or fewer.
max_views_by_user = 364 # The maximum number of user-article interactions by any 1 user is ______.
2.
Explore and remove duplicate articles from the df_content dataframe.
# Print the duplicated article ids
print(articles[articles['article_id'].duplicated()].article_id.values)
[1429. 1314. 1314. ... 233. 1160. 16.]
# Remove any rows that have the same article_id - only keep the first
articles = articles[~articles['article_id'].duplicated(keep='first')]
3.
Use the cells below to find:
a. The number of unique articles that have an interaction with a user.
b. The number of unique articles in the dataset (whether they have any interactions or not).
c. The number of unique users in the dataset.
d. The number of user-article interactions in the dataset.
unique_articles = len(user_interacts['article_id'].unique())
total_articles = len(articles)
unique_users = len(user_interacts['email'].dropna().unique())
user_article_interactions = len(user_interacts)
4.
Use the cells below to find the most viewed article_id, as well as how often it was viewed.
most_viewed_article_id = str(user_interacts['article_id'].value_counts().idxmax())# The most viewed article id
max_views = user_interacts['article_id'].value_counts().max() # The most number of views
## No need to change the code here - this will be helpful for later parts of the notebook
# Run this cell to map the user email to a user_id column and remove the email column
def email_mapper():
coded_dict = dict()
cter = 1
email_encoded = []
for val in user_interacts['email']:
if val not in coded_dict:
coded_dict[val] = cter
cter+=1
email_encoded.append(coded_dict[val])
return email_encoded
email_encoded = email_mapper()
del user_interacts['email']
user_interacts['user_id'] = email_encoded
# show header
user_interacts.head()
article_id | title | user_id | |
---|---|---|---|
0 | 1430.0 | using pixiedust for fast, flexible, and easier... | 1 |
1 | 1314.0 | healthcare python streaming application demo | 2 |
2 | 1429.0 | use deep learning for image classification | 3 |
3 | 1338.0 | ml optimization using cognitive assistant | 4 |
4 | 1276.0 | deploy your python model as a restful api | 5 |
## If you stored all your results in the variable names above,
## you shouldn't need to change anything in this cell
sol_1_dict = {
'`50% of individuals have _____ or fewer interactions.`': median_val,
'`The total number of user-article interactions in the dataset is ______.`': user_article_interactions,
'`The maximum number of user-article interactions by any 1 user is ______.`': max_views_by_user,
'`The most viewed article in the dataset was viewed _____ times.`': max_views,
'`The article_id of the most viewed article is ______.`': most_viewed_article_id,
'`The number of unique articles that have at least 1 rating ______.`': unique_articles,
'`The number of unique users in the dataset is ______`': unique_users,
'`The number of unique articles on the IBM platform`': total_articles
}
# Test your dictionary against the solution
t.sol_1_test(sol_1_dict)
Oops! It looks like the value associated with: `The number of unique articles on the IBM platform` wasn't right. Try again. It might just be the datatype. All of the values should be ints except the article_id should be a string. Let each row be considered a separate user-article interaction. If a user interacts with an article 3 times, these are considered 3 separate interactions.
Unlike in the earlier lessons, we don't actually have ratings for whether a user liked an article or not. We only know that a user has interacted with an article. In these cases, the popularity of an article can really only be based on how often an article was interacted with.
1.
Fill in the function below to return the n top articles ordered with most interactions as the top. Test your function using the tests below.
def get_top_articles(n, df=user_interacts):
'''
INPUT:
n - (int) the number of top articles to return
df - (pandas dataframe) df as defined at the top of the notebook, user interactions
OUTPUT:
top_articles - (list) A list of the top 'n' article titles
'''
top_articles = list(df['title'].value_counts().reset_index().head(n)['index'])
return top_articles # Return the top article titles from user interacts (not df_content)
def get_top_article_ids(n, df=user_interacts):
'''
INPUT:
n - (int) the number of top articles to return
df - (pandas dataframe) df as defined at the top of the notebook
OUTPUT:
top_articles - (list) A list of the top 'n' article titles
'''
# Your code here
top_articles = list(df['article_id'].value_counts().reset_index().head(n)['index'])
return top_articles # Return the top article ids
print(get_top_articles(10))
print(get_top_article_ids(10))
['use deep learning for image classification', 'insights from new york car accident reports', 'visualize car data with brunel', 'use xgboost, scikit-learn & ibm watson machine learning apis', 'predicting churn with the spss random tree algorithm', 'healthcare python streaming application demo', 'finding optimal locations of new store using decision optimization', 'apache spark lab, part 1: basic concepts', 'analyze energy consumption in buildings', 'gosales transactions for logistic regression model'] [1429.0, 1330.0, 1431.0, 1427.0, 1364.0, 1314.0, 1293.0, 1170.0, 1162.0, 1304.0]
# Test your function by returning the top 5, 10, and 20 articles
top_5 = get_top_articles(5)
top_10 = get_top_articles(10)
top_20 = get_top_articles(20)
# Test each of your three lists from above
t.sol_2_test(get_top_articles)
Your top_5 looks like the solution list! Nice job. Your top_10 looks like the solution list! Nice job. Your top_20 looks like the solution list! Nice job.
1.
Use the function below to reformat the df dataframe to be shaped with users as the rows and articles as the columns.
Each user should only appear in each row once.
Each article should only show up in one column.
If a user has interacted with an article, then place a 1 where the user-row meets for that article-column. It does not matter how many times a user has interacted with the article, all entries where a user has interacted with an article should be a 1.
If a user has not interacted with an item, then place a zero where the user-row meets for that article-column.
Use the tests to make sure the basic structure of your matrix matches what is expected by the solution.
def create_user_item_matrix(df):
'''
INPUT:
df - pandas dataframe with article_id, title, user_id columns
OUTPUT:
user_item - user item matrix
Description:
Return a matrix with user ids as rows and article ids on the columns with 1 values where a user interacted with
an article and a 0 otherwise
'''
# Fill in the function here
df['article_id'] = df['article_id'].astype(str)
user_item_pivot = df.groupby(['user_id', 'article_id'])['title'].count().notnull().unstack()
user_item = user_item_pivot.notnull().astype(np.int)
return user_item # return the user_item matrix
user_item = create_user_item_matrix(user_interacts)
## Tests: You should just need to run this cell. Don't change the code.
assert user_item.shape[0] == 5149, "Oops! The number of users in the user-article matrix doesn't look right."
assert user_item.shape[1] == 714, "Oops! The number of articles in the user-article matrix doesn't look right."
assert user_item.sum(axis=1)[1] == 36, "Oops! The number of articles seen by user 1 doesn't look right."
print("You have passed our quick tests! Please proceed!")
You have passed our quick tests! Please proceed!
2.
Complete the function below which should take a user_id and provide an ordered list of the most similar users to that user (from most similar to least similar). The returned result should not contain the provided user_id, as we know that each user is similar to him/herself. Because the results for each user here are binary, it (perhaps) makes sense to compute similarity as the dot product of two users.
Use the tests to test your function.
def find_similar_users(user_id, user_item=user_item):
'''
INPUT:
user_id - (int) a user_id
user_item - (pandas dataframe) matrix of users by articles:
1's when a user has interacted with an article, 0 otherwise
OUTPUT:
similar_users - (list) an ordered list where the closest users (largest dot product users)
are listed first
Description:
Computes the similarity of every pair of users based on the dot product
Returns an ordered
'''
# repeat the input user vector n times to match dimensions
num_users = user_item.shape[0]
user_vector = user_item.loc[user_id]
user_vector_tile = np.tile(user_vector.values, (num_users, 1))
# compute similarity of each user to the provided user
similarities = np.multiply(user_vector_tile, user_item).sum(axis = 1)
# sort by similarity
similarities.sort_values(ascending=False, inplace = True)
# create list of just the ids
most_similar_users = list(similarities.index)
# remove the input user itself from the most similiar users
most_similar_users.remove(user_id)
return most_similar_users # return a list of the users in order from most to least similar
# Do a spot check of your function
print("The 10 most similar users to user 1 are: {}".format(find_similar_users(1)[:10]))
print("The 5 most similar users to user 3933 are: {}".format(find_similar_users(3933)[:5]))
print("The 3 most similar users to user 46 are: {}".format(find_similar_users(46)[:3]))
The 10 most similar users to user 1 are: [3933, 23, 3782, 203, 4459, 131, 3870, 46, 4201, 5041] The 5 most similar users to user 3933 are: [1, 23, 3782, 4459, 203] The 3 most similar users to user 46 are: [4201, 23, 3782]
3.
Now that you have a function that provides the most similar users to each user, you will want to use these users to find articles you can recommend. Complete the functions below to return the articles you would recommend to each user.
def get_article_names(article_ids, df=user_interacts):
'''
INPUT:
article_ids - (list) a list of article ids
df - (pandas dataframe) df as defined at the top of the notebook, user interacts
OUTPUT:
article_names - (list) a list of article names associated with the list of article ids
(this is identified by the title column)
'''
# find the article names associated with list of article ids
article_names = (user_interacts[user_interacts['article_id'].isin(article_ids)]['title']
.drop_duplicates().values.tolist())
return article_names
def get_user_articles(user_id, user_item=user_item):
'''
INPUT:
user_id - (int) a user id
user_item - (pandas dataframe) matrix of users by articles:
1's when a user has interacted with an article, 0 otherwise
OUTPUT:
article_ids - (list) a list of the article ids seen by the user
article_names - (list) a list of article names associated with the list of article ids
(this is identified by the doc_full_name column in df_content)
Description:
Provides a list of the article_ids and article titles that have been seen by a user
'''
# Find all the user ids that a certain user has seen
user_vector = user_item.loc[user_id]
user_vector_seen = user_vector.where(user_vector == 1).dropna()
article_ids = list(user_vector_seen.index)
# Find all the article names based on the article_ids returned in the last step
article_names = get_article_names(article_ids)
return article_ids, article_names
def user_user_recs(user_id, m=10):
'''
INPUT:
user_id - (int) a user id
m - (int) the number of recommendations you want for the user
OUTPUT:
recs - (list) a list of recommendations for the user
Description:
Loops through the users based on closeness to the input user_id
For each user - finds articles the user hasn't seen before and provides them as recs
Does this until m recommendations are found
Notes:
Users who are the same closeness are chosen arbitrarily as the 'next' user
For the user where the number of recommended articles starts below m
and ends exceeding m, the last items are chosen arbitrarily
'''
# Find all articles that the user has read before
user_read_articles = get_user_articles(user_id)[0]
similar_users = find_similar_users(user_id)
# Find all articles that has been read by the similiar users
read_articles = [get_user_articles(user)[0] for user in similar_users]
read_articles_list = list(itertools.chain.from_iterable(read_articles))
# remove duplicated read articles
read_articles_unique = pd.Series(read_articles_list).drop_duplicates().tolist()
# remove articles that has been seen by the given user, use the remaining articles as recommendations
recs = [i for i in read_articles_unique if i not in user_read_articles][:m]
return recs
# Check Results
get_article_names(user_user_recs(1, 10)) # Return 10 recommendations for user 1
['analyze energy consumption in buildings', 'analyze accident reports on amazon emr spark', '520 using notebooks with pixiedust for fast, flexi...\nName: title, dtype: object', '1448 i ranked every intro to data science course on...\nName: title, dtype: object', 'data tidying in data science experience', 'airbnb data for analytics: vancouver listings', 'recommender systems: approaches & algorithms', 'airbnb data for analytics: mallorca reviews', 'analyze facebook data using ibm watson and watson studio', 'a tensorflow regression model to predict house values']
# Test your functions here - No need to change this code - just run this cell
assert set(get_article_names(['1024.0', '1176.0', '1305.0', '1314.0', '1422.0', '1427.0'])) == set(['using deep learning to reconstruct high-resolution audio', 'build a python app on the streaming analytics service', 'gosales transactions for naive bayes model', 'healthcare python streaming application demo', 'use r dataframes & ibm watson natural language understanding', 'use xgboost, scikit-learn & ibm watson machine learning apis']), "Oops! Your the get_article_names function doesn't work quite how we expect."
assert set(get_article_names(['1320.0', '232.0', '844.0'])) == set(['housing (2015): united states demographic measures','self-service data preparation with ibm data refinery','use the cloudant-spark connector in python notebook']), "Oops! Your the get_article_names function doesn't work quite how we expect."
assert set(get_user_articles(20)[0]) == set(['1320.0', '232.0', '844.0'])
assert set(get_user_articles(20)[1]) == set(['housing (2015): united states demographic measures', 'self-service data preparation with ibm data refinery','use the cloudant-spark connector in python notebook'])
assert set(get_user_articles(2)[0]) == set(['1024.0', '1176.0', '1305.0', '1314.0', '1422.0', '1427.0'])
assert set(get_user_articles(2)[1]) == set(['using deep learning to reconstruct high-resolution audio', 'build a python app on the streaming analytics service', 'gosales transactions for naive bayes model', 'healthcare python streaming application demo', 'use r dataframes & ibm watson natural language understanding', 'use xgboost, scikit-learn & ibm watson machine learning apis'])
print("If this is all you see, you passed all of our tests! Nice job!")
If this is all you see, you passed all of our tests! Nice job!
4.
Now we are going to improve the consistency of the user_user_recs function from above.
Instead of arbitrarily choosing when we obtain users who are all the same closeness to a given user - choose the users that have the most total article interactions before choosing those with fewer article interactions.
Instead of arbitrarily choosing articles from the user where the number of recommended articles starts below m and ends exceeding m, choose articles with the articles with the most total interactions before choosing those with fewer total interactions. This ranking should be what would be obtained from the top_articles function you wrote earlier.
def get_top_sorted_users(user_id, df=user_interacts, user_item=user_item):
'''
INPUT:
user_id - (int)
df - (pandas dataframe) df as defined at the top of the notebook, user interacts
user_item - (pandas dataframe) matrix of users by articles:
1's when a user has interacted with an article, 0 otherwise
OUTPUT:
neighbors_df - (pandas dataframe) a dataframe with:
neighbor_id - is a neighbor user_id
similarity - measure of the similarity of each user to the provided user_id
num_interactions - the number of articles viewed by the user - if a u
Other Details - sort the neighbors_df by the similarity and then by number of interactions where
highest of each is higher in the dataframe
'''
# repeat the input user vector n times to match dimensions
num_users = user_item.shape[0]
user_vector = user_item.loc[user_id]
user_vector_tile = np.tile(user_vector.values, (num_users, 1))
# compute similarity of each user to the provided user
similarities = pd.DataFrame(np.multiply(user_vector_tile, user_item).sum(axis = 1),
columns = ['similarity'])
# Add a column of total interactions each user have
similarities['num_interactions'] = df.groupby('user_id').count()['title'].values
# double sort on similarities and total interactions
similarities.sort_values(by = ['similarity','num_interactions'],
ascending=False, inplace = True)
# remove the inputed user him/herself
similarities.drop(user_id, inplace = True)
# build neighbors_df
neighbors_df = similarities.reset_index()
neighbors_df.columns = ['neighbor_id', 'similarity','num_interactions']
return neighbors_df
def user_user_recs_part2(user_id, m=10):
'''
INPUT:
user_id - (int) a user id
m - (int) the number of recommendations you want for the user
OUTPUT:
recs - (list) a list of recommendations for the user by article id
rec_names - (list) a list of recommendations for the user by article title
Description:
Loops through the users based on closeness to the input user_id
For each user - finds articles the user hasn't seen before and provides them as recs
Does this until m recommendations are found
Notes:
* Choose the users that have the most total article interactions
before choosing those with fewer article interactions.
* Choose articles with the articles with the most total interactions
before choosing those with fewer total interactions.
'''
user_read_articles = get_user_articles(user_id)[0]
similar_users = get_top_sorted_users(user_id)['neighbor_id'].values.tolist()
# Find all articles that has been read by the similiar users
read_articles = [get_user_articles(user)[0] for user in similar_users]
read_articles_list = list(itertools.chain.from_iterable(read_articles))
# remove duplicated read articles
read_articles_unique = pd.Series(read_articles_list).drop_duplicates().tolist()
# remove articles that has been seen by the given user, use the remaining articles as recommendations
recs = [i for i in read_articles_unique if i not in user_read_articles][:m]
rec_names = get_article_names(recs)
return recs, rec_names
# Quick spot check - don't change this code - just use it to test your functions
rec_ids, rec_names = user_user_recs_part2(20, 10)
print("The top 10 recommendations for user 20 are the following article ids:")
rec_ids
The top 10 recommendations for user 20 are the following article ids:
['1024.0', '1085.0', '109.0', '1150.0', '1151.0', '1152.0', '1153.0', '1154.0', '1157.0', '1160.0']
print("The top 10 recommendations for user 20 are the following article names:")
rec_names
The top 10 recommendations for user 20 are the following article names:
['airbnb data for analytics: washington d.c. listings', 'analyze accident reports on amazon emr spark', 'tensorflow quick tips', 'airbnb data for analytics: venice listings', 'airbnb data for analytics: venice calendar', 'airbnb data for analytics: venice reviews', 'using deep learning to reconstruct high-resolution audio', 'airbnb data for analytics: vienna listings', 'airbnb data for analytics: vienna calendar', 'airbnb data for analytics: chicago listings']
5.
Use your functions from above to correctly fill in the solutions to the dictionary below. Then test your dictionary against the solution. Provide the code you need to answer each following the comments below.
### Tests with a dictionary of results
# Find the user that is most similar to user 1
user1_most_sim = get_top_sorted_users(1)['neighbor_id'].head(1).values[0]
# Find the 10th most similar user to user 131
user131_10th_sim = get_top_sorted_users(131)['neighbor_id'].head(10).values[-1]
## Dictionary Test Here
sol_5_dict = {
'The user that is most similar to user 1.': user1_most_sim,
'The user that is the 10th most similar to user 131': user131_10th_sim,
# "The top 10 recommendations for user 20 are the following article ids:": rec_ids,
# "The top 10 recommendations for user 20 are the following article names:": rec_names
}
t.sol_5_test(sol_5_dict)
This all looks good! Nice job!
6.
If we were given a new user, which of the above functions would you be able to use to make recommendations? Explain. Can you think of a better way we might make recommendations? Use the cell below to explain a better method for new users.
If the new user is given, the user would have never seen any articles interactions in the history, which would lead to failure in the calculations of similiar vectors, since all values in user_item for that new user will be 0. The recommender will have trouble providing any meaningful recommendations for this new user.
7.
Using your existing functions, provide the top 10 recommended articles you would provide for the a new user below. You can test your function against our thoughts to make sure we are all on the same page with how we might make a recommendation.
new_user = '0.0'
# What would your recommendations be for this new user '0.0'? As a new user, they have no observed articles.
# Provide a list of the top 10 article ids you would give to
new_user_recs = get_top_article_ids(10)
assert set(new_user_recs) == set(['1314.0','1429.0','1293.0','1427.0','1162.0','1364.0','1304.0','1170.0','1431.0','1330.0']), "Oops! It makes sense that in this case we would want to recommend the most popular articles, because we don't know anything about these users."
print("That's right! Nice job!")
That's right! Nice job!
Another method we might use to make recommendations is to perform a ranking of the highest ranked articles associated with some term. You might consider content to be the doc_body, doc_description, or doc_full_name. There isn't one way to create a content based recommendation, especially considering that each of these columns hold content related information.
1.
Use the function body below to create a content based recommender. Since there isn't one right answer for this recommendation tactic, no test functions are provided. Feel free to change the function inputs if you decide you want to try a method that requires more input values. The input values are currently set with one idea in mind that you may use to make content based recommendations. One additional idea is that you might want to choose the most popular recommendations that meet your 'content criteria', but again, there is a lot of flexibility in how you might make these recommendations.
def make_content_recs():
'''
INPUT:
OUTPUT:
'''
2.
Now that you have put together your content-based recommendation system, use the cell below to write a summary explaining how your content based recommender works. Do you see any possible improvements that could be made to your function? Is there anything novel about your content based recommender?
Write an explanation of your content based recommendation system here.
3.
Use your content-recommendation system to make recommendations for the below scenarios based on the comments. Again no tests are provided here, because there isn't one right answer that could be used to find these content based recommendations.
# make recommendations for a brand new user
# make a recommendations for a user who only has interacted with article id '1427.0'
In this part of the notebook, you will build use matrix factorization to make article recommendations to the users on the IBM Watson Studio platform.
1.
You should have already created a user_item matrix above in question 1 of Part III above. This first question here will just require that you run the cells to get things set up for the rest of Part V of the notebook.
# Load the matrix here
user_item_matrix = pd.read_pickle('user_item_matrix.p')
# quick look at the matrix
user_item_matrix.head()
article_id | 0.0 | 100.0 | 1000.0 | 1004.0 | 1006.0 | 1008.0 | 101.0 | 1014.0 | 1015.0 | 1016.0 | ... | 977.0 | 98.0 | 981.0 | 984.0 | 985.0 | 986.0 | 990.0 | 993.0 | 996.0 | 997.0 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
user_id | |||||||||||||||||||||
1 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | ... | 0.0 | 0.0 | 1.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
2 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | ... | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
3 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | ... | 1.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
4 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | ... | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
5 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | ... | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
5 rows × 714 columns
2.
In this situation, you can use Singular Value Decomposition from numpy on the user-item matrix. Use the cell to perfrom SVD, and explain why this is different than in the lesson.
# Perform SVD on the User-Item Matrix
u, s, vt = np.linalg.svd(user_item_matrix)
Since there were missing data in the class, performing singular value decompositions directly will lead to errors from this opreation. However, in this project that, there were no missing data in the User-Item matrix. We are able to directly get an analytical solution out of singular value decompositions.
3.
Now for the tricky part, how do we choose the number of latent features to use? Running the below cell, you can see that as the number of latent features increases, we obtain a lower error rate on making predictions for the 1 and 0 values in the user-item matrix. Run the cell below to get an idea of how the accuracy improves as we increase the number of latent features.
num_latent_feats = np.arange(10,700+10,20)
sum_errs = []
for k in num_latent_feats:
# restructure with k latent features
s_new, u_new, vt_new = np.diag(s[:k]), u[:, :k], vt[:k, :]
# take dot product
user_item_est = np.around(np.dot(np.dot(u_new, s_new), vt_new))
# compute error for each prediction to actual value
diffs = np.subtract(user_item_matrix, user_item_est)
# total errors and keep track of them
err = np.sum(np.sum(np.abs(diffs)))
sum_errs.append(err)
plt.plot(num_latent_feats, 1 - np.array(sum_errs)/user_interacts.shape[0]);
plt.xlabel('Number of Latent Features');
plt.ylabel('Accuracy');
plt.title('Accuracy vs. Number of Latent Features');
4.
From the above, we can't really be sure how many features to use, because simply having a better way to predict the 1's and 0's of the matrix doesn't exactly give us an indication of if we are able to make good recommendations. Instead, we might split our dataset into a training and test set of data, as shown in the cell below.
Use the code from question 3 to understand the impact on accuracy of the training and test sets of data with different numbers of latent features. Using the split below:
df_train = user_interacts.head(40000)
df_test = user_interacts.tail(5993)
def create_test_and_train_user_item(df_train, df_test):
'''
INPUT:
df_train - training dataframe
df_test - test dataframe
OUTPUT:
user_item_train - a user-item matrix of the training dataframe
(unique users for each row and unique articles for each column)
user_item_test - a user-item matrix of the testing dataframe
(unique users for each row and unique articles for each column)
test_idx - all of the test user ids
test_arts - all of the test article ids
'''
user_item_train = create_user_item_matrix(df_train)
user_item_test = create_user_item_matrix(df_test)
test_idx = list(user_item_test.index)
test_arts = list(user_item_test.columns)
return user_item_train, user_item_test, test_idx, test_arts
user_item_train, user_item_test, test_idx, test_arts = create_test_and_train_user_item(df_train, df_test)
C:\Users\DELL\Anaconda3\lib\site-packages\ipykernel_launcher.py:14: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
# Replace the values in the dictionary below
a = 662
b = 574
c = 20
d = 0
sol_4_dict = {
'How many users can we make predictions for in the test set?': c,
'How many users in the test set are we not able to make predictions for because of the cold start problem?': a,
'How many movies can we make predictions for in the test set?': b,
'How many movies in the test set are we not able to make predictions for because of the cold start problem?': d
}
t.sol_4_test(sol_4_dict)
Awesome job! That's right! All of the test movies are in the training data, but there are only 20 test users that were also in the training set. All of the other users that are in the test set we have no data on. Therefore, we cannot make predictions for these users using SVD.
5.
Now use the user_item_train dataset from above to find U, S, and V transpose using SVD. Then find the subset of rows in the user_item_test dataset that you can predict using this matrix decomposition with different numbers of latent features to see how many features makes sense to keep based on the accuracy on the test data. This will require combining what was done in questions 2
- 4
.
Build functions that plot the training/test against number of latent features
# fit SVD on the user_item_train matrix
u_train, s_train, vt_train = np.linalg.svd(user_item_train)
test_rows_idx = user_item_train.index.isin(test_idx)
test_col_idxs = user_item_train.columns.isin(test_arts)
u_test = u_train[test_rows_idx, :]
vt_test = vt_train[:, test_col_idxs]
# find the users that exists in both training and test datasets
user_present_both = np.intersect1d(user_item_test.index, user_item_train.index)
user_item_test_predictable = user_item_test[user_item_test.index.isin(user_present_both)]
# initialize testing parameters
num_latent_feats = np.arange(10,700+10,20)
sum_errs_train = []
sum_errs_test = []
for k in num_latent_feats:
# restructure with k latent features for both training and test sets
s_train_lat, u_train_lat, vt_train_lat = np.diag(s_train[:k]), u_train[:, :k], vt_train[:k, :]
u_test_lat, vt_test_lat = u_test[:, :k], vt_test[:k, :]
# take dot product for both training and test sets
user_item_train_est = np.around(np.dot(np.dot(u_train_lat, s_train_lat), vt_train_lat))
user_item_test_est = np.around(np.dot(np.dot(u_test_lat, s_train_lat), vt_test_lat))
# compute error for each prediction to actual value
diffs_train = np.subtract(user_item_train, user_item_train_est)
diffs_test = np.subtract(user_item_test_predictable, user_item_test_est)
# total errors and keep track of them for both training and test sets
err_train = np.sum(np.sum(np.abs(diffs_train)))
err_test = np.sum(np.sum(np.abs(diffs_test)))
sum_errs_train.append(err_train)
sum_errs_test.append(err_test)
plt.figure(figsize=(10, 7))
plt.plot(num_latent_feats, 1 - np.array(sum_errs_train)/(user_item_train.shape[0]
* user_item_test_predictable.shape[1]), label='Train')
plt.plot(num_latent_feats, 1 - np.array(sum_errs_test)/(user_item_test_predictable.shape[0]
* user_item_test_predictable.shape[1]), label='Test')
plt.xlabel('# Latent Features')
plt.ylabel('Prediction Accuracy')
plt.legend()
plt.title('Training/Test Accuracy vs. Number of Latent Features')
plt.show()
6.
Use the cell below to comment on the results you found in the previous question. Given the circumstances of your results, discuss what you might do to determine if the recommendations you make with any of the above recommendation systems are an improvement to how users currently find articles?
1. From the investigation from the dataset above, we learnt that we only have 20 users in the test set are present in the training set, which makes the users that could be recommended using the collaborative filtering techniques. There are a large amount of users will suffer from the cold start problem, which forced us to use the rank based reccommendation - a method that is far less ideal.
2. From the training graph above, significant overfitting issues has been observed when we choose a larger number of latent features. It is better for us to choose a smaller number of latent features.
Using your workbook, you could now save your recommendations for each user, develop a class to make new predictions and update your results, and make a flask app to deploy your results. These tasks are beyond what is required for this project. However, from what you learned in the lessons, you certainly capable of taking these tasks on to improve upon your work here!
Congratulations! You have reached the end of the Recommendations with IBM project!
Tip: Once you are satisfied with your work here, check over your report to make sure that it is satisfies all the areas of the rubric. You should also probably remove all of the "Tips" like this one so that the presentation is as polished as possible.
Before you submit your project, you need to create a .html or .pdf version of this notebook in the workspace here. To do that, run the code cell below. If it worked correctly, you should get a return code of 0, and you should see the generated .html file in the workspace directory (click on the orange Jupyter icon in the upper left).
Alternatively, you can download this report as .html via the File > Download as submenu, and then manually upload it into the workspace directory by clicking on the orange Jupyter icon in the upper left, then using the Upload button.
Once you've done this, you can submit your project by clicking on the "Submit Project" button in the lower right here. This will create and submit a zip file with this .ipynb doc and the .html or .pdf version you created. Congratulations!
from subprocess import call
call(['python', '-m', 'nbconvert', 'Recommendations_with_IBM.ipynb'])
0