Sales Transactions Dataset Weekly

https://archive.ics.uci.edu/ml/machine-learning-databases/00396/
https://archive.ics.uci.edu/ml/datasets/Sales_Transactions_Dataset_Weekly

The dataset contains weekly purchased quantities of 811 products over 52 weeks.
Normalised values are also provided.

The objective is here to build a clustering model to identify natural grouping of the product based on purchase patterns.

Summary of Key information

Number of Products                          : 811 
Number of Products with missing attributes  : None  
Number of qualified Products                : 811

Number of Input Attributes                  : 53
Number of categorical attributes            : 01(Product code)
Number of numerical attributes              : 52(Sales qty for 52 weeeks)

Problem Identification                      : Unsupervised Learning (Clustering)

Loading necessary libraries

In [1]:
import numpy as np
import pandas as pd
import time
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.cm as cm

from sklearn.preprocessing import StandardScaler, MinMaxScaler
In [1]:
from urllib.request import urlopen

url = "https://archive.ics.uci.edu/ml/datasets/Sales_Transactions_Dataset_Weekly"
page = urlopen(url)
html = page.read().decode("utf-8")
start_index = html.find("<title>") + len("<title>")
end_index = html.find("</title>")

title = html[start_index:end_index]
title
Out[1]:
'UCI Machine Learning Repository: Sales_Transactions_Dataset_Weekly Data Set'
In [559]:
#print(html)

Importing the dataset

In [544]:
path = "/Users/bhaskarroy/BHASKAR FILES/BHASKAR CAREER/Data Science/" \
       "Practise/Python/UCI Machine Learning Repository/" \
       "Sales_Transaction_Weekly_Dataset/"
path1 = path + "Sales_Transactions_Dataset_Weekly.csv"
In [545]:
df = pd.read_csv(path1)
In [548]:
# Inspecting the data
df.head()
Out[548]:
Product_Code W0 W1 W2 W3 W4 W5 W6 W7 W8 ... Normalized 42 Normalized 43 Normalized 44 Normalized 45 Normalized 46 Normalized 47 Normalized 48 Normalized 49 Normalized 50 Normalized 51
0 P1 11 12 10 8 13 12 14 21 6 ... 0.06 0.22 0.28 0.39 0.50 0.00 0.22 0.17 0.11 0.39
1 P2 7 6 3 2 7 1 6 3 3 ... 0.20 0.40 0.50 0.10 0.10 0.40 0.50 0.10 0.60 0.00
2 P3 7 11 8 9 10 8 7 13 12 ... 0.27 1.00 0.18 0.18 0.36 0.45 1.00 0.45 0.45 0.36
3 P4 12 8 13 5 9 6 9 13 13 ... 0.41 0.47 0.06 0.12 0.24 0.35 0.71 0.35 0.29 0.35
4 P5 8 5 13 11 6 7 9 14 9 ... 0.27 0.53 0.27 0.60 0.20 0.20 0.13 0.53 0.33 0.40

5 rows × 107 columns

In [547]:
df.describe()
Out[547]:
W0 W1 W2 W3 W4 W5 W6 W7 W8 W9 ... Normalized 42 Normalized 43 Normalized 44 Normalized 45 Normalized 46 Normalized 47 Normalized 48 Normalized 49 Normalized 50 Normalized 51
count 811.000000 811.000000 811.000000 811.000000 811.000000 811.000000 811.000000 811.000000 811.000000 811.000000 ... 811.000000 811.000000 811.000000 811.000000 811.000000 811.000000 811.00000 811.000000 811.000000 811.000000
mean 8.902589 9.129470 9.389642 9.717633 9.574599 9.466091 9.720099 9.585697 9.784217 9.681874 ... 0.299149 0.287571 0.304846 0.316017 0.334760 0.314636 0.33815 0.358903 0.373009 0.427941
std 12.067163 12.564766 13.045073 13.553294 13.095765 12.823195 13.347375 13.049138 13.550237 13.137916 ... 0.266993 0.256630 0.263396 0.262226 0.275203 0.266029 0.27569 0.286665 0.295197 0.342360
min 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 ... 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.00000 0.000000 0.000000 0.000000
25% 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 ... 0.000000 0.000000 0.000000 0.020000 0.085000 0.000000 0.10500 0.100000 0.110000 0.090000
50% 3.000000 3.000000 3.000000 4.000000 4.000000 3.000000 4.000000 4.000000 4.000000 4.000000 ... 0.280000 0.270000 0.300000 0.310000 0.330000 0.310000 0.33000 0.330000 0.350000 0.430000
75% 12.000000 12.000000 12.000000 13.000000 13.000000 12.500000 13.000000 12.500000 13.000000 13.000000 ... 0.490000 0.450000 0.500000 0.500000 0.500000 0.500000 0.50000 0.550000 0.560000 0.670000
max 54.000000 53.000000 56.000000 59.000000 61.000000 52.000000 56.000000 62.000000 63.000000 52.000000 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.00000 1.000000 1.000000 1.000000

