<jupyter_start><jupyter_text>Recommending Items to Users  Collaborative Filtering is a popular technique that is used for coming up with User-Item recommendations. In this example, we will use the list of which users bought which items and build an affinity score between items. When a customers buys an item, we use this affinity score to recommend other items to the customer   Loading the DatasetThe source data set contains in each row a User ID and an Item ID. This is the list of users and the items they bought, one line at a time<jupyter_code>import pandas as pd

userItemData = pd.read_csv('ratings.csv')
userItemData.head()<jupyter_output><empty_output><jupyter_text>Building the Affinity ScoreFor building the affinity score, we can use out-of-the-box open source and commercial collaborative filtering libraries. In this example though, we are going to write a simple algorithm to generate user / item affinities.<jupyter_code>#Get list of unique items
itemList=list(set(userItemData["ItemId"].tolist()))

#Get count of users
userCount=len(set(userItemData["ItemId"].tolist()))

#Create an empty data frame to store item affinity scores for items.
itemAffinity= pd.DataFrame(columns=('item1', 'item2', 'score'))
rowCount=0

#For each item in the list, compare with other items.
for ind1 in range(len(itemList)):
    
    #Get list of users who bought this item 1.
    item1Users = userItemData[userItemData.ItemId==itemList[ind1]]["userId"].tolist()
    #print("Item 1 ", item1Users)
    
    #Get item 2 - items that are not item 1 or those that are not analyzed already.
    for ind2 in range(ind1, len(itemList)):
        
        if ( ind1 == ind2):
            continue
       
        #Get list of users who bought item 2
        item2Users=userItemData[userItemData.ItemId==itemList[ind2]]["userId"].tolist()
        #print("Item 2",item2Users)
        
        #Find score. Find the common list of users and divide it by the total users.
        commonUsers= len(set(item1Users).intersection(set(item2Users)))
        score=commonUsers / userCount

        #Add a score for item 1, item 2
        itemAffinity.loc[rowCount] = [itemList[ind1],itemList[ind2],score]
        rowCount +=1
        #Add a score for item2, item 1. The same score would apply irrespective of the sequence.
        itemAffinity.loc[rowCount] = [itemList[ind2],itemList[ind1],score]
        rowCount +=1
        
#Check final result
itemAffinity.head()<jupyter_output><empty_output><jupyter_text>Recommending ItemsLet us say that a customer bought an item 5001. We can query this data frame for item1-5001 and get items2 with score in desending order. This is the item list that you can recommend to the user in that order.<jupyter_code>searchItem=5001
recoList=itemAffinity[itemAffinity.item1==searchItem]\
        [["item2","score"]]\
        .sort_values("score", ascending=[0])
        
print("Recommendations for item 5001\n", recoList)<jupyter_output>Recommendations for item 5001
     item2  score
0  5002.0    0.4
6  5005.0    0.4
4  5004.0    0.2
2  5003.0    0.0
{'fraction_non_alphanumeric': 0.08414872798434442, 'fraction_numerical': 0.029354207436399216, 'mean_word_length': 3.777258566978193, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '215666', 'license': 'MIT', 'n_tokens_mistral': 949, 'n_tokens_neox': 903, 'n_words': 345, 'path': 'Files_Predictive_Customer_Analytics/Notebooks/03_05/.ipynb_checkpoints/Recommendations-checkpoint.ipynb', 'repo_name': '99sbr/Predictive-Customer-Analytics', 'size': '3066'}