author: Alexander Frieden date: 3/31/2016 autosize: true
-
4/22 we are set to have class, need to reschedule for a different night that week
-
Remember homework is due next week
-
We covered trees, what they are
-
We experimented with naive approaches in how to cut it up.
-
K-means clustering is a imple and elegant approach for partitioning a data set into K distinct and disjoint clusters.
-
This means none of these elements have any overlap.
-
Requires input parameter of number of clusters.
-
Algorithm will assign each observation to exactly one of the K clusters.
Let
In other words, each observation belongs to at least one of the K clusters.
For all
For instance if the ith observation is in the kth cluster, then
The idea behind K-means clustering is that a good clustering is one for which the winthin-cluster variation is as small as possible. The within-cluster variation.
The within-cluster variation for cluster
In other words, this formula says that we want to partition the observations into K clusters such that the total within-cluster variation, summed over all K clusters is as small as possible.
Solving (1) seems reasonable. However, in order to make it actionable we need to define the within-cluster variation. There are many possible ways to define this concept, but by far the most common choice involves Squared Euclidean distance. Thus:
Where
Combing (1) and (2) we arrive at the optimization that defines K-mean clustering.
Some of the figures in this presentation are taken from "An Introduction to Statistical Learning, with applications in R" (Springer, 2013) with permission from the authors: G. James, D. Witten, T. Hastie and R. Tibshirani
The following is a simulated data set with 150 observations in 2-d space. Panels show K-means clustering with different values of K.
Now we want to find an algorithm to solve (3).
In general, this is very difficult to solve precisely. There are at most
Luckily, K-means clustering algorithm can proivde a local optimum.
-
Randomly assin a number from 1 to
$K$ to each of the observations. These serve as initial cluster assignments for the observations . -
Iterate until the cluster asignments stop changing:
- For each of the
$K$ clusters, compute the cluster centroid. The kth cluster centroid is the vector of the p feature means for the observations in the kth cluster. - Assign each observation to the cluster whose centroid is closest (where closest is defined using Euclidean distance)
The algorithm is guaranteed to decrease the value of objective (3) at each step.
To understand why, the following is illuminating: $$ \tag{4} \frac{1}{|C_k|}\sum_{i,i^{\prime}\in C_k}\sum_{j=1}^{p}(x_{ij} - x_{i^{\prime}j})^2 = 2\sum_{i\in C_k}\sum_{j=1}^p(x_ij - \bar{x}_{kj})^2 $$
Here $,\bar{x}{kj} = \frac{1}{|C_k|}\sum{i\in C_k}x_{ij}$ is the mean for feature j in cluster
In step 2a of our algorithm the cluster means for each feature are teh contants that minimize the sum-of-squared deviations.
In step 2b reallocating the observations can only improve (4). This means that as the algorithm is run, the clustering will continue to improve a local optimum is reached.
The name of the algorithm's name comes from that in step 2a the cluster centroids are computed as the mean of the observations assigned to each cluster.
-
Because the K-means algorithm finds a local rather than a global optimum, the results obtained are a function of the initial conditions, in particular the random cluster assignment.
-
For this reason it is important to run your algorithm multiple times.
-
It turns out that iteratively arriving at the optimum doesn't take very many iterations, thus finding the number of iterations takes some experimenting, as running some of these computations can take a very long time.
-
After different initial conditions, one can select the best solution, i.e. one that minimizes (3).
The previous is K-means clustering with K=3 from slide 10.5, each with different random value input from step 1.
Some decisions needs to be made when planning on clustering
-
Should the observations or features first be standardized in some way? For instance, maybe the variables should be centered to have mean zero and scaled to have standard deviation one.
-
In the case of K-means clustering, how many clusters should we look for in the data?
In practice we try several different choices and experiment with parameters for various data sets.
Clustering methods are generally not very good at being robust against perturbations.
For example, suppose we cluster
However, this is not often the case.
The function kmeans() performs K-means clustering in R. We begin a simple simulated example in which there truly are two clusters in the data.
The first twenty five observations have a mean shift relative to the twenty five observations
set.seed(2)
x=matrix(rnorm(50*2), ncol=2)
head(x) [,1] [,2]
[1,] -0.89691455 -0.8382871
[2,] 0.18484918 2.0663014
[3,] 1.58784533 -0.5622471
[4,] -1.13037567 1.2757155
[5,] -0.08025176 -1.0475726
[6,] 0.13242028 -1.9658782
Shift the entries
x[1:25,1]=x[1:25,1] + 3
x[1:25,2]=x[1:25,2] - 4Now perform K-means clustering with
km.out=kmeans(x,2,nstart=20)The cluster assignments of the 50 observations are contained in
km.out$cluster [1] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
[36] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
The K-means clustering perfectly seperated the observations into two clusters even though we did not supply any group information to kmeans().
We can plot the data, with each observation colored according to its cluster assignment
plot(x,col=(km.out$cluster+1), main="K-Means Clustering Results with K=2", xlab = "", ylab = "", pch=20, cex=2)Here the we are able to plot this because our data is two dimensional.
If it was greater than two dimensional than we could instead run PCA and look at first two prinicpal components.
In general we don't know how many clusters, so lets try this with three clusters.
set.seed(4)
km.out=kmeans(x,3,nstart=20)K-means clustering with 3 clusters of sizes 10, 23, 17
Cluster means:
[,1] [,2]
1 2.3001545 -2.69622023
2 -0.3820397 -0.08740753
3 3.7789567 -4.56200798
Clustering vector:
[1] 3 1 3 1 3 3 3 1 3 1 3 1 3 1 3 1 3 3 3 3 3 1 3 3 3 2 2 2 2 2 2 2 2 2 2
[36] 2 2 2 2 2 2 2 2 1 2 1 2 2 2 2
Within cluster sum of squares by cluster:
[1] 19.56137 52.67700 25.74089
(between_SS / total_SS = 79.3 %)
Available components:
[1] "cluster" "centers" "totss" "withinss"
[5] "tot.withinss" "betweenss" "size" "iter"
[9] "ifault"
While its tough to see, when we set
To run kmeans() with multple initial cluster assignments, we use the nstart argument.
If the nstart argument is greater than one, then K-means clustering will use multiple random assignments for intiial observation assignment.
Here we are comparing nstart=1 vs nstart=20.
set.seed(3)
km.out=kmeans(x,3,nstart=1)
km.out$tot.withinss[1] 104.3319
km.out=kmeans(x,3,nstart=20)
km.out$tot.withinss[1] 97.97927
Note that km.out$tot.withinss is the total within-cluster sum of squares which we seek to minimize by performing K-means clustering.
The individual within-cluster sum-of-squares are contaied in the vector km.out$tot.withinss
It is always recommended to run K-means clustering with a large value of nstart such as 20 or 50. Otherwise local optimums that are misrepresenting our data can be obtained.
It is also important to use the set.seed() function so that the results are reproducible.
One potential disadvantage of K-means clustering is that it requires us to pre-specify the number of clusteres K.
Hierarchial clustering is an alternative approach which does not require that we commit to a particular choice of K.
Hierarchial clustering has the added advantage over K-means clustering in that it results in an attractive tree-based representation of the observation, called a dendrogram.
We will be looking at bottom up clustering which refers to the idea that the leaves are built first then we combine clusters to get the trunk.
In the following figure, each leaf of the dendrogram respresents one of the 45 observations from our earlier example.
As we move up the tree, some leaves begin to fuse into branches. These correspond to observations that are similar to eacah other.
Fusions further down correspond to groupings that are similar, where as the higher up fusions correspond to groupings that are not similar.
We can make this precise:
For any two observations, we can look at the point in the tree where branches containing those two observations are first fused.
The height of the fusion, as measured on the vertical axis, indicates how different the two observations are.
We can read this by seeing that points 5 and 7 are close so they are branched together at a low point.
7 and 9 are far away from each other so they are branched very high, in fact at the trunk.
It is tempting but incorrect to conclude from the figure that observations 9 and 2 are quite similar to each other on the bais that they are located near each other on the dendrogram.
In fact, observation 9 is no more similar to observation 2 than it is to observations 8, 5, and 7.
There are
This is because at each of the
We cannot draw conclusions based on their proximity along the horizontal axis. We have to use vertical axis.
In order to cluster the dendrogram, we perform a horizontal cut across the tree.
The height of the cut serves the same role as the K in K-means clustering. It controls how many clusters are available.
We begin by defining some sort of dissiilarity measure between each pair of observations. Most often Euclidean distance is used.
The algorithm proceeds iteratively. Starting out at the bottom of the dendrogram, each of the n observations is treated as its own cluster.
The two clusters that are the most similar to each other are then fused so that there now are
Do this again for the next two that are most similar. Now there are
One potential problem: How do we determine if a cluster should be fused to a pair of observations? We need to extend our idea of dissimilarity to groups of observations.
We can do this by developing the notion of linkage, which defines the similarity between two groups of observations.
The four most commmon types of linkage: complete, average, single, and centroid. Average, complete, and single linkage are most popular among statisticians.
-
Begin with
$n$ observations and a measure (such as Euclidean) of all${n \choose 2} = n(n-1)/2$ pairwise dissimilarities. Treat each observation as its own cluster. -
For
$i=n,n-1,...,2$
- Examine all pairwise inter-cluster dissimilarities among the i clusters and identify the pair of clusters that are least dissimilar. Fuse those two clusters. The dissimilarity between these two clusters indicates the height in the dendrogram at which the fusion should be placed.
- Computer the new pairwise inter-cluster dissimilarities among the i - 1 remaining clusters.
Maximal Intercluster dissimilarity.
Compute all pairwise dissimilarities between the observations in cluster A and the observations in cluster B, and record the largest of these dissimilarities.
Minimal intercluster dissimilarity.
Compute all pairwise dissimilarities between the observations in cluster A and the observations in cluster B, and record the smallest of these dissimilarities.
Simple linkage can result in extended, trailing clusters in which single observations are fused one-at-a-time.
Mean intercluster dissimilarity.
Compute all pairewise dissimilarities between the observations in cluster A and the observations in cluster B, and record the average of these dissimilarities.
Dissimilarity between the centroid for cluster A (a mean vector of length
Centroid linkage can result in undesriable inversions.
Choice of dissimilarity measure has a major role on what the dendrogram looks like and where our data clusters.
We can do things like Euclidean Distance, Correlation-based distance, etc. We will not go into how these are chosen and consequences of this.
The hclust() function implements hierarchical clustering in R.
In the following example we are going to plot data using this method with the different types of linking.
The dist() function is used to to compute a matrix of inter-observation Euclidean distance matrix.
Changing the method parameter would allow us to do average or single
hc.complete = hclust(dist(x), method="complete")
hc.average = hclust(dist(x), method="average")
hc.single = hclust(dist(x), method="single")
hc.complete
Call:
hclust(d = dist(x), method = "complete")
Cluster method : complete
Distance : euclidean
Number of objects: 50
We can now plot the denodrograms obtained using the plot function.
The numbers at the bottom of the plot identify each observation.
To determine the cluster labels for each observation associated with a given cut of the denodrogram, we can use cuttree()
cutree(hc.complete, 2) [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
[36] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
cutree(hc.average, 2) [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 1 2 2
[36] 2 2 2 2 2 2 2 2 1 2 1 2 2 2 2
cutree(hc.single, 2) [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[36] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
From this data, complete and average linkage generally seperate the observations into their correct group.
However, single linkage identifies one point as belonging to its own cluster. When we look to sort into four groups, there are still two singletons.
cutree(hc.single,4) [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 3 3 3 3 3 3 3 3 3 3
[36] 3 3 3 3 3 3 4 3 3 3 3 3 3 3 3
To scale the variables before HC, we use scale()
xsc=scale(x)
plot(hclust(dist(xsc),method="complete"), main = "Hierarchial Clustering with Scaled Features")Here we are going to use unsupervised methods to analyze genomic data.
NCI60 is a cancer cell line microarray data.
This data consists of 6830 gene expression measurements on 64 cancer cell lines
Add our data
library(ISLR)
nci.labs=NCI60$labs
nci.data=NCI60$dataNote that every cell line is labeled with a cancer type.
One analysis we could perform is to run PCA on our data, then type if the groupings have anything to do with type and trying to filter down to get the types.
We want to use hierarchical clustering to see if observations cluster into distinct types of cancer.
To start, we standardize the variables to have mean zero and standard deviation one. We do this because we don't want to weight any genes heavier than any other ones.
sd.data = scale(nci.data)We now perform hierarchical clustering using complete, single, and average linkage. Euclidean distance is used as our measure.
Choice of linkage affects results obtained.
Typically Single linkage will yield trailing clusters. These are very large clusteres onto which individual observations attach one-by-one.
Complete and Average tend to be more balanced clusters. A priori, we would choose go with complete and average linkage.
Lets look at a cut of four on our dendrogram.
hc.out=hclust(dist(sd.data))
hc.clusters=cutree(hc.out,4)
table(hc.clusters, nci.labs) nci.labs
hc.clusters BREAST CNS COLON K562A-repro K562B-repro LEUKEMIA MCF7A-repro
1 2 3 2 0 0 0 0
2 3 2 0 0 0 0 0
3 0 0 0 1 1 6 0
4 2 0 5 0 0 0 1
nci.labs
hc.clusters MCF7D-repro MELANOMA NSCLC OVARIAN PROSTATE RENAL UNKNOWN
1 0 8 8 6 2 8 1
2 0 0 1 0 0 1 0
3 0 0 0 0 0 0 0
4 1 0 0 0 0 0 0
Some patterns emerge: All leukemia cell lines fall in cluster 3.
All breast cancer cell lines are spread out about evenly NOT in cluster 3.
Lets look at the plot next.
The abline() function draws a straight line on top of any existing plot.
The argument h=139 is chosen to give four distinct clusters.
It can be verified that the resulting clusters are the same as the ones we obtained from cutree(hc.out,4)
Lets take a look at hc.out
hc.out
Call:
hclust(d = dist(sd.data))
Cluster method : complete
Distance : euclidean
Number of objects: 64
Before we claimed that K-means clustering and hierarchial clustering with the dendrogram cut to obtain the same number of clusteres can yield very different results.
Lets run this exerise using the NCI60 data set. How does our hierarchical clustering compare to what we get if we perform K-means clustering on
set.seed(2)
km.out=kmeans(sd.data, 4, nstart=20)
km.clusters=km.out$cluster
table(km.clusters,hc.clusters) hc.clusters
km.clusters 1 2 3 4
1 11 0 0 9
2 0 0 8 0
3 9 0 0 0
4 20 7 0 0
We see the results using each method are somewhat different. What would this have looked like if these had been the same?
table(hc.clusters,hc.clusters) hc.clusters
hc.clusters 1 2 3 4
1 40 0 0 0
2 0 7 0 0
3 0 0 8 0
4 0 0 0 9
table(km.clusters,km.clusters) km.clusters
km.clusters 1 2 3 4
1 20 0 0 0
2 0 8 0 0
3 0 0 9 0
4 0 0 0 27
Also note that cluster 2 in K-means is identical to cluster 3 in hierarchical clustering. However the rest different.
Sometimes performing hierarchical clustering on the first few principal component score vectors can give better results.
PCA can remove a lot of the noise from our data and give us a cleaner dendrogram.
Similarly for K-means.