8 rows × 106 columns

In [9]:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 811 entries, 0 to 810
Columns: 107 entries, Product_Code to Normalized 51
dtypes: float64(52), int64(54), object(1)
memory usage: 678.1+ KB
In [10]:
df.columns[:55]
Out[10]:
Index(['Product_Code', 'W0', 'W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8',
       'W9', 'W10', 'W11', 'W12', 'W13', 'W14', 'W15', 'W16', 'W17', 'W18',
       'W19', 'W20', 'W21', 'W22', 'W23', 'W24', 'W25', 'W26', 'W27', 'W28',
       'W29', 'W30', 'W31', 'W32', 'W33', 'W34', 'W35', 'W36', 'W37', 'W38',
       'W39', 'W40', 'W41', 'W42', 'W43', 'W44', 'W45', 'W46', 'W47', 'W48',
       'W49', 'W50', 'W51', 'MIN', 'MAX'],
      dtype='object')
In [11]:
df.shape
Out[11]:
(811, 107)
In [60]:
# Verifying if normalised values provided are correct
In [114]:
df.iloc[0:2, 0:53].set_index('Product_Code')
Out[114]:
W0 W1 W2 W3 W4 W5 W6 W7 W8 W9 ... W42 W43 W44 W45 W46 W47 W48 W49 W50 W51
Product_Code
P1 11 12 10 8 13 12 14 21 6 14 ... 4 7 8 10 12 3 7 6 5 10
P2 7 6 3 2 7 1 6 3 3 3 ... 2 4 5 1 1 4 5 1 6 0

2 rows × 52 columns

In [105]:
df.iloc[0:2,np.r_[0,-52:-1:1]].set_index('Product_Code')
Out[105]:
Normalized 0 Normalized 1 Normalized 2 Normalized 3 Normalized 4 Normalized 5 Normalized 6 Normalized 7 Normalized 8 Normalized 9 ... Normalized 41 Normalized 42 Normalized 43 Normalized 44 Normalized 45 Normalized 46 Normalized 47 Normalized 48 Normalized 49 Normalized 50
Product_Code
P1 0.44 0.5 0.39 0.28 0.56 0.5 0.61 1.0 0.17 0.61 ... 0.44 0.06 0.22 0.28 0.39 0.5 0.0 0.22 0.17 0.11
P2 0.70 0.6 0.30 0.20 0.70 0.1 0.60 0.3 0.30 0.30 ... 0.50 0.20 0.40 0.50 0.10 0.1 0.4 0.50 0.10 0.60

2 rows × 51 columns

In [113]:
df.iloc[0:2,0:53].set_index('Product_Code') \
                   .apply(lambda x : (x-x.min())/(x.max()-x.min()), axis = 1)
