🏙 Machine Learning Engineer Nanodegree   🌀   Home Page      

Unsupervised Learning

📑  P3: Creating Customer Segments

Getting Started

Dataset

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.

Resources

🕸UCI Machine Learning Repository  🕸scikit-learn. Machine Learning in Python  🕸seaborn: statistical data visualization 

Code Library






Data Exploration

In this section, we will begin exploring the data through visualizations and code to understand how each feature is related to the others.
We 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 you will track through the course of this project.
The dataset is composed of six important product categories: Fresh, Milk, Grocery, Frozen, Detergents_Paper, and Delicatessen.
Consider what each category represents in terms of products we could purchase.

Data Loading



Implementation: Selecting Samples

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, add three indices of your choice to the indices list which will represent the customers to track.
It is suggested to try different sets of samples until you obtain customers that vary significantly from one another.

Question 1

Consider the total purchase cost of each product category and the statistical description of the dataset above for your sample customers.
What kind of establishment (customer) could each of the three samples you've chosen represent?

Answer 1

I have built a plot for comparing the feature values with the means and a heatmap to visualize for each customer the spending amount per feature in percentages.



Customer C0 - food-oriented supermarket:
- the wide range of products with big values;
- the significant excess of the purchasing volumes of categories Fresh, Milk over others;
- the purchasing volumes of categories Fresh, Grocery, Milk, Delicatessen are much higher than the mean values;
- the categories Detergents_Paper, Frozen are close to the means values.
Customer C1 - market for the nearest neighborhood:
- the highest purchasing volumes are in the category Fresh;
- the purchasing volumes of all categories are close to the mean values.
Customer C2 - vegetarian cafe or restaurant:
- the significant excess of the purchasing volumes of the category Fresh over others;
- the purchasing volumes of categories Frozen, Grocery, Milk, Detergents_Paper are lower than the mean values;
- the purchasing volumes of the category Detergents_Paper are extremely small.

Implementation: Feature Relevance

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.
In the code block below, we will need to implement the following:
Assign new_data a copy of the data by removing a feature of our choice using the DataFrame.drop function.
Use sklearn.model_selection.train_test_split to split the dataset into training and testing sets.
  Use the removed feature as our target label.
  Set the test_size of 0.25 and set the random_state parameter.
Import the Decision Tree Regressor, set the random_state parameter, and fit the learner to the training data.
Report the prediction score of the testing set using the regressor's score function.

Experiment with Delicatessen


pylab.figure(figsize=(10,5)) seaborn.distplot(target,color='#1b2c45',bins=200, hist_kws={'color':'SlateGrey'}) pylab.xlabel('Delicatessen',fontsize=15) pylab.title('Customers` Annual Spending',fontsize=15,color='#5a8bbd') pylab.grid(); pylab.tight_layout(); pylab.show()



Experiment with Grocery




Question 2

Which feature did you attempt to predict? What was the reported prediction score? Is this feature is necessary for identifying customers' spending habits?

Answer 2

I have chosen Grocery.
In this case, the reported score for predictions is much higher, and the feature has a strong correlation with at least two others (Detergents_Paper and Milk).
Therefore, it was easy to predict Grocery values by applying a simple regressor (Decision Tree).
An ensemble regressor (Random Forest) demonstrates better results and confirms the assumptions.
It means also that this feature is not so important for identifying spending habits of customers, and these strong
relationships between variables make possible to run the procedure of dimensionality reduction.
The experiment with Delicatessen demonstrates the fact that it's hard to predict the values of this feature based on others, so Delicatessen is important for custom clustering.

Visualize Feature Distributions

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 we found that the feature we 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 we 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.


Question 3

Are there any pairs of features which exhibit some degree of correlation?
Does this confirm or deny your suspicions about the relevance of the feature you attempted to predict?
How is the data for those features distributed?

Answer 3

The highest degree of correlation has the pair Grocery-Detergents_Paper. These scatter plots demonstrate it very clearly.
There are some pairs else with a well-detectable correlation: Milk-Grocery and Milk-Detergents_Paper.
These facts confirm the thoughts about the relevance of the feature we attempted to predict.
We should also note that the features is not normally distributed. But the log-normal distribution looks very similar with our features.
I have created the random example of the log-normal distribution for visual comparing.

Data Preprocessing

In this section, we will preprocessing 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 you obtain from your analysis are significant and meaningful.

Implementation: Feature Scaling

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.
Now we will do the following steps:
  Assign a copy of the data to log_data after applying logarithmic scaling. Use the numpy.log function for this.
  Assign a copy of the sample data to log_samples after applying logarithmic scaling. Again, use numpy.log.

Observation

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).


Implementation: Outlier Detection

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 the 🕸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.
So the next steps are the following:
Assign the value of the 25th percentile for the given feature to Q1. Use numpy.percentile for this.
Assign the value of the 75th percentile for the given feature to Q3. Again, use numpy.percentile.
Assign the calculation of an outlier step for the given feature to step.
Optionally remove data points from the dataset by adding indices to the outliers list.

Question 4

Are there any data points considered outliers for more than one feature based on the definition above?
Should these data points be removed from the dataset?
If any data points were added to the outliers list to be removed, explain why.

Answer 4

Five data points [65, 66, 75, 128, 154] can be detected as outliers for more than one feature.
It's confirmed by another method with a heatmap in the original data. I think it needs to remove them from the data.
When we apply k-means the results can be distorted by outliers: clusters are constructed with calculations of cluster-centers
as the averages of all data points from this cluster, so outliers can have a great influence.
If we do not remove outliers from the dataset, they can form additional artificial clusters for the outliers which can get some data points from the real clusters.

Feature Transformation

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.

Implementation: PCA

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.
The next steps are the following:
Import sklearn.decomposition.PCA and assign the results of fitting PCA in six dimensions with good_data to pca.
Apply a PCA transformation of log_samples using pca.transform, and assign the results to pca_samples.


Question 5

How much variance in the data is explained in total by the first and second principal component? What about the first four principal components?
Using the visualization provided above, discuss what the first four dimensions best represent in terms of customer spending.

Answer 5

Dimension 1: features Milk, Grocery, Detergents_Paper have the highest influence, so it seems like a regular household spending on retail goods in supermarkets.
We noted in the previous section that these three features are highly correlated.
Dimension 2: features Fresh, Frozen, Delicatessen are the most important, so it can be a spending for restaurants and cafes with a wide spectrum of the menu.
Dimension 3: features Fresh, Frozen, Delicatessen are the most important also but they have different directions,
so it can be a spending on retail goods in the nearest stores and markets.
Dimension 4: features Fresh, Frozen, Delicatessen are the most important again but Frozen has the highest influence,
so it can be a spending for restaurants and cafes with a special spectrum of the menu (fast food, for example).
The first four dimensions represent enough well in terms of customer spending because they have explained the main part of the spending variance.

PCA Observation

Let us have a look 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.
Consider if this is consistent with our initial interpretation of the sample points.

Implementation: Dimensionality Reduction

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 is 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.
The next steps are the following:
Assign the results of fitting PCA in two dimensions with good_data to pca.
Apply a PCA transformation of good_data using pca.transform, and assign the results to reduced_data.
Apply a PCA transformation of log_samples using pca.transform, and assign the results to pca_samples.

Dimensionality Reduction Observation

Let's 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.

Visualizing a Biplot

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.

Biplot Observation

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 we obtained earlier?

The features Milk, Grocery, Detergents_Paper are most strongly correlated with the first component (their projections are very close to the horizontal line).
The features Fresh, Frozen, Delicatessen are correlated with the second component but not so strongly (their projections are close to the vertical line).
The pca_results plot displays exactly the same observations.

Clustering

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.

Question 6

What are the advantages to using a K-Means clustering algorithm?
What are the advantages to using a Gaussian Mixture Model clustering algorithm?
Given your observations about the wholesale customer data so far, which of the two algorithms will you use and why?

Answer 6

The advantages of the K-Means clustering in comparing with the Gaussian Mixture Model clustering are speed and simplicity.
K-means only maintains cluster centers (linearly correlated with the feature numbers) and it will be much faster in model training.
The advantages of the Gaussian Mixture Model are a "soft" classification (indicated how likely the concrete data point belongs to the certain cluster) and
a good performance with different data distributions.
Theoretically, the Gaussian Mixture Model can do the job better thanks to its soft classification,
but the K-Means also can predict correctly without additional complexity of the model.
This project is not so large so we can try to apply both just to compare algorithms in action.

Implementation: Creating Clusters

Depending on the problem, the number of clusters that we 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.
Now we need to implement the following:
Fit a clustering algorithm to the reduced_data and assign it to clusterer.
Predict the cluster for each data point in reduced_data using clusterer.predict and assign them to preds.
Find the cluster centers using the algorithm's respective attribute and assign them to centers.
Predict the cluster for each sample data point in pca_samples and assign them sample_preds.
Import sklearn.metrics.silhouette_score and calculate the silhouette score of reduced_data against preds.
  Assign the silhouette score to score and print the result.

Question 7

Report the silhouette score for several cluster numbers you tried. Of these, which number of clusters has the best silhouette score?

Answer 7

I have printed scores for the K-Means clustering and the Gaussian Mixture Model.
We can see the highest scores in case of 2 clusters for both algorithms. So it should be our choice.


We also can run the speed comparison for the K-Means clustering and the Gaussian Mixture Model.

Cluster Visualization

Once we've chosen the optimal number of clusters for the clustering algorithm using the scoring metric above, we can now visualize the results.
Note that, for experimentation purposes, it's useful to adjust the number of clusters for the clustering algorithm to see various visualizations.
The final visualization provided should, however, correspond with the optimal number of clusters.


Implementation: Data Recovery

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.
It's time for the next steps:
Apply the inverse transform to centers using pca.inverse_transform and assign the new centers to log_centers.
Apply the inverse function of numpy.log to log_centers using numpy.exp and assign the true centers to true_centers.





Question 8

Consider the total purchase cost of each product category for the representative data points above,
and reference the statistical description of the dataset at the beginning of this project.
What set of establishments could each of the customer segments represent?

Answer 8

The values in categories are perfect indicators:
Detergents_Paper, Grocery, Milk, Delicatessen are higher than the mean for Retail and less than the mean for HoReCa (Hotel/Restaurant/Cafe).
Fresh has the highest level among others for HoReCa than for Retail.
Detergents_Paper has an extremely small level for HoReCa.

Question 9

For each sample point, which customer segment from Question 8 best represents it?
Are the predictions for each sample point consistent with this?

Answer 9



Conclusion

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.

Question 10

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.
How can the wholesale distributor use the customer segments to determine which customers, if any, would react positively to the change in delivery service?

Answer 10

If we reduce the delivery frequency for Retail it's possible to have a positive reaction:
they do not order a lot of fresh food, it can reduce the transport cost, and their spending values are more predictable and regular.
But some reactions could be negative: many supermarkets try to minimize inventory to save cost.
The customers in HoReCa (Hotel/Restaurant/Cafe) can react positively if they have enough places for saving food.
But a negative reaction also can be: some of them do not have enough space for saving, but they need fresh food for their business.
For both segments, a negative effect is possible.
Only an A/B test can detect if actually true.
We can run the A/B test with randomly selected samples for each cluster.
It is possible to have absolutely different tendencies in the test results.
One segment could have the significant effect, another segment could not demonstrate it.
Their spending habits are not similar. If we mixed them we could lose information about the real effect.

Question 11

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.
How can the wholesale distributor label the new customers using only their estimated product spending and the customer segment data?

Answer 11

There are several ways for using and improving analytic predictions for labels:
- the clustering algorithms K-Means and GMMs updated for the new data points to include them into the certain clusters;
- supervised learning algorithms to detect differences between clusters, cluster labels can be just a target in the model predictions for new data points.

Visualizing Underlying Distributions

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.
Let's 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.

Question 12

How well does the clustering algorithm and number of clusters you've chosen compare to this underlying distribution of Hotel/Restaurant/Cafe customers to Retailer customers?
Are there customer segments that would be classified as purely Retailers or Hotels/Restaurants/Cafes by this distribution?
Would you consider these classifications as consistent with your previous definition of the customer segments?

Answer 12

The number of clusters is consistent with the underlying distribution so both clustering algorithms work enough well.
As we can see the K-Means simplicity does not affect the efficiency in this case.
The customer segments classified as purely Retailers or Hotels/Restaurants/Cafes on the left side and on the right side accordingly.
The algorithmic classification in the majority of cases is in line with the real results.
We should note that for both algorithms borders of clusters are more clearly detectable.
Differences between actual and algorithmic classification may indicate a lack of the number of clusters for this market.
Perhaps it needs a greater number to detect spending habits.

Reflections

It would be interesting to repeat the steps of this project in R and compare the results.
Or try animation for clustering algorithms to compare the borders of clusters with real data labels during the learning process.

Additional Code Cell