In this project, we will analyze a dataset containing data on various customers' annual spending amounts (reported in monetary units) of diverse product categories for internal structure. One goal of this project is to best describe the variation in the different types of customers that a wholesale distributor interacts with. Doing so would equip the distributor with insight into how to best structure their delivery service to meet the needs of each customer.
The dataset for this project can be found on the UCI Machine Learning Repository. For the purposes of this project, the features 'Channel'
and 'Region'
will be excluded in the analysis — with focus instead on the six product categories recorded for customers.
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inline
# Load the wholesale customers dataset
try:
data = pd.read_csv("customers.csv")
data.drop(['Region', 'Channel'], axis = 1, inplace = True)
print("Wholesale customers dataset has {} samples with {} features each.".format(*data.shape))
except:
print("Dataset could not be loaded. Is the dataset missing?")
In this section, we will begin exploring the data through visualizations and code to understand how each feature is related to the others. You will observe a statistical description of the dataset, consider the relevance of each feature, and select a few sample data points from the dataset which we will track through the course of this project.
Note that the dataset is composed of six important product categories: 'Fresh', 'Milk', 'Grocery', 'Frozen', 'Detergents_Paper', and 'Delicatessen'.
# Display a description of the dataset
display(data.describe())
To get a better understanding of the customers and how their data will transform through the analysis, it would be best to select a few sample data points and explore them in more detail. In the code block below, we add three indices of our choice to the indices
list which will represent the customers to track. It is suggested to try different sets of samples until we obtain customers that vary significantly from one another.
# TODO: Select three indices of your choice you wish to sample from the dataset
indices = [3,87,200]
# Create a DataFrame of the chosen samples
samples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop = True)
Consider the total purchase cost of each product category and the statistical description of the dataset above for our sample customers.
What kind of establishment (customer) could each of the three samples we've chosen represent?
The mean values are as follows:
Fresh: 12000.2977
Knowing this, how do our samples compare? Does that help in driving our insight into what kind of establishments they might be?
import seaborn as sns
import matplotlib.pyplot as plt
#Percentile values of the the sampled data
percentile_values = 100. *data.rank(axis=0, pct=True).iloc[indices].round(decimals=3)
#heatmap of percentiled value
sns.heatmap(data=percentile_values,annot=True,fmt='.1f')
plt.yticks([0.5,1.5,2.5],['Customer 0, Index '+str(indices[0]),'Customer 1, Index '+str(indices[1]),'Customer 2, Index '+str(indices[2])],rotation='horizontal')
plt.title('Percentile scores of every value in the sampled data frame')
print("Chosen samples of wholesale customers dataset:")
display(samples)
CUSTOMER 0:
CUSTOMER 1:
One interesting thought to consider is if one (or more) of the six product categories is actually relevant for understanding customer purchasing. That is to say, is it possible to determine whether customers purchasing some amount of one category of products will necessarily purchase some proportional amount of another category of products? We can make this determination quite easily by training a supervised regression learner on a subset of the data with one feature removed, and then score how well that model can predict the removed feature.
# TODO: Make a copy of the DataFrame, using the 'drop' function to drop the given feature
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
target_features = ['Fresh', 'Milk', 'Grocery', 'Frozen', 'Detergents_Paper', 'Delicatessen']
for target in target_features:
y_target = data[target]
new_data = data.drop([target], axis = 1, inplace = False)
# TODO: Split the data into training and testing sets using the given feature as the target
X_train, X_test, y_train, y_test = train_test_split(new_data, y_target, test_size=0.25, random_state=0)
# TODO: Create a decision tree regressor and fit it to the training set
regressor = DecisionTreeRegressor(random_state=0)
regressor.fit(X_train, y_train)
# TODO: Report the score of the prediction using the testing set
score = regressor.score(X_test, y_test)
print ("score for target feature ",target," is ",str(score))
The coefficient of determination, R^2
, is scored between 0 and 1, with 1 being a perfect fit. A negative R^2
implies the model fails to fit the data. If we get a low score for a particular feature, that lends us to beleive that that feature point is hard to predict using the other features, thereby making it an important feature to consider when considering relevance.
Answer:
target feature | score |
---|---|
Fresh | -0.2525 |
Milk | 0.3657 |
Grocery | 0.6028 |
Frozen | 0.2539 |
Detergent_paper | 0.7287 |
Delicatessen | -11.6637 |
R^2
score which is less than zero. This means that the model fails to fit the data with the when 'Fresh' and 'Delicatessen' are taken as target variables.R^2
score which means that there is a very high correlation between 'Grocery' and 'Detergent_paper' and other features. Hence 'Grocery' can be predicted using other features. Thus these features do not provide good insight for identifying customers' spending segment.R^2
which points to the fact that these feature do not have much correlation with other features and as a result of this, these features can be used for identifying customers' spending habits. To get a better understanding of the dataset, we can construct a scatter matrix of each of the six product features present in the data. If you found that the feature you attempted to predict above is relevant for identifying a specific customer, then the scatter matrix below may not show any correlation between that feature and the others. Conversely, if you believe that feature is not relevant for identifying a specific customer, the scatter matrix might show a correlation between that feature and another feature in the data.
# Produce a scatter matrix for each pair of features in the data
pd.plotting.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
sns.heatmap(data=data.corr(),annot=True,fmt='.1f')
plt.title('Correlation heatmap of features')
plt.show()
Answer:
We are going to neglect the features 'Fresh' and 'Delicatessen' as the R^2
score was negative which points to the fact that those two features do not fit the model and are useless.
Take a look at the heat-map shown above in whcih each cell represents the correlation of the feature corresponding to the particular row and column. (We won't be considering the auto-correlation of features when we look at the heat map above, we will only be considering the cross-correlations.).
'Frozen' has minimum correlation with 'Milk'.
Thus we included all the other four features we are interested in. Now we will take a look at the scatter plots of the above mentioned four features in more detail.
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2,figsize=(12,12))
f.suptitle('The magnified subplots of useful variables')
ax1.scatter(np.array(data['Grocery']),np.array(data['Milk']),alpha=0.2,edgecolors='purple')
ax1.set(xlabel='Grocery', ylabel='Milk')
ax2.scatter(np.array(data['Frozen']),np.array(data['Milk']),c='orange',alpha=0.2,edgecolors='red')
ax2.set(xlabel='Frozen', ylabel='Milk')
ax3.scatter(np.array(data['Detergents_Paper']),np.array(data['Milk']),c='red',alpha=0.2,edgecolors='green')
ax3.set(xlabel='Detergents_Paper', ylabel='Milk')
ax4.scatter(np.array(data['Detergents_Paper']),np.array(data['Grocery']),c='purple',alpha=0.2,edgecolors='blue')
ax4.set(xlabel='Detergents_Paper', ylabel='Grocery')
plt.show()
# Create some normally distributed data
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 3000).T
# Set up the axes with gridspec
fig = plt.figure(figsize=(6, 6))
grid = plt.GridSpec(4, 4, hspace=0.2, wspace=0.2)
main_ax = fig.add_subplot(grid[:-1, 1:])
y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax)
x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)
# scatter points on the main axes
main_ax.plot(x, y, 'ok', markersize=3, alpha=0.2)
# histogram on the attached axes
x_hist.hist(x, 40, histtype='stepfilled',
orientation='vertical', color='blue')
x_hist.invert_yaxis()
y_hist.hist(y, 40, histtype='stepfilled',
orientation='horizontal', color='red')
y_hist.invert_xaxis()
The first plot tells us that 'Grocery' and milk are correlated to some extent as with the increase in value of 'Grocery' the value of 'Milk' tends to increase. The correlation value is 0.7 which is pretty high. Thus if we know value of one of the features we can predict the value of the other one.
R^2
score of 'Milk' is less as compared to 'Grocery' we can neglect the 'Grocery' feature and use the feature 'Milk' to create customer segments.The second plot is the plot of 'Milk' and 'Frozen' and apparently the values are spread throughout the space. This is verified by the correlation coffecient between them being 0.1. Such small correlation coffecient and a small R^2
score suggest that Frozen is indeed an important variable to create customer segments.
The third plot suggest that there is a good correlation between 'Milk' and 'Detergents_Paper' and hence as the reasons provided in the points above we can neglect 'Detergents_Paper'.
The fourth graph is the most important graph. We might argue that since the correlation between 'Frozen' and 'Grocery', and 'Frozen' and 'Detergents_Paper' is zero it would be wise to include 'Grocery' and 'Detergents_Paper' as a feature to create customer segments. However we can provide two counter arguments to this which are as follows:
R^2
score that we calculated before was high for 'Grocery' as well as 'Detergents_Papers' which indicated that the above two features can be predicted using the other features. Thus neglecting these two features is a good choice.(for better visualization look at the last graph)
and this means that knowing the value of one helps us preict the value of other. Also in the first point we concluded that since there is a correlation between 'Milk' and 'Grocery' we can drop 'Grocery' as knowing the value of 'Milk' will help us predict the value of 'Grocery' and owing to this fact we can also drop 'Detergents_Paper' as it comes from the same distribution as that of 'Grocery'.In this section, we will preprocess the data to create a better representation of customers by performing a scaling on the data and detecting (and optionally removing) outliers. Preprocessing data is often times a critical step in assuring that results we obtain from your analysis are significant and meaningful.
If data is not normally distributed, especially if the mean and median vary significantly (indicating a large skew), it is most often appropriate to apply a non-linear scaling — particularly for financial data. One way to achieve this scaling is by using a Box-Cox test, which calculates the best power transformation of the data that reduces skewness. A simpler approach which can work in most cases would be applying the natural logarithm.
# TODO: Scale the data using the natural logarithm
log_data = np.log(data)
# TODO: Scale the sample data using the natural logarithm
log_samples = np.log(samples)
# Produce a scatter matrix for each pair of newly-transformed features
pd.plotting.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
plt.show()
sns.heatmap(data=log_data.corr(),annot=True,fmt='.1f')
plt.title('Correlation heatmap of features after scaling the data using natural logarithm')
plt.show()
After applying a natural logarithm scaling to the data, the distribution of each feature should appear much more normal. For any pairs of features we may have identified earlier as being correlated, observe here whether that correlation is still present (and whether it is now stronger or weaker than before).
# Display the log-transformed sample data
display(log_samples)
Detecting outliers in the data is extremely important in the data preprocessing step of any analysis. The presence of outliers can often skew results which take into consideration these data points. There are many "rules of thumb" for what constitutes an outlier in a dataset. Here, we will use Tukey's Method for identfying outliers: An outlier step is calculated as 1.5 times the interquartile range (IQR). A data point with a feature that is beyond an outlier step outside of the IQR for that feature is considered abnormal.
# For each feature find the data points with extreme high or low values
feature_out_all = {}
all_outliers = set()
for feature in log_data.keys():
# TODO: Calculate Q1 (25th percentile of the data) for the given feature
Q1 = np.percentile(log_data[feature], 25)
# TODO: Calculate Q3 (75th percentile of the data) for the given feature
Q3 = np.percentile(log_data[feature], 75)
# TODO: Use the interquartile range to calculate an outlier step (1.5 times the interquartile range)
step = (Q3 - Q1)*1.5
# Display the outliers
print ("Data points considered outliers for the feature '{}':".format(feature))
display(log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))])
current_feat_outliers = list((log_data.index[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))]))
all_outliers = all_outliers.union(set(current_feat_outliers))
for index in current_feat_outliers:
if(feature_out_all.get(index) == None):
feature_out_all[index] = [feature]
else:
feature_out_all[index].append(feature)
outliers = []
for key in feature_out_all:
if(len(feature_out_all[key]) > 1):
outliers.append(key)
outliers.sort()
all_outliers = list(all_outliers)
all_outliers.sort()
# Remove the outliers, if any were specified
good_data = log_data.drop(log_data.index[all_outliers]).reset_index(drop = True)
for key in feature_out_all:
if(len(feature_out_all[key]) > 1):
print("The point with index ",key," occurs as outlier in features ",feature_out_all[key])
Answer:
Data points are added to the outliers list because these data points posses certain characteristics which the bulk doesn't posses.
For instance consider a class of 10 students and we are supposed to find the average intelligence of this class. We aim at doing this by conducting a test. Consider the following table which shows the exam scores, scored out of 100 for 10 students in the previously mentioned test.We will make the assumption that all the students are sincere, taught by the same teacher and have a high IQ which was measured upon their admission owing to the highly selective nature of this imaginary class.
As shown in the table and because of the assumptions made, since maximum students have scored good grades and since they all were sincere, taught by the same teacher and had high IQs, everyone should have got good grades. However students with id 4
and 6
scored very less due to unforseen circumstances. And if we consider all the students including these two for measuring the intelligence of the class, the class comes out to be an average class with a the class_average of 79. However we know that students with id 4
and 6
are quite intelligent but due to some reason they couldn't perform well. Thus considering this fact if we consider students 4
and 6
as outliers, we will get a class_avg of 97.875 which is pretty good, qualifies as a highly intelligent class and is representative of the entire population of the class.
Student_id | exam_score |
---|---|
1 | 97 |
2 | 99 |
3 | 94 |
4 | 5 |
5 | 98 |
6 | 2 |
7 | 96 |
8 | 100 |
9 | 100 |
10 | 99 |
Class_avg without removing outliers | 79 |
Class_avg after removing outliers | 97.875 |
1.5 * IQR
units away from the middle 50% data. This convention of chosing a data which is 1.5 * IQR
times away helps to ensure the fact that no important data is lost and only the data which is the oddest is removed.In this section we will use principal component analysis (PCA) to draw conclusions about the underlying structure of the wholesale customer data. Since using PCA on a dataset calculates the dimensions which best maximize variance, we will find which compound combinations of features best describe customers.
Now that the data has been scaled to a more normal distribution and has had any necessary outliers removed, we can now apply PCA to the good_data
to discover which dimensions about the data best maximize the variance of features involved. In addition to finding these dimensions, PCA will also report the explained variance ratio of each dimension — how much variance within the data is explained by that dimension alone. Note that a component (dimension) from PCA can be considered a new "feature" of the space, however it is a composition of the original features present in the data.
from sklearn.decomposition import PCA
# TODO: Apply PCA by fitting the good data with the same number of dimensions as features
pca = PCA(n_components=6)
pca.fit(good_data)
# TODO: Transform the sample log-data using the PCA fit above
pca_samples = pca.transform(log_samples)
# Generate PCA results plot
pca_results = vs.pca_results(good_data, pca)
Note: A positive increase in a specific dimension corresponds with an increase of the positive-weighted features and a decrease of the negative-weighted features. The rate of increase or decrease is based on the individual feature weights.
Answer:
The total variance in the data explained by first and second principal component is:
The total variance in the data explained by first four principal component is:
If we look closely at the graph above we can see that there is an explained variance for each dimension generated by the PCA. This explained variance tells us how much information is retained in a particular dimension when we change the basis of our original space. The feature weights for a particular dimension gives us insight about how much a customer belonging to that particular dimension will spend on a particular product. Due to all these reasons we can conclude that explained variance and feature weights together are describing the spending patterns of customer rather than representing the customers.
Looking at dimension 1 which accounts for 49.93% of the entire variance or 49.93% of the spending pattern, we can see that Milk
, Grocery
, Detergents_Paper
and Delicatessen
have feature weights that are positive while all the other features have weights that are negative.
Milk
, Grocery
, Detergents_Paper
and Delicatessen
mean that customer that are concenterated in dimension 1 will be spending more on these category of products. Maximum spending will be done for Detergents_Paper
as the feature weight corresponding to it is the maximum and in the same way the second highest spending for customers clustered near dimension 1 would be for feature Grocery
as the feature weight corresponding to it is second highest , thierd would be Milk
and fourth would be Delicatessen
.Fresh
and Frozen
. Dimension 2 ranks second in accounting for the explained variance and thus the spending pattern with a value of 22.59%.
Detergents_Paper
. Thus spending will in descending order as follows: Frozen
,Fresh
,Delicatessen
,Milk
and the lest spending would on Grocery
Detergents_Paper
would be neglected alltogether by the customers clustered near this dimension.Dimension 3 comes next with an explained ratio of 10.49%.
Delicatessen
, Frozen
and Milk
have positive feature weights with their values descending in the above mentioned order. Thus customers concenterated near this dimension will be spending the maximum in the three features mentioned above. Eventhough the feature weight of milk is positive, its value is very less and hence the spending on milk wont be very high, but ther will still be some spending for Milk
.The fourth dimension Dimension 4 accounts for 9.78% of the spending pattern.
Delicatessen
, Fresh
, Milk
and Grocery
prodcuts with their values descending in above mentioned order. Milk
and Grocery
with positive but low feature weights will have a low spending from the customers in this dimension.Frozen
and Detergents_Paper
will be avoided by the customers all together.It is to be noted that the spending patterns are unique to each dimenion. The spending patterns in one dimension will not repeat itself in other dimension.
Run the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it in six dimensions. Observe the numerical value for the first four dimensions of the sample points.
# Display sample log-data after having a PCA transformation applied
print('PCA transformed dimension of three samples')
display(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values))
When using principal component analysis, one of the main goals is to reduce the dimensionality of the data — in effect, reducing the complexity of the problem. Dimensionality reduction comes at a cost: Fewer dimensions used implies less of the total variance in the data being explained. Because of this, the cumulative explained variance ratio is extremely important for knowing how many dimensions are necessary for the problem. Additionally, if a signifiant amount of variance is explained by only two or three dimensions, the reduced data can be visualized afterwards.
# TODO: Apply PCA by fitting the good data with only two dimensions
pca = PCA(n_components=2)
pca.fit(good_data)
# TODO: Transform the good data using the PCA fit above
reduced_data = pca.transform(good_data)
# TODO: Transform log_samples using the PCA fit above
pca_samples = pca.transform(log_samples)
# Create a DataFrame for the reduced data
reduced_data = pd.DataFrame(reduced_data, columns = ['Dimension 1', 'Dimension 2'])
Run the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it using only two dimensions. Observe how the values for the first two dimensions remains unchanged when compared to a PCA transformation in six dimensions.
# Display sample log-data after applying PCA transformation in two dimensions
display(pd.DataFrame(np.round(pca_samples, 4), columns = ['Dimension 1', 'Dimension 2']))
A biplot is a scatterplot where each data point is represented by its scores along the principal components. The axes are the principal components (in this case Dimension 1
and Dimension 2
). In addition, the biplot shows the projection of the original features along the components. A biplot can help us interpret the reduced dimensions of the data, and discover relationships between the principal components and original features.
Run the code cell below to produce a biplot of the reduced-dimension data.
# Create a biplot
vs.biplot(good_data, reduced_data, pca)
Once we have the original feature projections (in red), it is easier to interpret the relative position of each data point in the scatterplot. For instance, a point the lower right corner of the figure will likely correspond to a customer that spends a lot on 'Milk'
, 'Grocery'
and 'Detergents_Paper'
, but not so much on the other product categories.
From the biplot, which of the original features are most strongly correlated with the first component? What about those that are associated with the second component? Do these observations agree with the pca_results plot you obtained earlier?
We can see from the above biplot and the original feature projections in red that there are three features in maximum correlation with dimension 1 with the following order of decreasing correlation:
- Detergents_Paper(max_correlation with dimension 1)
- Grocery (second best correlation with dimension 1)
- Milk (Third best correlation with dimension 1)
In the same way the three features with maximum correlation with dimension 2 with their are as follows:
- Frozen(max_correlation with dimension 2)
- Fresh (second best correlation with dimension 2)
- delicatessen (Third best correlation with dimension 2)
dimension 1
and dimension 2
is proved by the PCA plot above where the feature weights of the respective features in dimension 1
and dimension 2
correspond to the correlations mentioned in points above. In this section, we will choose to use either a K-Means clustering algorithm or a Gaussian Mixture Model clustering algorithm to identify the various customer segments hidden in the data. We will then recover specific data points from the clusters to understand their significance by transforming them back into their original dimension and scale.
HARD AND SOFT CLUSTERING:
K-Means: This method of clustering is a hard clustering method. This means that every data point when clustered using a K-means will be assigned a unique cluster center. However the assignment depends highly on the initial selection of cluster centers. This is because K-means selects its initial centers randomly and after that it does the following steps:
These two steps optimization and assignment are carried out again and again till there is no change in the coordinates of the cluster center. This is when we are done with clustering with K-means and we finally have our two clusters. However due to the initial random selection of cluster centers, if the data is spread out i.e there is no clear boundaries between the two clusters, K-means clustering will give us a different result everytime. These results may be what we want or they may not be what we expected. Emperical results suggests that K-means tends to work when we have our data set which is separated in such a way that, not only the clusters have a defining separating boundary, but also when the clusters are in the shape of circular blobs. Even when we have such conditions for our data it is not guranteed that K-means will cluster properly. The clustering quality depends very much on the initial selection of the cluster centers. Thus since our data is highly spread K-means clustering will not be a good choice because of the following reasons:
Gaussian-Mixture Model: As the name suggests the Gaussian Mixture model uses multivariate normal probability distribution to cluster data. Depending on the number of clusters chosen initially this model assigns a specific probability to all the data points and this probability suggests how much a data point belongs to a specific cluster. A familiarity with the normal model suggests that the probability distribution never touches 0 instead it reduces exponentially, reaches very close to zero and touches the zero probability point only at infinity. Due to this fact there is never a zero probability of a data point being in any one of the cluster. Instead there is only a relative probability that suggests the data point being more or less in a particular cluster. This points to the fact that Gaussian-Mixture Model clustering is a soft clustering method.
WE FINALLY CHOOSE THE GUSAASIAN MIXTURE MODEL CLUSTERING BECAUSE OF THE ABOVE DISCUSSION.
Depending on the problem, the number of clusters that you expect to be in the data may already be known. When the number of clusters is not known a priori, there is no guarantee that a given number of clusters best segments the data, since it is unclear what structure exists in the data — if any. However, we can quantify the "goodness" of a clustering by calculating each data point's silhouette coefficient. The silhouette coefficient for a data point measures how similar it is to its assigned cluster from -1 (dissimilar) to 1 (similar). Calculating the mean silhouette coefficient provides for a simple scoring method of a given clustering.
# TODO: Apply your clustering algorithm of choice to the reduced data
from sklearn.mixture import GaussianMixture
from sklearn.metrics import silhouette_score
# Choose the range of k values to test.
possible_n_values = range(2, len(reduced_data)+1, 5)
#Calculating the silhouette_score for every possible value of clusters possible
errors_per_n = []
for n in possible_n_values:
clusterer = GaussianMixture(n_components=n)
clusterer.fit(reduced_data)
preds = clusterer.predict(reduced_data)
score = silhouette_score(reduced_data,preds)
errors_per_n.append(score)
# Plot the each value of n vs. the silhouette score at that value
fig, ax = plt.subplots(figsize=(16, 6))
ax.set_xlabel('n - number of clusters')
ax.set_ylabel('Silhouette Score (higher is better)')
ax.plot(possible_n_values, errors_per_n)
# Ticks and grid
xticks = np.arange(min(possible_n_values), max(possible_n_values)+1, 20.0)
ax.set_xticks(xticks, minor=False)
ax.set_xticks(xticks, minor=True)
ax.xaxis.grid(True, which='both')
yticks = np.arange(round(min(errors_per_n), 2), max(errors_per_n), .05)
ax.set_yticks(yticks, minor=False)
ax.set_yticks(yticks, minor=True)
ax.yaxis.grid(True, which='both')
clusterer = GaussianMixture(n_components=2)
clusterer.fit(reduced_data)
preds = clusterer.predict(reduced_data)
score = silhouette_score(reduced_data,preds)
centers = clusterer.means_
sample_preds = clusterer.predict(pca_samples)
print('Highest silhouette score is with 2 cluster centers and its value is: ',score)
Once we've chosen the optimal number of clusters for our clustering algorithm using the scoring metric above, we can now visualize the results by executing the code block below.
# Display the results of the clustering from implementation
vs.cluster_results(reduced_data, preds, centers, pca_samples)
Each cluster present in the visualization above has a central point. These centers (or means) are not specifically data points from the data, but rather the averages of all the data points predicted in the respective clusters. For the problem of creating customer segments, a cluster's center point corresponds to the average customer of that segment. Since the data is currently reduced in dimension and scaled by a logarithm, we can recover the representative customer spending from these data points by applying the inverse transformations.
# TODO: Inverse transform the centers
log_centers = pca.inverse_transform(centers)
# TODO: Exponentiate the centers
true_centers = np.exp(log_centers)
# Display the true centers
segments = ['Segment {}'.format(i) for i in range(0,len(centers))]
true_centers = pd.DataFrame(np.round(true_centers), columns = data.keys())
true_centers_new = pd.DataFrame(np.round(true_centers), columns = data.keys())
true_centers.index = segments
display(true_centers)
true_good_data = pd.DataFrame(np.exp(good_data))
new_true_good_data = true_good_data.append(true_centers_new,ignore_index=True)
#Printing the heat map of the percentile values of the averages from Segment 0 and Segment 1 customers.
indices_new = [398,399]
#Percentile values of the the sampled data
percentile_values = 100. *new_true_good_data.rank(axis=0, pct=True).iloc[indices_new].round(decimals=3)
#heatmap of percentiled value
sns.heatmap(data=percentile_values,annot=True,fmt='.1f')
plt.yticks([0.5,1.5,2.5],['Segment 0','Segment 1'],rotation='horizontal')
plt.title('Percentile scores of customers from Segment 0 and 1')
plt.show()
display(true_good_data.describe())
Note: A customer who is assigned to 'Cluster X'
should best identify with the establishments represented by the feature set of 'Segment X'
. Think about what each segment represents in terms their values for the feature points chosen. Reference these values with the mean values to get some perspective into what kind of establishment they represent.
Answer:
The customers from Segment 0
have maximum spending in(above 75th percentile) Detergents_paper, Grocery and Milk. It also has above 50th percentile spending in Delicatessen products. This segment of customers likely represents a big cafe where we get everything, ranging from milk products like coffee, fast food items and also most probably desserts.
As we can see from the above data the customers in Segment 1
have above average spending in Fresh and Frozen products only. In all the other categories, these customers spend below average. It is to be noted that these customers spend a bit higher in Delicatessen products which is almost 42.5th percentile. Thus we can say that such customers are small shop owners whose main business is to serve fruit-vegetables and items made from frozen things like meat etc.
# Display the predictions
for i, pred in enumerate(sample_preds):
print("Sample point", i, "predicted to be in Cluster", pred)
#Percentile values of the the sampled data
percentile_values = 100. *data.rank(axis=0, pct=True).iloc[indices].round(decimals=3)
#heatmap of percentiled value
sns.heatmap(data=percentile_values,annot=True,fmt='.1f')
plt.yticks([0.5,1.5,2.5],['Customer 0, Index '+str(indices[0]),'Customer 1, Index '+str(indices[1]),'Customer 2, Index '+str(indices[2])],rotation='horizontal')
plt.title('Percentile scores of every value in the sampled data frame')
print("Chosen samples of wholesale customers dataset:")
display(samples)
Answer:
Customer(index) | Segment |
---|---|
Customer 0(3) | 1 |
Customer 1(87) | 1 |
Customer 2(200) | 0 |
Customer 0
and Customer 1
are clustered in Cluster 1
. This is consistent with our perdicted segment because as you can see from the above heatmap, Customer 0 and 1 have higher spending in Fresh, Frozen and Delicatessen. All other categories have lower spending as compared to the three categories mentioned before. This is in sync with our predicted Segment 0
customer where an average customer from this segment tends to follow this trend in spending.Cluster 0
customer. This is because Customer 2
tends to spend the maximum in Milk, Grocery and Detergents_paper which is again in sync with trend of spending of what an average customer of Segment 1
would do. In this final section, we will investigate ways that we can make use of the clustered data. First, we will consider how the different groups of customers, the customer segments, may be affected differently by a specific delivery scheme. Next, we will consider how giving a label to each customer (which segment that customer belongs to) can provide for additional features about the customer data. Finally, we will compare the customer segments to a hidden variable present in the data, to see whether the clustering identified certain relationships.
Companies will often run A/B tests when making small changes to their products or services to determine whether making that change will affect its customers positively or negatively. The wholesale distributor is considering changing its delivery service from currently 5 days a week to 3 days a week. However, the distributor will only make this change in delivery service for customers that react positively.
Answer:
Segment 0
who tend to spend more on Milk products will be unhappy with this new service while the customers from Segment 1
who spend less on Milk products and more on Frozen products will be indifferent to this new service.Additional structure is derived from originally unlabeled data when using clustering techniques. Since each customer has a customer segment it best identifies with (depending on the clustering algorithm applied), we can consider 'customer segment' as an engineered feature for the data. Assume the wholesale distributor recently acquired ten new customers and each provided estimates for anticipated annual spending of each product category. Knowing these estimates, the wholesale distributor wants to classify each new customer to a customer segment to determine the most appropriate delivery service.
Answer:
Segment 0
and Segment 1
.At the beginning of this project, it was discussed that the 'Channel'
and 'Region'
features would be excluded from the dataset so that the customer product categories were emphasized in the analysis. By reintroducing the 'Channel'
feature to the dataset, an interesting structure emerges when considering the same PCA dimensionality reduction applied earlier to the original dataset.
Run the code block below to see how each data point is labeled either 'HoReCa'
(Hotel/Restaurant/Cafe) or 'Retail'
the reduced space. In addition, we will find the sample points are circled in the plot, which will identify their labeling.
# Display the clustering results based on 'Channel' data
vs.channel_results(reduced_data, all_outliers, pca_samples)
Answer:
Retail
category whereas the same is not true for Hotels/Restaurants/Cafes
. This is visible from the graph above, which shows us that there are a lot of data points belonging to Hotels/Restaurants/Cafes
category which are present in the side where the Retail
cluster is, however not a lot of Retail
category data points are present in the cluster of Hotels/Restaurants/Cafes
. Now since we have a GMM clustering this means that the probability of Hotels/Restaurants/Cafes
selling retail products is higher as compared to the probability of a Retail
customer opening a hotel/resturant/cafe. This is visible in our day to day life too, there are cafes smaller or bigger that tend to sell products to their customers however we do not see a lot of vendors selling coffee or similar items.Customer 0
and Customer 1
is Segment 0
which as we specified earlier may belong to category of cafe and that of Customer 2
is Segment 1
which we specified earlier to be some vendor. These assumptions of ours are consistent with this true underlying distribution which shows us that Customer 0
and Customer 1
belong to Hotel/Restaurant/Cafe
category and Customer 2
belongs tp Retail
category.