Out[113]:
W0 W1 W2 W3 W4 W5 W6 W7 W8 W9 ... W42 W43 W44 W45 W46 W47 W48 W49 W50 W51
Product_Code
P1 0.444444 0.5 0.388889 0.277778 0.555556 0.5 0.611111 1.0 0.166667 0.611111 ... 0.055556 0.222222 0.277778 0.388889 0.5 0.0 0.222222 0.166667 0.111111 0.388889
P2 0.700000 0.6 0.300000 0.200000 0.700000 0.1 0.600000 0.3 0.300000 0.300000 ... 0.200000 0.400000 0.500000 0.100000 0.1 0.4 0.500000 0.100000 0.600000 0.000000

2 rows × 52 columns

Dataset Info

Abstract:
Contains weekly purchased quantities of 800 over products over 52 weeks. Normalised values are provided too.

Attribute Information:

Product_Code
52 weeks: W0, W1, ..., W51.
Normalised vlaues of weekly data: Normalised 0, Normalised 1, ..., Normalised 51

Data Set Characteristics:
Multivariate, Time-Series

Number of Instances:
811

Area:
N/A

Attribute Characteristics:
Integer, Real

Number of Attributes:
53

Date Donated
2017-07-16

Associated Tasks:
Clustering

Missing Values?
N/A

Number of Web Hits: 92132

Defining the Problem

We have the sales quantity of 811 products over a period of 52 weeks. The available information can be used for two kinds of problems.

  • Firstly, we can create a time series forecasting model to predict the sales qty for next week.
  • Secondly, we can build a clustering model to identify natural groupings of the product based on the weekly sales pattern.

In this notebook, we will focus on the clustering problem.
The forecasting problem will taken up in a separate notebook.

Finding Product Clusters

We have chosen k-means clustering as it is one of the most extensively used clustering algorithms. There is no hierarchy in k means clustering which suits our problem. Whereas, Hierarchical clustering creates a tree using either of agglomerative(bottom-up) and divisive(top-down) approaches. For our particular example, we don't require hierarchical tree.

In [373]:
#import libraries
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import missingno as msno 
import scipy.cluster.hierarchy as sch

from sklearn.preprocessing import MinMaxScaler
from sklearn.cluster import KMeans
from sklearn.cluster import AgglomerativeClustering

Preparing the data

In [549]:
# Extracting the sales qty values as the input data
# The product codes are unique and will be used as index
col_num = [0]
col_num.extend(list(np.arange(1,53)))
X = df.iloc[:,col_num]  \
      .set_index(keys = "Product_Code")
X.head()
Out[549]:
W0 W1 W2 W3 W4 W5 W6 W7 W8 W9 ... W42 W43 W44 W45 W46 W47 W48 W49 W50 W51
Product_Code
P1 11 12 10 8 13 12 14 21 6 14 ... 4 7 8 10 12 3 7 6 5 10
P2 7 6 3 2 7 1 6 3 3 3 ... 2 4 5 1 1 4 5 1 6 0
P3 7 11 8 9 10 8 7 13 12 6 ... 6 14 5 5 7 8 14 8 8 7
P4 12 8 13 5 9 6 9 13 13 11 ... 9 10 3 4 6 8 14 8 7 8
P5 8 5 13 11 6 7 9 14 9 9 ... 7 11 7 12 6 6 5 11 8 9

5 rows × 52 columns

In [551]:
# creating strandard scaled and min max scaled versions of the input data
# https://scikit-learn.org/stable/modules/classes.html#module-sklearn.preprocessing
from sklearn.preprocessing import StandardScaler, MinMaxScaler
ssc, mmsc = StandardScaler(), MinMaxScaler()
X_ssc = ssc.fit_transform(X)
X_mmsc = mmsc.fit_transform(X)
In [376]:
# Inspecting the 
#print(list(dir(ssc)))
#print('\n'*2)
#print(ssc.feature_names_in_)
#print('\n'*2)
#print(ssc.__getstate__())

K means clustering

We will choose the optimal number of clusters (k value) using both the elbow method and Silhouette analysis.

Choosing optimal number of clusters using Elbow method

Observations
From elbow method, 3 seems to be the most optimal value.
However, we cannot rule out 4 and 5. We will proceed with the Silhouette coefficient plot to confirm.

In the below code, we have checked the elbow plots with three forms of input data :

  • Unscaled (which means no feature scaling)
  • Standard scaling
  • Minmax scaling
