# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import numpy as np
import pandas as pd
import os


# +
# Relative path reference that contains the dataset
os.chdir('C:\\Users\\Pankhuri\\Desktop\\Customer Analytics\\data.csv\\')

# Reading and displaying the list of movies that were rated
ProductNames = pd.read_csv('UniqueProducts.csv')
ProductNames.head()
# -

ratings = pd.read_csv('Rating.csv')
#ratings.head()

ratings.drop(ratings.columns[[3]], 1, inplace = True)
#print("Unique Customers:" + str(ratings.CustomerID.unique().size) + ", Unique Products = " + str(ratings.ProductID.unique().size))


ratings_matrix = pd.crosstab(ratings.CustomerID, ratings.ProductID, ratings.Rating, aggfunc=np.sum).fillna(value=0)
ratings_matrix.head()

ratings_matrix = ratings_matrix.div(ratings_matrix.sum(axis=1), axis=0)


## Function to calculate Cosine Similarity between items
def CosineSimilarity(matrix, item1, item2):
    # Extract the column for the first item
    if item1 == 1:
        p1m = np.ma.filled(matrix[:, :item1], 0)
    else:
        # Calculate the previous index value, so that we can make use of the correct column
        prev = item1 - 1 if item1 > 1 else 1
        p1m = np.ma.filled(matrix[:, prev:item1], 0)

    # Extract the column for the second item
    if item2 == 1:
        p2m = np.ma.filled(matrix[:, :item2], 0)
    else:
        # Calculate the previous index value, so that we can make use of the correct column
        prev = item2 - 1 if item2 > 1 else 1
        p2m = np.ma.filled(matrix[:, prev:item2], 0)

    p1m = p1m.reshape(1, -1)
    p2m = p2m.reshape(1, -1)

    # Check for divide by zero error
    if ((np.asscalar(np.sqrt(np.einsum('ij,ij ->i', p1m, p1m))) *
             np.asscalar(np.sqrt(np.einsum('ij,ij ->i', p2m, p2m)))) == 0):
        return 0
    else:
        similar = np.asscalar(np.inner(p1m, p2m)) / (np.asscalar(np.sqrt(np.einsum('ij,ij ->i', p1m, p1m))) *
                                                     np.asscalar(np.sqrt(np.einsum('ij,ij ->i', p2m, p2m))))
        return similar


count = ratings_matrix.shape[1]
out = np.zeros(shape=(count, count))
headers = list(ratings_matrix)
matrix = np.asarray(ratings_matrix)
for i in range(1, count + 1):
    baseItem = i - 1
    for j in range(1, count + 1):
        out[baseItem, j - 1] = CosineSimilarity(matrix, i, j)
similarity_matrix = pd.DataFrame(out, index=headers, columns=headers)
#similarity_matrix.head()

item_neighbourhood = pd.DataFrame(index=similarity_matrix.columns, columns=range(1, len(similarity_matrix) + 1))
for i in range(0,len(similarity_matrix.columns)):
    item_neighbourhood.iloc[i, :] = similarity_matrix.iloc[0:, i].sort_values(ascending=False)[:].index
#item_neighbourhood.head()

# +
#selected_Product = 'CHILDS BREAKFAST SET'
#selected_User = 12748
#number_of_recos = 10
# -

def rec_itemitem(selected_Product, selected_User, number_of_recos, similarity_matrix):
    selected_ProductId = int(ProductNames.loc[ProductNames['ProductName'] == selected_Product]['ProductID'])
    similar_items = item_neighbourhood.loc[selected_ProductId].values.tolist()[:number_of_recos+1]
    similar_item_scores = similarity_matrix.loc[similar_items].loc[similar_items]
    
    user_vector = ratings_matrix.loc[selected_User].loc[similar_items]
    
    score = user_vector.dot(similar_item_scores).div(similar_item_scores.sum())
    score = score.sort_values(ascending=False)
    
    score.index.tolist()[:number_of_recos]
    rec_item_list = []
    for i in score.index.tolist()[:number_of_recos]:
        rec_items=(ProductNames[ProductNames['ProductID'] == int(i)]['ProductName'].values)
        rec_item_list.append(rec_items)
    #codes = [item[0] for item in rec_item_list]
    descriptions = [item[0] for item in rec_item_list]
    final_frame = pd.DataFrame({'ProductName': descriptions}) # Create a dataframe 
    return final_frame[['ProductName']]
    
    #return rec_item_list


rec_item_list = rec_itemitem('APRONS',12748,10,similarity_matrix)
rec_item_list



StarcoderdataJupyterScriptsDedupFiltered