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

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/labhalamanojkumar/Capstoneprojects/blob/main/Electronics.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="11BphXo9mU7D"
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn import neighbors
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler

# + colab={"base_uri": "https://localhost:8080/", "height": 204} id="Edq3iu9Cmrgk" outputId="d23bf301-b1cc-4d67-9d7f-00a3ee8b3688"
df = pd.read_csv("/content/drive/MyDrive/Capgemini/electronics.csv")
df.head()

# + colab={"base_uri": "https://localhost:8080/"} id="Uh5C732Hn8Y2" outputId="39cd4434-e54e-4d0d-d989-5d33e5aaf10f"
df.shape

# + colab={"base_uri": "https://localhost:8080/"} id="W_7cNA-2qQN4" outputId="cc335fce-6a53-4c7f-dbdd-1a168fed9088"
df.info()

# + colab={"base_uri": "https://localhost:8080/"} id="qph3t8JmnolJ" outputId="92dd5c59-ea8a-48d3-e9ab-90771111515a"
df.isnull().sum()

# + colab={"base_uri": "https://localhost:8080/"} id="-W14Z94RozgO" outputId="7db2f10e-01ec-4fd0-cd78-4cade84fb868"
df['brand'].unique()

# + id="GGFi-b8Dp2XO"
df.drop(['user_attr'],axis = 'columns' ,inplace=True)

# + id="0qfnCEjYrJHt"
df["brand"].fillna( method ='ffill', inplace = True)

# + colab={"base_uri": "https://localhost:8080/"} id="kjbG_N60qziD" outputId="2f7c7aed-2a2f-46d9-8657-a02f55613462"
df.info()

# + colab={"base_uri": "https://localhost:8080/", "height": 204} id="uoMhxGTwq7Sv" outputId="6860bac5-053d-4f15-fd1d-da6b9bb33fd1"
df.corr()

# + colab={"base_uri": "https://localhost:8080/", "height": 279} id="Yyegry3sr3cs" outputId="0f5e7f87-fc8f-46cd-e1ab-bbc39e21d673"
sns.countplot(x ='rating', data = df)
plt.show()

# + colab={"base_uri": "https://localhost:8080/", "height": 390} id="Vb-WK5Kvr_Q6" outputId="5e550238-3f32-4cc8-9cf7-4e4c1b4e22ed"
rating_count = pd.DataFrame(df.groupby('item_id')['rating'].count())
df1 = rating_count.sort_values('rating', ascending=False).head(10)
df1

# + [markdown] id="Cp6yPvqeui5t"
# #These are the top 10 highest rated items.

# + colab={"base_uri": "https://localhost:8080/", "height": 296} id="3RU4wRVbuYhL" outputId="566f42b6-119c-4e84-e265-22d096b313ae"
ax = df1.plot.bar(stacked=True)

# + [markdown] id="blRiFa6-848e"
# #Recommendation based on Brand 

# + colab={"base_uri": "https://localhost:8080/", "height": 675} id="GaG0yIqLx3zQ" outputId="080d0d75-e7de-4008-f61d-8664d4fb826c"
most_items = df.groupby('brand')['item_id'].count().reset_index().sort_values('item_id', ascending=False).head(10).set_index('brand')
plt.figure(figsize=(15,10))
ax = sns.barplot(most_items['item_id'], most_items.index, palette='inferno')
ax.set_title("Top 10 most rated Brands")
ax.set_xlabel("Total number of items")
totals = []
for i in ax.patches:
    totals.append(i.get_width())
total = sum(totals)
for i in ax.patches:
    ax.text(i.get_width()+.2, i.get_y()+.2,str(round(i.get_width())), fontsize=15,color='black')
    


# + [markdown] id="ppk1KNuO-MCT"
# #Recommendations based on correlations

# + colab={"base_uri": "https://localhost:8080/", "height": 390} id="ivLVBY8v9e8N" outputId="5cb36bd7-f890-43bd-9ab3-4891fe35b1ce"
average_rating = pd.DataFrame(df.groupby('item_id')['rating'].mean())
average_rating['ratingCount'] = pd.DataFrame(df.groupby('item_id')['rating'].count())
df2 = average_rating.sort_values('ratingCount',ascending=False).head(10)
df2

# + colab={"base_uri": "https://localhost:8080/", "height": 296} id="aIs8cgie9-9I" outputId="e5e22573-e0f3-4925-ebd5-bd0c2f08ddcd"
ax = df2.plot.bar(stacked=True)