In [475]:
# Elbow plot for unscaled, standard scaled and minmax scaled data

from sklearn.cluster import KMeans

#plt.style.use('classic')
plt.rcdefaults()
lw = 0.75
marker_size = 3
titlefntsize = 10
labelfntsize = 8
labelalpha = 0.5
ticklabelsize = 8
ticklabelalpha = 0.7
gridalpha = 0.4

fig, axs = plt.subplots(3, figsize = (4,5), dpi = 150)

# Creating a user defined function to return elbow plot
def Elbow_plot(X, ax, ax_title, range_strt, range_end):  
    '''returns a elbow plot for evaluating optimum k value in k-means
    
    X is the prepared dataframe.
    ax is the axes.
    ax_title is the title.
    range_strt is start value of k for evaluating k means.
    range_end is end value of k for evaluating k means.    
    '''
    
    sns.set_style('white')
    k_vals = list(range(range_strt, range_end+1))
    WCSSE = []
    
    for k in k_vals:
        kmeans = KMeans(n_clusters=k, init='k-means++',random_state=0)
        model = kmeans.fit(X)
        WCSSE.append(model.inertia_)

    ax.plot(k_vals, WCSSE, marker='o', 
            markersize=marker_size,linewidth = lw)
    
    ax.set_title(ax_title, fontsize = titlefntsize)
    ax.set_ylabel('Within Cluster SSE',
                  fontsize = labelfntsize,
                  alpha = labelalpha)                
    ax.set_xlabel('k',
                  fontsize = labelfntsize,
                  alpha = labelalpha)
    
    for labels in ax.get_xticklabels():
        labels.set(fontsize = ticklabelsize, alpha = ticklabelalpha) 
    
    for labels in ax.get_yticklabels():
        labels.set(fontsize = ticklabelsize, alpha = ticklabelalpha) 

    ax.yaxis.grid(True, alpha = gridalpha)
    
    # Adjusting visibility of the spines
    #ax.set_frame_on(True)
    for axspine in ax.spines:
        ax.spines[axspine].set(visible = True, alpha = 0.5)
    #ax.spines['right'].set_visible(False)
    #ax.spines['top'].set_visible(False)
    #ax.spines['left'].set(visible = True, alpha = 0.5)
    #ax.spines['bottom'].set_visible(True)
    

#List of Data 
Data_list = [X, X_ssc, X_mmsc]

#List of titles 
Title_list = ['Unscaled', 'Scaled', 'MinMax Scaled']

for i, (data,title) in enumerate(zip(Data_list, Title_list)):
    Elbow_plot(data, ax = axs[i], ax_title = title, range_strt = 2, range_end =20)
    
plt.tight_layout()

Silhouette Analysis for k-means clustering

From Silhouette Analysis, the number of clusters can be 3,4,5 in decreasing order of silhouette scores.
Cluster counts 10,8,6 are ruled out owing to presence of negative silhouette scores.

For standard scaled data, the silhouette scores for different k values are :

For n_clusters = 3,  The average silhouette_score is : 0.609876  
For n_clusters = 4,  The average silhouette_score is : 0.56319  
For n_clusters = 5,  The average silhouette_score is : 0.449328  
For n_clusters = 6,  The average silhouette_score is : 0.3887  
For n_clusters = 8,  The average silhouette_score is : 0.358646  
For n_clusters = 10, The average silhouette_score is : 0.290975  

Note : Results for standard-scaled data are similar to the un-scaled and minmax scaled data.

In [552]:
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score


