Visualizing Recommendations

Use this notebook to quickly visualize recommendations. It is assumed that you have saved and loaded your item similarity matrix and full_mat.


In [ ]:
from PIL import Image
import urllib.request
from IPython.display import display, Image, HTML
import matplotlib.pyplot as plt
%matplotlib inline

In [ ]:
def getmrec(full_mat, user_id, item_similarity, k, m, idict,  cov = False):
    '''
        This function takes in the full_matrix, user_id and other arguments
        and returns the list of read and recommended books respectively.
    '''
    
    n = item_similarity.shape[0]
    nzero = full_mat[user_id].nonzero()[0]
    
    preds = {}
    for row in range(n):
        preds[row] = predict(user_id, row, full_mat, item_similarity, amean, umean, imean, k)
    
    flipped_dict = dict(zip(idict.values(), idict.keys()))
    
    books_read = []    
    
    if not cov:

        for i in nzero:
            books_read.append(flipped_dict[i])
            del preds[i]
    
    
    res = sorted(preds.items(), key=lambda x: x[1], reverse = True)
    
    ans = [flipped_dict[i[0]] for i in res[:m]]
    
    return books_read, ans

In [ ]:
# Get the list of books for a given user

books_read, ans = getmrec(full_mat, udict[227520], item_similarity, 5, 3, idict)

In [ ]:
# Create a database of de-deduplicated titles

books_db = books[books['Book-Title'].duplicated() == False]

In [ ]:
users = [227520]  # Populate this will multiple user IDs if you want out put for more than one users

for user in users:
    
    books_read, ans = getmrec(full_mat, udict[user], item_similarity, 5, 3, idict)
    
    print('User: ' + str(user))
    print('\n =x=x=x=x=x=x=x=x=x=x= BOOKS READ =x=x=x=x=x=x=x=x=x=x=')
    
    books_read_urls = list(books_db[books_db['Book-Title'].isin(books_read)]['Image-URL-L'])
    i=0
    for URL in books_read_urls:
        i+=1
        display(Image(URL, width=100))
    
    print('\n\n =x=x=x=x=x=x=x=x=x=x= BOOKS RECOMMENDED =x=x=x=x=x=x=x=x=x=x=')
    
    recommended_urls = list(books_db[books_db['Book-Title'].isin(ans)]['Image-URL-L'])
    i=0
    for URL in recommended_urls:
        i+=1
        display(Image(URL, width=100))