# + [markdown] id="WFXxHJMvDIoA"
# # Category based Recommendation

# + colab={"base_uri": "https://localhost:8080/", "height": 675} id="5F8nJYyzHb0b" outputId="583c4965-37ce-4fc3-c207-9164e5ace7c5"
most_items1 = df.groupby('category')['item_id'].count().reset_index().sort_values('item_id', ascending=False).head(10).set_index('category')
plt.figure(figsize=(15,10))
ax = sns.barplot(most_items1['item_id'], most_items1.index, palette='inferno')
ax.set_title("Top 10 most rated Category")
ax.set_xlabel("Total number of items")
totals = []
for i in ax.patches:
    totals.append(i.get_width())
total = sum(totals)
for i in ax.patches:
    ax.text(i.get_width()+.2, i.get_y()+.2,str(round(i.get_width())), fontsize=15,color='black')

# + colab={"base_uri": "https://localhost:8080/", "height": 359} id="QCdH83qVIZu4" outputId="3bf81bb8-8e70-4145-957b-f6bf7239a4e3"
combine_item_rating = df.copy()
columns = ['timestamp', 'model_attr','brand', 'year', 'split']
combine_item_rating = combine_item_rating.drop(columns, axis=1)
combine_item_rating.head(10)

# + colab={"base_uri": "https://localhost:8080/", "height": 359} id="MY4F04KdJw4c" outputId="7ba4a099-51e6-40fb-b0ab-fb9ac04f70a5"
combine_item_rating = combine_item_rating.dropna(axis = 0, subset = ['category'])

item_ratingCount = (combine_item_rating.groupby(by = ['category'])['rating'].count().reset_index().rename(columns = {'rating': 'totalRatingCount'})[['category', 'totalRatingCount']])
item_ratingCount.head(10)

# + colab={"base_uri": "https://localhost:8080/", "height": 204} id="A44HbO0CKZOF" outputId="74a6c849-75d0-4980-cbc2-8ea79b1d3497"
rating_with_totalRatingCount = combine_item_rating.merge(item_ratingCount, left_on = 'category', right_on = 'category', how = 'left')
rating_with_totalRatingCount.head()


# + colab={"base_uri": "https://localhost:8080/", "height": 204} id="9wMkQIHdOxLc" outputId="b0e0b8ba-24af-42e5-a3b3-6a2117f0d3f8"
df3 = rating_with_totalRatingCount.join(df, lsuffix="DROP").filter(regex="^(?!.*DROP)")
df3.head()

# + [markdown] id="8oVDq9pZTJOl"
# #Recommendation Using **Nearst Neighbors**

# + colab={"base_uri": "https://localhost:8080/"} id="SauW8x6KPdJP" outputId="372a923c-8361-41ed-a69a-f1898af7eaa1"
from scipy.sparse import csr_matrix
from sklearn.neighbors import NearestNeighbors
user_rating = df3.drop_duplicates(['user_id','category'])
user_rating_pivot = user_rating.pivot(index = 'category', columns = 'user_id', values = 'rating').fillna(0)
user_rating_matrix = csr_matrix(user_rating_pivot.values)

model_knn = NearestNeighbors(metric = 'cosine', algorithm = 'brute')
model_knn.fit(user_rating_matrix)

# + colab={"base_uri": "https://localhost:8080/"} id="yj7C6UNzRoZb" outputId="e9d58644-d2ac-4c42-ad4a-1994139c9cc8"
query_index = np.random.choice(user_rating_pivot.shape[0])
print(query_index)
distances, indices = model_knn.kneighbors(user_rating_pivot.iloc[query_index,:].values.reshape(1, -1), n_neighbors = 5)

# + colab={"base_uri": "https://localhost:8080/", "height": 35} id="L-QBgwyOSCjW" outputId="a7da8b67-a07c-4792-9780-03e69e1fd323"
user_rating_pivot.index[query_index]

# + colab={"base_uri": "https://localhost:8080/"} id="y-rzpzWxSFhK" outputId="6eaf93b7-a9de-4dab-8113-7e5ca5fd6886"
for i in range(0, len(distances.flatten())):
    if i == 0:
        print('Recommendations for who purchased {0}:\n'.format(user_rating_pivot.index[query_index]))
    else:
        print('{0}: {1}, with Score of {2}:'.format(i, user_rating_pivot.index[indices.flatten()[i]], distances.flatten()[i]))


StarcoderdataJupyterScriptsDedupFiltered