def cluster_evaluation(X, range_n_clusters, xlowerlim = -0.1, store_values = False):
    '''Returns Silhouette plot for clusterwise samples and a second plot to show  
    distribution of points in the feature space of first two attributes
    
                   X : a dataframe.
    range_n_clusters : a list of candidate values for the number of clusters.
          xlower_lim : the lower limit of x axis for the silhouette scores plot
          Usually, The silhouette coefficient can range from -1, 1.
        store_values : Bool. False
        If True, function will return a dictionary storing the silhouette scores
        at overall level and individual clusters.
    
    '''
    # Create a subplot with 1 row and 2 columns
    #rowcount = len(range_n_clusters)
    #fig, axr = plt.subplots(nrows = rowcount, ncols = 2)
    #fig.set_size_inches(18, rowcount*3)
    
    #Intercluster gap for inserting blank space between silhouette
    #plots of individual clusters, to demarcate them clearly.
    intercluster_gap = 10
    
    #Initializing a dictionary
    dict_Kcluster = {}
    
    for i,n_clusters in enumerate(range_n_clusters):
        # Create a subplot with 1 row and 2 columns
        fig, (ax1, ax2) = plt.subplots(1, 2)
        fig.set_size_inches(10, 4)


        # The 1st subplot is the silhouette plot
        # The silhouette coefficient can range from -1, 1 but depending on the 
        # observed minimum silhouette coefficient, we will set the lower limit of x.
        ax1.set_xlim([xlowerlim,1])
        
        # The (n_clusters+1)*10 is for inserting blank space between silhouette
        # plots of individual clusters, to demarcate them clearly.
        ax1.set_ylim([0, len(X) + (n_clusters + 1) * intercluster_gap])

        # Initialize the clusterer with n_clusters value and a random generator
        # seed of 10 for reproducibility.
        clusterer = KMeans(n_clusters=n_clusters, random_state=10)
        cluster_labels = clusterer.fit_predict(X)

        # The silhouette_score gives the average value for all the samples.
        # This gives a perspective into the density and separation of the formed
        # clusters
        silhouette_avg = silhouette_score(X, cluster_labels)
        
        # Compute the silhouette scores for each sample
        sample_silhouette_values = silhouette_samples(X, cluster_labels)
        
        # Store values - silhoutte score in dictionary
        if store_values == True:
            dict_Kcluster[n_clusters] = {}
            dict_Kcluster[n_clusters]['silhouette_score'] = {}
            dict_Kcluster[n_clusters]['silhouette_score']['size'] = \
                                        int(sample_silhouette_values.size)
            dict_Kcluster[n_clusters]['silhouette_score']['avg'] = \
                                        silhouette_avg.round(6)
            dict_Kcluster[n_clusters]['silhouette_score']['max'] = \
                                        sample_silhouette_values.max().round(6)
            dict_Kcluster[n_clusters]['silhouette_score']['min'] = \
                                        sample_silhouette_values.max().round(6)
        print("For n_clusters =", n_clusters,
              "The average silhouette_score is :", silhouette_avg.round(6))

        
        
        y_lower = intercluster_gap
        for i in range(n_clusters):
            # Aggregate the silhouette scores for samples belonging to
            # cluster i, and sort them
            ith_cluster_silhouette_values = \
                sample_silhouette_values[cluster_labels == i]
            
            ith_cluster_silhouette_values.sort()

            size_cluster_i = ith_cluster_silhouette_values.shape[0]
            
            # Store values - cluster sizes in dictionary
            if store_values == True:
                dict_Kcluster[n_clusters]['cluster'+str(i)] = {}
                dict_Kcluster[n_clusters]['cluster'+str(i)]['size'] = \
                                                int(size_cluster_i)
                dict_Kcluster[n_clusters]['cluster'+str(i)]['avg'] = \
                                                        ith_cluster_silhouette_values.mean()
                dict_Kcluster[n_clusters]['cluster'+str(i)]['max'] = \
                                                ith_cluster_silhouette_values.max()
                dict_Kcluster[n_clusters]['cluster'+str(i)]['min'] = \
                                                ith_cluster_silhouette_values.min()
            
            #print(f'   Cluster {i}: {size_cluster_i}')
            
            y_upper = y_lower + size_cluster_i
    
            color = cm.nipy_spectral(float(i) / n_clusters)
            
            # Plotting silhouette values corresponding to each value in sample
            ax1.fill_betweenx(np.arange(y_lower, y_upper),
                              0, ith_cluster_silhouette_values,
                              facecolor=color, edgecolor=color, alpha=0.7)

            # Label the silhouette plots with their cluster numbers at the middle
            ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))

            # Compute the new y_lower for next plot
            y_lower = y_upper + 10  # 10 for the 0 samples

        ax1.set_title("The silhouette plot for the various clusters.")
        ax1.set_xlabel("The silhouette coefficient values")
        ax1.set_ylabel("Cluster label")

        # The vertical line for average silhouette score of all the values
        ax1.axvline(x=silhouette_avg, color="red", linestyle="--")

        ax1.set_yticks([])  # Clear the yaxis labels / ticks
        ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
        
        #---------------------------------------------------------------------------
        # 2nd Plot showing the actual clusters formed
        colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)
        ax2.scatter(X.iloc[:, 0], X.iloc[:, 1], marker='.', s=30, lw=0, alpha=0.7,
                    c=colors, edgecolor='k')

        # Labeling the clusters
        centers = clusterer.cluster_centers_
        
        # Draw white circles at cluster centers
        ax2.scatter(centers[:, 0], centers[:, 1], marker='o',
                    c="white", alpha=1, s=200, edgecolor='k')

        for i, c in enumerate(centers):
            ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1,
                        s=50, edgecolor='k')

        ax2.set_title("The visualization of the clustered data.")
        ax2.set_xlabel("Feature space for the 1st feature")
        ax2.set_ylabel("Feature space for the 2nd feature")

        plt.suptitle(("Silhouette analysis for KMeans clustering on sample data "
                      "with n_clusters = %d" % n_clusters),
                     fontsize=14, fontweight='bold')
        plt.tight_layout()
    plt.show()
    
    # Return dictionary if store_values is True
    if store_values == True: 
        return dict_Kcluster

Unscaled input Data

In [553]:
range_n_clusters = [3,4,5,6,8,10]
Kmeanwise_cluster_info = cluster_evaluation(X,range_n_clusters = range_n_clusters,
                                            xlowerlim = -0.3, store_values= True)
For n_clusters = 3 The average silhouette_score is : 0.615055
For n_clusters = 4 The average silhouette_score is : 0.568778
For n_clusters = 5 The average silhouette_score is : 0.456103
For n_clusters = 6 The average silhouette_score is : 0.39461
For n_clusters = 8 The average silhouette_score is : 0.364105
For n_clusters = 10 The average silhouette_score is : 0.310211
In [466]:
pd.DataFrame(Kmeanwise_cluster_info[3]).T.fillna("")
Out[466]:
size avg max min
silhouette_score 811.0 0.615055 0.830150 0.830150
cluster0 197.0 0.348887 0.502259 -0.033548
cluster1 124.0 0.582979 0.642369 0.077280
cluster2 490.0 0.730182 0.830150 0.208272
In [478]:
user_ids = []
frames = []

for user_id, d in Kmeanwise_cluster_info.items():
    user_ids.append(user_id)
    frames.append(pd.DataFrame.from_dict(d, orient='columns'))

df = pd.concat(frames, keys=user_ids).round(2)
df.fillna("")
Out[478]:
silhouette_score cluster0 cluster1 cluster2 cluster3 cluster4 cluster5 cluster6 cluster7 cluster8 cluster9
3 size 811.00 197.00 124.00 490.00
avg 0.62 0.35 0.58 0.73
max 0.83 0.50 0.64 0.83
min 0.83 -0.03 0.08 0.21
4 size 811.00 163.00 120.00 483.00 45.0
avg 0.57 0.38 0.47 0.69 0.26
max 0.81 0.50 0.54 0.81 0.41
min 0.81 -0.13 0.29 0.14 0.09
5 size 811.00 302.00 120.00 45.00 156.0 188.0
avg 0.46 0.74 0.47 0.25 0.29 0.18
max 0.82 0.82 0.54 0.41 0.43 0.36
min 0.82 0.24 0.29 0.07 -0.07 -0.22
6 size 811.00 188.00 52.00 156.00 69.0 302.0 44.0
avg 0.39 0.18 0.01 0.29 0.1 0.74 0.26
max 0.82 0.36 0.09 0.43 0.17 0.82 0.41
min 0.82 -0.22 -0.04 -0.07 -0.02 0.24 0.09
8 size 811.00 52.00 188.00 111.00 302.0 5.0 45.0 40.0 68.0
avg 0.36 0.01 0.17 0.19 0.74 0.18 0.09 0.16 0.1
max 0.82 0.08 0.36 0.27 0.82 0.25 0.19 0.27 0.17
min 0.82 -0.05 -0.22 0.01 0.24 0.02 -0.06 -0.01 0.05
10 size 811.00 93.00 47.00 42.00 39.0 98.0 19.0 114.0 299.0 54.0 6.0
avg 0.31 0.12 0.07 0.10 0.15 0.01 0.0 0.17 0.68 0.01 0.15
max 0.79 0.22 0.12 0.20 0.25 0.18 0.05 0.28 0.79 0.08 0.25
min 0.79 -0.18 0.02 -0.03 -0.01 -0.1 -0.04 -0.06 0.21 -0.04 -0.06
In [479]:
Kmeanwise_cluster_info[3]
Out[479]:
{'silhouette_score': {'size': 811,
  'avg': 0.615055,
  'max': 0.83015,
  'min': 0.83015},
 'cluster0': {'size': 197,
  'avg': 0.3488867236071804,
  'max': 0.5022589261586605,
  'min': -0.03354812226088503},
 'cluster1': {'size': 124,
  'avg': 0.5829794207392918,
  'max': 0.6423693787539931,
  'min': 0.07728045417198895},
 'cluster2': {'size': 490,
  'avg': 0.7301818227930915,
  'max': 0.8301498162920166,
  'min': 0.20827162594274562}}

