#!/usr/bin/env python
# coding: utf-8

# In[1]:


import numpy as np


# In[2]:


import pandas as pd


# In[3]:


import matplotlib.pyplot as plt


# In[4]:


import seaborn as sns


# In[5]:


import datetime as dt


# In[6]:


import sklearn


# In[7]:


from sklearn.preprocessing import StandardScaler


# In[8]:


from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from scipy.cluster.hierarchy import linkage
from scipy.cluster.hierarchy import dendrogram
from scipy.cluster.hierarchy import cut_tree


# In[31]:


inven = pd.read_csv("Data set .csv", sep=",", encoding="ISO-8859-1", header=0)
inven.head()


# In[32]:


inven.shape


# In[33]:


inven.info()


# In[34]:


inven.describe()


# In[35]:


df_null = round(100*(inven.isnull().sum())/len(inven), 2)


# In[36]:


df_null


# In[46]:


rfm_f = inven.groupby('Brand')['Item No'].count()
rfm_f = rfm_f.reset_index()
rfm_f.columns = ['Brand', 'Frequency']
rfm_f.head()


# In[47]:


rfm_f


# In[51]:


rfm_o = inven.groupby('Brand')['OrderAmount'].sum()
rfm_o = rfm_o.reset_index()
rfm_o.columns = ['Brand', 'Frequency2']
rfm_o.head()


# In[52]:


rfm = pd.merge(rfm_o, rfm_f, on='Brand', how='inner')
rfm.head()


# In[53]:


attributes = ['Frequency','Frequency2']
plt.rcParams['figure.figsize'] = [10,8]
sns.boxplot(data = rfm[attributes], orient="v", palette="Set2" ,whis=1.5,saturation=1, width=0.7)
plt.title("Outliers Variable Distribution", fontsize = 14, fontweight = 'bold')
plt.ylabel("Range", fontweight = 'bold')
plt.xlabel("Attributes", fontweight = 'bold')


# In[56]:


Q1 = rfm.Frequency2.quantile(0.05)
Q3 = rfm.Frequency2.quantile(0.95)
IQR = Q3 - Q1
rfm = rfm[(rfm.Frequency2 >= Q1 - 1.5*IQR) & (rfm.Frequency2 <= Q3 + 1.5*IQR)]


# Removing (statistical) outliers for Frequency
Q1 = rfm.Frequency.quantile(0.05)
Q3 = rfm.Frequency.quantile(0.95)
IQR = Q3 - Q1
rfm = rfm[(rfm.Frequency >= Q1 - 1.5*IQR) & (rfm.Frequency <= Q3 + 1.5*IQR)]


# In[57]:


rfm_df = rfm[['Frequency', 'Frequency2']]


# In[58]:


scaler = StandardScaler()


# In[59]:


rfm_df_scaled = scaler.fit_transform(rfm_df)
rfm_df_scaled.shape


# In[60]:


rfm_df_scaled = pd.DataFrame(rfm_df_scaled)
rfm_df_scaled.columns = ['Frequency', 'Frequency2']
rfm_df_scaled.head()


# In[61]:


kmeans = KMeans(n_clusters=4, max_iter=50)
kmeans.fit(rfm_df_scaled)


# In[62]:


kmeans.labels_


# In[63]:


ssd = []
range_n_clusters = [2, 3, 4, 5, 6, 7, 8]
for num_clusters in range_n_clusters:
    kmeans = KMeans(n_clusters=num_clusters, max_iter=50)
    kmeans.fit(rfm_df_scaled)
    
    ssd.append(kmeans.inertia_)


# In[64]:


plt.plot(ssd)


# In[66]:


range_n_clusters = [2, 3, 4, 5, 6, 7, 8]


# In[67]:


kmeans = KMeans(n_clusters=num_clusters, max_iter=50)


# In[68]:


kmeans.fit(rfm_df_scaled)


# In[69]:


cluster_labels =  kmeans.labels_


# In[71]:



    silhouette_avg = silhouette_score(rfm_df_scaled, cluster_labels)
    print("For n_clusters={0}, the silhouette score is {1}".format(num_clusters, silhouette_avg))


# In[72]:


kmeans = KMeans(n_clusters=3, max_iter=50)
kmeans.fit(rfm_df_scaled)


# In[73]:


kmeans.labels_


# In[74]:


rfm['Cluster_Id'] = kmeans.labels_
rfm.head()


# In[76]:


sns.boxplot(x='Cluster_Id', y='Frequency2', data=rfm)


# In[77]:


sns.boxplot(x='Cluster_Id', y='Frequency', data=rfm)


# In[ ]:




