|
import pandas as pd |
|
from sklearn.metrics.pairwise import cosine_similarity |
|
import gradio as gr |
|
|
|
def recommend_items(customer_id_1, customer_id_2): |
|
|
|
try: |
|
df1 = pd.read_excel("UBCF_Online_Retail.xlsx") |
|
except FileNotFoundError: |
|
return "Error: Excel file not found." |
|
df1a = df1.dropna(subset=['CustomerID']) |
|
|
|
|
|
CustomerID_Item_matrix = df1a.pivot_table( |
|
index='CustomerID', |
|
columns='StockCode', |
|
values='Quantity', |
|
aggfunc='sum' |
|
) |
|
|
|
|
|
CustomerID_Item_matrix = CustomerID_Item_matrix.applymap(lambda x: 1 if x > 0 else 0) |
|
|
|
|
|
user_to_user_similarity_matrix = pd.DataFrame( |
|
cosine_similarity(CustomerID_Item_matrix) |
|
) |
|
|
|
|
|
user_to_user_similarity_matrix.columns = CustomerID_Item_matrix.index |
|
user_to_user_similarity_matrix['CustomerID'] = CustomerID_Item_matrix.index |
|
user_to_user_similarity_matrix = user_to_user_similarity_matrix.set_index('CustomerID') |
|
|
|
|
|
try: |
|
items_purchased_by_X = set(CustomerID_Item_matrix.loc[customer_id_1].iloc[ |
|
CustomerID_Item_matrix.loc[customer_id_1].to_numpy().nonzero()].index) |
|
except KeyError: |
|
return pd.DataFrame({"Error": ["Customer ID 1 is invalid. Please enter a valid Customer ID"]}) |
|
|
|
|
|
|
|
|
|
try: |
|
items_purchased_by_Y = set(CustomerID_Item_matrix.loc[customer_id_2].iloc[ |
|
CustomerID_Item_matrix.loc[customer_id_2].to_numpy().nonzero()].index) |
|
except KeyError: |
|
return pd.DataFrame({"Error": ["Customer ID 2 is invalid. Please enter a valid Customer ID"]}) |
|
|
|
|
|
|
|
items_to_recommend_to_Y = items_purchased_by_X - items_purchased_by_Y |
|
|
|
|
|
return df1a.loc[ |
|
df1a['StockCode'].isin(items_to_recommend_to_Y), |
|
['StockCode', 'Description'] |
|
].drop_duplicates().set_index('StockCode') |
|
|
|
|
|
iface = gr.Interface( |
|
fn=recommend_items, |
|
inputs=[ |
|
gr.inputs.Number(label="Customer ID 1",default=12702), |
|
gr.inputs.Number(label="Customer ID 2",default=14608), |
|
], |
|
outputs=gr.outputs.Dataframe(label="Recommended Items for Customer 2",type="pandas"), |
|
allow_flagging=False |
|
) |
|
iface.launch() |
|
|
|
|