Standard scaled data

In [480]:
range_n_clusters = [3,4,5,6,8,10]
cluster_evaluation(pd.DataFrame(X_ssc, columns = ssc.get_feature_names_out().tolist()),
                   range_n_clusters = range_n_clusters)
For n_clusters = 3 The average silhouette_score is : 0.609876
For n_clusters = 4 The average silhouette_score is : 0.56319
For n_clusters = 5 The average silhouette_score is : 0.449328
For n_clusters = 6 The average silhouette_score is : 0.3887
For n_clusters = 8 The average silhouette_score is : 0.358646
For n_clusters = 10 The average silhouette_score is : 0.290975

From Silhouette Analysis, the number of clusters can be 3,4,5 in decreasing order of silhouette scores.
Cluster counts 10,8,6 are ruled out owing to presence of negative silhouette scores.

In [365]:
print(list(dir(ssc)))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_check_feature_names', '_check_n_features', '_get_param_names', '_get_tags', '_more_tags', '_repr_html_', '_repr_html_inner', '_repr_mimebundle_', '_reset', '_validate_data', 'copy', 'feature_names_in_', 'fit', 'fit_transform', 'get_feature_names_out', 'get_params', 'inverse_transform', 'mean_', 'n_features_in_', 'n_samples_seen_', 'partial_fit', 'scale_', 'set_params', 'transform', 'var_', 'with_mean', 'with_std']

Minmax scaled data

In [481]:
range_n_clusters = [3,4,5,6,8,10]
cluster_evaluation(pd.DataFrame(X_mmsc, columns = mmsc.get_feature_names_out().tolist()),
                   range_n_clusters = range_n_clusters)
For n_clusters = 3 The average silhouette_score is : 0.615093
For n_clusters = 4 The average silhouette_score is : 0.569098
For n_clusters = 5 The average silhouette_score is : 0.453778
For n_clusters = 6 The average silhouette_score is : 0.391998
For n_clusters = 8 The average silhouette_score is : 0.358751
For n_clusters = 10 The average silhouette_score is : 0.354226

Visualising the product clusters

On Raw Data

