Mini Project Clustering
Mini Project Clustering
This mini-project is based on this blog post by yhat. Please feel free to refer to the post for
additional information, and solutions.
# Setup Seaborn
sns.set_style("whitegrid")
sns.set_context("poster")
1.1 Data
The dataset contains information on marketing newsletters/e-mail campaigns (e-mail offers sent
to customers) and transaction level data from customers. The transactional data shows which
offer customers responded to, and what the customer ended up buying. The data is presented as
an Excel workbook containing two worksheets. Each worksheet contains a different dataset.
past_peak
1
0 False
1 False
2 True
3 True
4 True
We see that the first dataset contains information about each offer such as the month it is in
effect and several attributes about the wine that the offer refers to: the variety, minimum quantity,
discount, country of origin and whether or not it is past peak. The second dataset in the second
worksheet contains transactional data which offer each customer responded to.
In [20]: # merge
df_merge = df_transactions.merge(df_offers, how='left', on='offer_id') # s
df_merge.head()
2
4 Johnson 26 1 October Pinot Noir 144 83
origin past_peak
0 France False
1 Italy False
2 Germany False
3 Italy False
4 Australia False
In [32]: df_merge[df_merge.customer_name=='Allen']
origin past_peak
102 Chile False
103 New Zealand False
In [34]: # unfold
df_pivot = pd.pivot_table(df_merge, index='customer_name', columns='offer_
df_pivot.head()
offer_id 28 29 30 31 32
customer_name
Adams 0 1 1 0 0
Allen 0 0 0 0 0
Anderson 0 0 0 0 0
Bailey 0 0 1 0 0
Baker 0 0 0 1 0
[5 rows x 32 columns]
3
1.3.1 Choosing K: The Elbow Sum-of-Squares Method
The first method looks at the sum-of-squares error in each cluster against K. We compute the
distance from each data point to the center of the cluster (centroid) to which the data point was
assigned.
X X X X X
SS = (xi xj )2 = (xi k )2
k xi Ck xj Ck k xi Ck
where xi is a point, Ck represents cluster k and k is the centroid for cluster k. We can plot SS
vs. K and choose the elbow point in the plot as the best value for K. The elbow point is the point
at which the plot starts descending much more slowly.
Checkup Exercise Set II
Exercise:
What values of SS do you believe represent better clusterings? Why?
Create a numpy matrix x_cols with only the columns representing the offers (i.e. the 0/1
colums)
Write code that applies the KMeans clustering method from scikit-learn to this matrix.
Construct a plot showing SS for each K and pick K using this plot. For simplicity, test 2
K 10.
Make a bar chart showing the number of points in each cluster for k-means under the best K.
What challenges did you experience using the Elbow method to pick K?
Smaller values of SS represents better clusterings since smaller SS means each points is closer
to its assigned center. However, this explanation only assumes the number of centers given is
reasonable because in cases like large k or even k = n, the SS is very small but it does not make
any sense to cluster using such a big number of centers.
SS is 203.387.
offer_id 30 31 32 label
customer_name
Adams 1 0 0 0
4
Allen 0 0 0 2
Anderson 0 0 0 3
Bailey 1 0 0 0
Baker 0 1 0 4
[5 rows x 33 columns]
5
Since we dont want too many clusters since otherwise it would not make sense to cluster. We
observe that there is a significant drop in SS between 2 and 3 groups. We therefore choose the
optimal k as 3.
6
1.3.2 Choosing K: The Silhouette Method
There exists another method that measures how well each datapoint xi fits its assigned cluster
and also how poorly it fits into other clusters. This is a different way of looking at the same
objective. Denote axi as the average distance from xi to all other points within its own cluster k.
The lower the value, the better. On the other hand bxi is the minimum average distance from xi to
points in a different cluster, minimized over clusters. That is, compute separately for each cluster
the average distance from xi to the points within that cluster, and then take the minimum. The
silhouette s(xi ) is defined as
bxi axi
s(xi ) =
max (axi , bxi )
The silhouette score is computed on every datapoint in every cluster. The silhouette score ranges
from -1 (a poor clustering) to +1 (a very dense clustering) with 0 denoting the situation where
clusters overlap. Some criteria for the silhouette coefficient is provided in the table below.
Source: http://www.stat.berkeley.edu/~spector/s133/Clus.html
Fortunately, scikit-learn provides a function to compute this for us (phew!) called
sklearn.metrics.silhouette_score. Take a look at this article on picking K in scikit-learn,
as it will help you in the next exercise set.
Checkup Exercise Set III
Exercise: Using the documentation for the silhouette_score function above, construct a
series of silhouette plots like the ones in the article linked above.
7
Exercise: Compute the average silhouette score for each K and plot it. What K does the plot
suggest we should choose? Does it differ from what we found using the Elbow method?
X = x_col
silhouette_dict = {}
# The silhouette_score gives the average value for all the samples.
# This gives a perspective into the density and separation of the for
# clusters
silhouette_avg = silhouette_score(X, cluster_labels)
print("For n_clusters =", n_clusters,
"The average silhouette_score is :", silhouette_avg)
silhouette_dict[n_clusters] = silhouette_avg
y_lower = 10
for i in range(n_clusters):
# Aggregate the silhouette scores for samples belonging to
# cluster i, and sort them
8
ith_cluster_silhouette_values = \
sample_silhouette_values[cluster_labels == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
# The vertical line for average silhouette score of all the values
ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
plt.show()
9
For n_clusters = 3 The average silhouette_score is : 0.250659377196
10
For n_clusters = 4 The average silhouette_score is : 0.236772886303
11
For n_clusters = 5 The average silhouette_score is : 0.209951014144
12
For n_clusters = 6 The average silhouette_score is : 0.205119021976
13
For n_clusters = 7 The average silhouette_score is : 0.192867897806
14
For n_clusters = 8 The average silhouette_score is : 0.193458942962
15
For n_clusters = 9 The average silhouette_score is : 0.170224641456
16
For n_clusters = 10 The average silhouette_score is : 0.16821550099
17
In [139]: # plot silhouette score
plt.plot(list(range(2,11)), list(silhouette_dict.values()))
plt.xlabel('k')
plt.ylabel('Silhouette Score')
plt.show()
18
According to the plot of Silhouette score, since we obtained the highest Silhouette score at k
= 2, we therefore conclude that there the optimal k is 2, which is different from the optimal k
concluded from Elbow method.
19
1.3.4 Aside: Choosing K when we Have Labels
Unsupervised learning expects that we do not have the labels. In some situations, we may wish to
cluster data that is labeled. Computing the optimal number of clusters is much easier if we have
access to labels. There are several methods available. We will not go into the math or details since
it is rare to have access to the labels, but we provide the names and references of these measures.
# For k=5
cluster = KMeans(n_clusters=5, random_state=10)
20
df_pivot['cluster'] = cluster.fit_predict(x_col)
# Create a scatterplot of the reduced data when k=5 as shown through the
plt.rcParams["figure.figsize"] = (5,5)
colors = {0:'blue', 1:'red', 2:'green', 3:'purple', 4:'yellow'}
plt.scatter(x=df_pca['x'], y=df_pca['y'], c=df_pivot['cluster'].apply(lam
plt.xticks(size=10)
plt.xlabel('1st principal component', size=12)
plt.yticks(size=10)
plt.ylabel('2nd principal component', size=12)
plt.title('Cluster Representation by\n 2 Principal Components (k=5)', siz
21
What weve done is weve taken those columns of 0/1 indicator variables, and weve trans-
formed them into a 2-D dataset. We took one column and arbitrarily called it x and then called
the other y. Now we can throw each point into a scatterplot. We color coded each point based on
its cluster so its easier to see them.
Exercise Set V
As we saw earlier, PCA has a lot of other uses. Since we wanted to visualize our data in 2
dimensions, restricted the number of dimensions to 2 in PCA. But what is the true optimal number
of dimensions?
Exercise: Using a new PCA object shown in the next cell, plot the explained_variance_
field and look for the elbow point, the point where the curves rate of descent seems to slow
sharply. This value is one possible value for the optimal number of dimensions. What is it?
# Create a scatterplot of the reduced data when k=5 as shown through the
plt.rcParams["figure.figsize"] = (5,5)
colors = {0:'blue', 1:'red', 2:'green', 3:'purple', 4:'yellow'}
plt.scatter(x=df_pca['x'], y=df_pca['y'], c=df_pivot['cluster'].apply(lam
plt.xticks(size=10)
plt.xlabel('1st principal component', size=12)
plt.yticks(size=10)
plt.ylabel('2nd principal component', size=12)
plt.title('Cluster Representation by\n 2 Principal Components (k=3)', siz
22
In [156]: # Initialize a PCA where components = number of features
# Extract the explained variance in a dataframe
pca = sklearn.decomposition.PCA(n_components=32)
pca.fit(x_col)
variance_pca_df = pd.DataFrame(data={'components':range(1,33),
'explained_variance':pca.explained_v
23
In [160]: variance_pca_df = pd.DataFrame()
for dimension in range(1,33):
pca = sklearn.decomposition.PCA(n_components=dimension)
pca.fit(x_col)
temp_df = pd.DataFrame(data={'components':dimension,
'explained_variance':pca.explained_varia
index=[0])
variance_pca_df = variance_pca_df.append(temp_df)
24
1.5 Other Clustering Algorithms
k-means is only one of a ton of clustering algorithms. Below is a brief description of several
clustering algorithms, and the table provides references to the other clustering algorithms in scikit-
learn.
Affinity Propagation does not require the number of clusters K to be known in advance!
AP uses a message passing paradigm to cluster points based on their similarity.
Spectral Clustering uses the eigenvalues of a similarity matrix to reduce the dimensional-
ity of the data before clustering in a lower dimensional space. This is tangentially similar
to what we did to visualize k-means clusters using PCA. The number of clusters must be
known a priori.
25
Hierarchical clustering is divisive, that is, all observations are part of the same cluster at first,
and at each successive iteration, the clusters are made smaller and smaller. With hierarchi-
cal clustering, a hierarchy is constructed, and there is not really the concept of number of
clusters. The number of clusters simply determines how low or how high in the hierarchy
we reference and can be determined empirically or by looking at the dendogram.
DBSCAN is based on point density rather than distance. It groups together points with
many nearby neighbors. DBSCAN is one of the most cited algorithms in the literature. It
does not require knowing the number of clusters a priori, but does require specifying the
neighborhood size.
26
Distances between points
Agglomerative clustering
number of clusters, linkage type, distance
Large n_samples and n_clusters
Many clusters, possibly connectivity constraints, non Euclidean distances
Any pairwise distance
DBSCAN
neighborhood size
Very large n_samples, medium n_clusters
Non-flat geometry, uneven cluster sizes
Distances between nearest points
Gaussian mixtures
many
Not scalable
Flat geometry, good for density estimation
Mahalanobis distances to centers
Birch
branching factor, threshold, optional global clusterer.
Large n_clusters and n_samples
Large dataset, outlier removal, data reduction.
Euclidean distance between points
Source: http://scikit-learn.org/stable/modules/clustering.html
Exercise Set VI
Exercise: Try clustering using the following algorithms.
Affinity propagation
Spectral clustering
Agglomerative clustering
DBSCAN
How do their results compare? Which performs the best? Tell a story why you think it per-
forms the best.
(Partial code below are from https://github.com/dpalbrecht/Springboard-Exercises)
cluster = AffinityPropagation()
df_pivot['cluster'] = cluster.fit_predict(x_col)
27
# Concatenate the data frames
df_pivot_short_2 = pd.DataFrame(X, columns=['x', 'y'])
df_pca = pd.concat([df_pivot_short, df_pivot_short_2], axis=1)
28
from sklearn.cluster import SpectralClustering
cluster = SpectralClustering(n_clusters=3)
df_pivot['cluster'] = cluster.fit_predict(x_col)
Number of clusters: 3
29
In [169]: # 3. Try agglomerative clustering
cluster = AgglomerativeClustering(n_clusters=3)
df_pivot['cluster'] = cluster.fit_predict(x_col)
30
# Concatenate the data frames
df_pivot_short_2 = pd.DataFrame(X, columns=['x', 'y'])
df_pca = pd.concat([df_pivot_short, df_pivot_short_2], axis=1)
31
cluster = DBSCAN(min_samples=3)
df_pivot['cluster'] = cluster.fit_predict(x_col)
Number of clusters: 4
Percent of instances classified as noise: 91.0%
32
33