In [499]:
optimal_k = 3
clusterer = KMeans(n_clusters= optimal_k, random_state=10)
cluster_labels = clusterer.fit_predict(X_ssc)
In [554]:
X
Out[554]:
W0 W1 W2 W3 W4 W5 W6 W7 W8 W9 ... W42 W43 W44 W45 W46 W47 W48 W49 W50 W51
Product_Code
P1 11 12 10 8 13 12 14 21 6 14 ... 4 7 8 10 12 3 7 6 5 10
P2 7 6 3 2 7 1 6 3 3 3 ... 2 4 5 1 1 4 5 1 6 0
P3 7 11 8 9 10 8 7 13 12 6 ... 6 14 5 5 7 8 14 8 8 7
P4 12 8 13 5 9 6 9 13 13 11 ... 9 10 3 4 6 8 14 8 7 8
P5 8 5 13 11 6 7 9 14 9 9 ... 7 11 7 12 6 6 5 11 8 9
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
P815 0 0 1 0 0 2 1 0 0 1 ... 0 1 1 0 0 1 0 0 2 0
P816 0 1 0 0 1 2 2 6 0 1 ... 3 3 4 2 4 5 5 5 6 5
P817 1 0 0 0 1 1 2 1 1 0 ... 2 0 0 2 2 0 0 0 4 3
P818 0 0 0 1 0 0 0 0 1 0 ... 0 0 0 1 1 0 0 0 2 0
P819 0 1 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 1

811 rows × 52 columns

In [557]:
X_clustered = pd.concat([X, \
                         pd.DataFrame(cluster_labels, \
                                      columns = ['cluster_label'], index = X.index)], \
                        axis = 1)
In [558]:
sns.scatterplot(x = 'W2', y = 'W3', data = X_clustered, hue = 'cluster_label', palette = 'muted')
Out[558]:
<AxesSubplot:xlabel='W2', ylabel='W3'>

On PCA Transformed Data

In [534]:
from sklearn.decomposition import PCA
 
pca = PCA(n_components = 3)
X_pca = pca.fit_transform(X)
X_pca = pd.DataFrame(X_trans, columns = ['PCA1', 'PCA2','PCA3'], index = X.index )

explained_variance =  pca.explained_variance_ratio_
In [535]:
X_pca_clustered = pd.concat([X_trans, 
                               pd.DataFrame(cluster_labels,
                                            columns = ['cluster_label'],
                                            index = X.index)], axis = 1)
In [536]:
X_pca_clustered
Out[536]:
PCA1 PCA2 PCA3 cluster_label
Product_Code
P1 5.321035 -8.330276 3.213794 0
P2 -35.764069 -4.442247 2.845525 2
P3 -1.850250 -1.926762 -2.171873 0
P4 -4.691024 -3.537034 -1.001507 0
P5 -2.953761 1.357492 7.548739 0
... ... ... ... ...
P815 -61.135625 -3.821242 1.000051 2
P816 -45.655741 1.682969 -2.337677 2
P817 -60.929080 -1.376589 -0.172900 2
P818 -62.153931 -2.396644 -0.810878 2
P819 -62.234971 -3.776276 -0.243990 2

811 rows × 4 columns

In [537]:
explained_variance
Out[537]:
array([0.92274682, 0.00833725, 0.00283047])
In [539]:
sns.scatterplot(x = 'PCA1', y = 'PCA2', data = X_pca_clustered, hue = 'cluster_label', palette = 'muted')
Out[539]:
<AxesSubplot:xlabel='PCA1', ylabel='PCA2'>

Summary

We had done below tasks on the data :

  • k-means clustering was used to identify natural groupings of products based on Weekly sales quantity pattern.
  • From elbow plot, 3 seemed to be most suited to be the optimal value of k. The other candidate values were 4 and 5.
  • From Silhouette analysis, we have confirmed k = 3 with the highest silhouette score.
  • For k = 5, 6, 8, 10, there were instances of negative silhouette coefficients.
  • For both elbow method and silhouette analysis, We had used unscaled, standard scaled and min max scaled data. Results were similar.
  • We have then proceeded with k = 3 and visualised the clusters successively using both raw and PCA transformed data.

Useful resources