SOCR ≫ | DSPA ≫ | Topics ≫ |
As we learned in Chapters 6-8, classification could help us make predictions on new observations. However, classification requires (human supervised) predefined label classes. What if we are in the early phases of a study and/or don’t have the required resources to manually define, derive or generate these class labels?
Clustering can help us explore the dataset and separate cases into groups representing similar traits or characteristics. Each group could be a potential candidate for a class. Clustering is used for exploratory data analytics, i.e., as unsupervised learning, rather than for confirmatory analytics or for predicting specific outcomes.
In this chapter, we will present (1) clustering as a machine learning task, (2) the silhouette plots for assessing the reliability of clustering, (3) the k-Means clustering algorithm and how to tune it, (4) examples of several interesting case-studies, including Divorce and Consequences on Young Adults, Pediatric Trauma, and Youth Development, (5) demonstrate hierarchical clustering, (6) show spectral clustering, and (7) present Gaussian mixture modeling.
As we mentioned earlier, clustering is a machine learning technique that bundles unlabeled cases into groups. Scatter plots we saw in previous chapters represent a simple illustration of the clustering process. Let’s start with a hotdogs example. Assume we don’t know much about the ingredients of frankfurter hot dogs and we look the following graph.
In terms of calories and sodium, these hot dogs are clearly separated into three different clusters. Cluster 1 has hot dogs of low calories and medium sodium content; Cluster 2 has both calorie and sodium at medium levels; Cluster 3 has both sodium and calories at high levels. We can make a bold guess about the ingredients used in the hot dogs in these three clusters. For cluster 1, it could be mostly chicken meat since it has low calories. The second cluster might be beef and the third one is likely to be pork, because beef hot dogs have considerably less calories and salt than pork hot dogs. However, this is just guessing. Some hot dogs have a mixture of two or three types of meat. The real situation is somewhat similar to what we guessed but with some random noise, especially in cluster 2.
The following plot shows a more nuanced scatter of the primary type of meat used for each hotdog designated by color and and glyph-symbol for meat-type.
Silhouette plots are useful for interpretation and validation of consistency of all clustering algorithms. The silhouette value, \(sil \in [-1,1]\), measures the similarity (cohesion) of a data point to its cluster relative to other clusters (separation). Silhouette plots rely on a distance metric, e.g., the Euclidean distance, Manhattan distance, Minkowski distance, etc.
Suppose a clustering method groups all data points (objects), \(\{X_i\}_i\), into \(k\) clusters and define:
Then, the silhouette of \(X_i\) is defined by:
\[-1 \leq s_i = \frac{l_i - d_i}{\max\{l_i, d_i\}} \equiv \begin{cases} 1-\frac{d_i}{l_i}, & \mbox{if } d_i < l_i \\ 0, & \mbox{if } d_i = l_i \\ \frac{l_i}{d_i}-1, & \mbox{if } d_i > l_i \\ \end{cases} \leq 1\]
Note that:
The K-means algorithm is one of the most commonly used algorithms for clustering.
This algorithm is similar to k-nearest neighbors (KNN) presented in Chapter 6. In clustering, we don’t have a priori pre-determined labels, and the algorithm is trying to deduce intrinsic groupings in the data.
Similar to KNN, k-means uses Euclidean distance (\(|. |_2\) norm) most of the times, however Manhattan distance (\(|. |_1\) norm), or the more general Minkowski distance (\((\sum_{i=1}^n{|p_i - q_i|^c})^{\frac{1}{c}}\)) may also be used. For \(c=2\), the Minkowski distance represents the classical Euclidean distance: \[dist(x, y)=\sqrt{\sum_{n=1}^n(x_i-y_i)^2}.\]
How can we separate clusters using this formula? The k-means protocol is as follows:
Although there is no guarantee that the k-means algorithm converges to a global optimum, in practice, the algorithm tends to converge, i.e., the assignments no longer change, to a local minimum as there are only a finite number of such Voronoi partitionings, see the SOCR 2D Interactive Voronoi Tessellation App.
We don’t want our number of clusters to be either too large or too small. If it is too large, the groups are too specific to be meaningful. On the other hand, too few groups might be too broadly general to be useful. As we mentioned in Chapter 6, \(k=\sqrt{\frac{n}{2}}\) is a good place to start. However, it might generate a large number of groups.
Also, the elbow method may be used to determine the relationship of \(k\) and homogeneity of the observations within each cluster.
When we graph within-group homogeneity against \(k\), we can find an “elbow point” that suggests a minimum \(k\) corresponding to relatively large within-group homogeneity.
This graph shows that homogeneity barely increases above the “elbow point”. There are various ways to measure homogeneity within a cluster. Further detailed about these choices are provided in this paper On clustering validation techniques, Journal of Intelligent Information Systems Vol. 17, pp. 107-145, by M. Halkidi, Y. Batistakis, and M. Vazirgiannis (2001).
More generally, we can develop a new method drawElbowGraph()
to identify the elbow point and determine an appropriate value for the number of clusters \(k\).
Note: Recall that the projection of a point \(\vec{P}\) onto a line \(\vec{l}\) is defined as the vector \(\vec{Q}=\frac{\langle \vec{P} | \vec{l} \rangle }{\langle \vec{l} | \vec{l} \rangle }\vec{l}\). In the graph above the max-distance is the length \(||\vec{Q}||\) and \(\vec{Q} \perp \vec{l}\). However, since the scales of the horizontal and vertical axes are different, \(\vec{Q}\) appears to be a vertical line (it’s not!) and it represents the max-distance from the blue curve to the reference orange line.
The dataset we will be using is the Divorce and Consequences on Young Adults dataset. This is a longitudinal study focused on examining the consequences of recent parental divorce for young adults (initially ages 18-23) whose parents had divorced within 15 months of the study’s first wave (1990-91). The sample consisted of 257 White respondents with newly divorced parents. Here we have a subset of this dataset with 47 respondents in our case-studies folder, CaseStudy01_Divorce_YoungAdults_Data.csv.
Let’s load the dataset and pull out a summary of all variables.
<-read.csv("https://umich.instructure.com/files/399118/download?download_frd=1")
divorcesummary(divorce)
## DIVYEAR momint dadint momclose
## Min. :89.00 Min. :1.000 Min. :1.000 Min. :1.000
## 1st Qu.:89.00 1st Qu.:1.000 1st Qu.:2.000 1st Qu.:1.000
## Median :90.00 Median :1.000 Median :2.000 Median :2.000
## Mean :89.68 Mean :1.809 Mean :2.489 Mean :1.809
## 3rd Qu.:90.00 3rd Qu.:3.000 3rd Qu.:3.000 3rd Qu.:2.000
## Max. :90.00 Max. :4.000 Max. :4.000 Max. :4.000
## depression livewithmom gethitched
## Min. :1.000 Min. :1.000 Min. :1.000
## 1st Qu.:2.000 1st Qu.:1.000 1st Qu.:2.000
## Median :3.000 Median :1.000 Median :2.000
## Mean :2.851 Mean :1.489 Mean :2.213
## 3rd Qu.:4.000 3rd Qu.:2.000 3rd Qu.:2.000
## Max. :4.000 Max. :9.000 Max. :8.000
According to the summary, DIVYEAR is actually a dummy variable (either 89 or 90). We can re-code (binarize) the DIVYEAR using the ifelse()
function (mentioned in Chapter 7). The following line of code generates a new indicator variable for divorce year=1990.
$DIVYEAR<-ifelse(divorce$DIVYEAR==89, 0, 1) divorce
We also need another preprocessing step to deal with livewithmom
, which has missing values, livewithmom=9
. We can impute these using momint
and dadint
variables for each specific participant.
table(divorce$livewithmom)
##
## 1 2 9
## 31 15 1
$livewithmom==9, ] divorce[divorce
## DIVYEAR momint dadint momclose depression livewithmom gethitched
## 45 1 3 1 3 3 9 2
For instance, respondents that feel much closer to their dads may be assigned divorce$livewithmom==2
, suggesting they most likely live with their fathers. Of course, alternative imputation strategies are also possible.
45, 6]<-2
divorce[45, ] divorce[
## DIVYEAR momint dadint momclose depression livewithmom gethitched
## 45 1 3 1 3 3 2 2
We are only using R base functionality, so no need to install any additional packages now, library(stats)
may be necessary. Then, the function kmeans()
will provide the k-means clustering of the data.
myclusters<-kmeans(mydata, k)
The output consists of:
Before we perform clustering, we need to standardize the features to avoid biasing the clustering based on features that use large-scale values. Note that distance calculations are sensitive to measuring units. as.data.frame()
will convert our dataset into a data frame allowing us to use the lapply()
function. Next, we use a combination of lapply()
and scale()
to standardize our data.
<- as.data.frame(lapply(divorce, scale))
di_zstr(di_z)
## 'data.frame': 47 obs. of 7 variables:
## $ DIVYEAR : num 0.677 0.677 -1.445 0.677 -1.445 ...
## $ momint : num 1.258 1.258 -0.854 1.258 -0.854 ...
## $ dadint : num -0.514 -0.514 0.536 1.586 0.536 ...
## $ momclose : num 0.225 1.401 -0.951 1.401 0.225 ...
## $ depression : num 0.164 -0.937 1.265 0.164 -2.038 ...
## $ livewithmom: num -0.711 1.377 -0.711 -0.711 -0.711 ...
## $ gethitched : num 0.846 -0.229 -0.229 0.846 -0.229 ...
The resulting dataset, di_z
, is standardized so all features are unitless and follow approximately standardized normal distribution.
Next, we need to think about selecting a proper \(k\). We have a relatively small dataset with 47 observations. Obviously we cannot have a \(k\) as large as 10. The rule of thumb suggests \(k=\sqrt{47/2}=4.8\). This would be relatively large also because we will have less than 10 observations for each cluster. It is very likely that for some clusters we only have one observation. A better choice may be 3. Let’s see if this will work.
library(stats)
set.seed(321)
<-kmeans(di_z, 3) diz_clussters
Let’s look at the clusters created by the k-means model.
$size diz_clussters
## [1] 15 19 13
At first glance, it seems that 3 worked well for the number of clusters. We don’t have any cluster that contains a small number of observations. The three clusters have relatively equal number of respondents.
Silhouette plots represent the most appropriate evaluation strategy to assess the quality of the clustering. Silhouette values are between -1 and 1. In our case, two data points correspond to a negative Silhouette values, suggesting these cases may be “mis-clustered”, or perhaps are ambiguous as the Silhouette value is close to 0. We can observe that the average Silhouette is reasonable, about \(0.2\).
require(cluster)
= dist(di_z)
dis = silhouette(diz_clussters$cluster, dis)
sil summary(sil)
## Silhouette of 47 units in 3 clusters from silhouette.default(x = diz_clussters$cluster, dist = dis) :
## Cluster sizes and average silhouette widths:
## 15 19 13
## 0.1026558 0.2381074 0.1216357
## Individual silhouette widths:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -0.04724 0.08985 0.15871 0.16266 0.23772 0.38138
plot(sil, col=c(1:length(diz_clussters$size)))
::fviz_silhouette(sil, label=T, palette = "jco", ggtheme = theme_classic()) factoextra
## cluster size ave.sil.width
## 1 1 15 0.10
## 2 2 19 0.24
## 3 3 13 0.12
The next step would be to interpret the clusters in the context of this social study.
$centers diz_clussters
## DIVYEAR momint dadint momclose depression livewithmom
## 1 0.5358437 1.1170605 -0.30375217 1.0089641 0.01717647 0.4027512
## 2 -0.2162704 -0.4645881 0.03879188 -0.6411903 0.74335501 -0.4909699
## 3 -0.3021936 -0.6099026 0.29378745 -0.2270650 -1.10626095 0.2528585
## gethitched
## 1 0.27271371
## 2 -0.17199968
## 3 -0.06328552
This result shows:
Cluster 1: divyear=mostly 90, momint=very close, dadint=not close, livewithmom=mostly mother, depression=not often, (gethiched) marry=will likely not get married. Cluster 1 represents mostly adolescents that are closer to mom than dad. These young adults do not often feel depressed and they may avoid getting married. These young adults tends to be not be too emotional and do not value family.
Cluster 2: divyear=mostly 89, momint=not close, dadint=very close, livewithmom=father, depression=mild, marry=do not know/not inclined. Cluster 2 includes children that mostly live with dad and only feel close to dad. These people don’t felt severely depressed and are not inclined to marry. These young adults may prefer freedom and tend to be more naive.
Cluster 3: divyear=mix of 89 and 90, momint=not close, dadint=not at all, livewithmom=mother, depression=sometimes, marry=tend to get married. Cluster 3 contains children that did not feel close to either dad or mom. They sometimes felt depressed and are willing to build their own family. These young adults seem to be more independent.
We can see that these three different clusters do contain three alternative types of young adults.
Bar plots provide an alternative strategy to visualize the difference between clusters.
# par(mfrow=c(1, 1), mar=c(4, 4, 4, 2))
# myColors <- c("darkblue", "red", "green", "brown", "pink", "purple", "yellow")
# barplot(t(diz_clussters$centers), beside = TRUE, xlab="cluster",
# ylab="value", col = myColors)
# legend("top", ncol=2, legend = c("DIVYEAR", "momint", "dadint", "momclose", "depression", "livewithmom", "gethitched"), fill = myColors)
<- as.data.frame(t(diz_clussters$centers))
df <- rownames(df)
rowNames colnames(df) <- paste0("Cluster",c(1:3))
plot_ly(df, x = rownames(df), y = ~Cluster1, type = 'bar', name = 'Cluster1') %>%
add_trace(y = ~Cluster2, name = 'Cluster2') %>%
add_trace(y = ~Cluster3, name = 'Cluster3') %>%
layout(title="Explicating Derived Cluster Labels",
yaxis = list(title = 'Cluster Centers'), barmode = 'group')
For each of the three clusters, the bars in the plot above represent the following order of features DIVYEAR, momint, dadint, momclose, depression, livewithmom, gethitched
.
Clustering results could be utilized as new information augmenting the original dataset. For instance, we can add a cluster label in our divorce
dataset:
$clusters<-diz_clussters$cluster
divorce1:5, ] divorce[
## DIVYEAR momint dadint momclose depression livewithmom gethitched clusters
## 1 1 3 2 2 3 1 3 1
## 2 1 3 2 3 2 2 2 1
## 3 0 1 3 1 4 1 2 2
## 4 1 3 4 3 3 1 3 1
## 5 0 1 3 2 1 1 2 3
We can also examine the relationship between live with mom and feel close to mom by displaying a scatter plot of these two variables. If we suspect that young adults’ personality might affect this relationship, then we could consider the potential personality (cluster type) in the plot. The cluster labels associated with each participant are printed in different positions relative to each pair of observations, (livewithmom, momint)
.
# require(ggplot2)
# ggplot(divorce, aes(livewithmom, momint), main="Scatterplot Live with mom vs feel close to mom") +
# geom_point(aes(colour = factor(clusters), shape=factor(clusters), stroke = 8), alpha=1) +
# theme_bw(base_size=25) +
# geom_text(aes(label=ifelse(clusters%in%1, as.character(clusters), ''), hjust=2, vjust=2, colour = factor(clusters)))+
# geom_text(aes(label=ifelse(clusters%in%2, as.character(clusters), ''), hjust=-2, vjust=2, colour = factor(clusters)))+
# geom_text(aes(label=ifelse(clusters%in%3, as.character(clusters), ''), hjust=2, vjust=-1, colour = factor(clusters))) +
# guides(colour = guide_legend(override.aes = list(size=8))) +
# theme(legend.position="top")
<- paste0("Cluster ", divorce$clusters)
clusterNames plot_ly(data = divorce, x = ~livewithmom, y = ~momint, type="scatter", mode="markers",
color = ~clusters, marker = list(size = 30), name=clusterNames) %>%
hide_colorbar()
We can either use plot_ly()
, as we showed above, or use the ggplot2::ggplot()
function to label points with cluster types. In plot_ly
, we use name and color to stratify the clusters, whereas using ggplot(divorce, aes(livewithmom, momint))+geom_point()
uses aesthetics (aes
) to draw the scatterplot where the geom_text()
function help us label the points with their corresponding cluster identifiers.
This plot shows that live with mom does not necessarily mean young adults will feel close to mom. For “emotional” (cluster 1) young adults, they felt close to their mom whether they live with their mom or not. “Naive” (cluster 2) young adults feel closer to mom if they live with mom. However, they tend to be estranged from their mother. “Independent” (cluster 3) young adults are opposite to cluster 1. They felt closer to mom if they don’t live with her.
Let’s still use the divorce data to illustrate a model improvement using k-means++.
(Appropriate) initialization of the k-means algorithm is of paramount importance. The k-means++ extension provides a practical strategy to obtain an optimal initialization for k-means clustering using a predefined kpp_init
method.
# install.packages("matrixStats")
library(matrixStats)
= function(dat, K) {
kpp_init = as.matrix(dat)
x = nrow(x)
n # Randomly choose a first center
= matrix(NA, nrow=K, ncol=ncol(x))
centers set.seed(123)
1,] = as.matrix(x[sample(1:n, 1),])
centers[for (k in 2:K) {
# Calculate dist^2 to closest center for each point
= matrix(NA, nrow=n, ncol=k-1)
dists for (j in 1:(k-1)) {
= sweep(x, 2, centers[j,], '-')
temp = rowSums(temp^2)
dists[,j]
}= rowMins(dists)
dists # Draw next center with probability proportional to dist^2
= cumsum(dists)
cumdists = runif(1, min=0, max=cumdists[n])
prop = as.matrix(x[min(which(cumdists > prop)),])
centers[k,]
}return(centers)
}
= kmeans(di_z, kpp_init(di_z, 3), iter.max=100, algorithm='Lloyd') clust_kpp
We can observe some differences.
$centers clust_kpp
## DIVYEAR momint dadint momclose depression livewithmom
## 1 0.5446866 1.0598785 -0.31687382 0.9599752 0.095153756 0.33315813
## 2 0.6773305 -0.6672239 0.04204182 -0.7431116 -0.095067644 -0.09668118
## 3 -1.4449717 -0.4010893 0.31109072 -0.1947646 0.006692132 -0.26335357
## gethitched
## 1 0.2413859
## 2 -0.1021668
## 3 -0.1518099
This improvement is not substantial - the new overall average Silhouette value remains \(0.2\) for k-means++, compared with the value of \(0.2\) reported for the earlier k-means clustering, albeit the 3 groups generated by each method are quite distinct. In addition, the number of “mis-clustered” instances remains 2 although their Silhouette values are rather smaller than before and the overall cluster 1 Silhouette average value is low (\(0.006\)).
= silhouette(clust_kpp$cluster, dis)
sil2 summary(sil2)
## Silhouette of 47 units in 3 clusters from silhouette.default(x = clust_kpp$cluster, dist = dis) :
## Cluster sizes and average silhouette widths:
## 16 17 14
## 0.0726969 0.2708308 0.1907326
## Individual silhouette widths:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -0.1757 0.1173 0.1975 0.1795 0.2593 0.3698
plot(sil2, col=1:length(diz_clussters$size), border=NA)
Similar to what we performed for KNN and SVM, we can tune the k-means parameters, including centers initialization and \(k\).
<- 21
n_rows = matrix(0,nrow = n_rows)
mat for (i in 2:n_rows){
set.seed(321)
= kmeans(di_z, kpp_init(di_z, i), iter.max=100, algorithm='Lloyd')
clust_kpp = silhouette(clust_kpp$cluster, dis)
sil = mean(as.matrix(sil)[,3])
mat[i]
}colnames(mat) <- c("Avg_Silhouette_Value")
mat
## Avg_Silhouette_Value
## [1,] 0.0000000
## [2,] 0.2128452
## [3,] 0.1795219
## [4,] 0.2001579
## [5,] 0.1780246
## [6,] 0.1886250
## [7,] 0.1628551
## [8,] 0.2101592
## [9,] 0.1815201
## [10,] 0.1938268
## [11,] 0.1822460
## [12,] 0.1865835
## [13,] 0.2131691
## [14,] 0.1475313
## [15,] 0.1172894
## [16,] 0.1143476
## [17,] 0.1059846
## [18,] 0.0982532
## [19,] 0.1363817
## [20,] 0.1552494
## [21,] 0.1699629
# ggplot(data.frame(k=2:n_rows,sil=mat[2:n_rows]),aes(x=k,y=sil))+
# geom_line()+
# scale_x_continuous(breaks = 2:n_rows)
<- data.frame(k=2:n_rows,sil=mat[2:n_rows])
df plot_ly(df, x = ~k, y = ~sil, type = 'scatter', mode = 'lines', name='Silhouette') %>%
layout(title="Average Silhouette Graph")
This suggests that \(k\sim 3\) may be an appropriate number of clusters to use in this case.
Next, let’s set the maximal iteration of the algorithm and rerun the model with optimal k=2
, k=3
or k=10
. Below, we just demonstrate the results for \(k=3\). There are still 2 mis-clustered observations, which is not a significant improvement on the prior model according to the average Silhouette measure.
<- 3
k set.seed(31)
= kmeans(di_z, kpp_init(di_z, k), iter.max=200, algorithm="MacQueen")
clust_kpp = silhouette(clust_kpp$cluster, dis)
sil3 summary(sil3)
## Silhouette of 47 units in 3 clusters from silhouette.default(x = clust_kpp$cluster, dist = dis) :
## Cluster sizes and average silhouette widths:
## 16 17 14
## 0.0726969 0.2708308 0.1907326
## Individual silhouette widths:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -0.1757 0.1173 0.1975 0.1795 0.2593 0.3698
plot(sil3, col=1:length(clust_kpp$size))
Note that we now see 3 cases of group 1 that have negative silhouette values (previously we had only 2), albeit the overall average silhouette remains \(0.2\).
Let’s go through another example demonstrating the k-means clustering method using a larger dataset.
The dataset we will interrogate now includes Services Utilization by Trauma-Exposed Children in the US data, which is located in our case-studies folder. This case study examines associations between post-traumatic psychopathology and service utilization by trauma-exposed children.
Variables:
Case_04_ChildTrauma._Data.csv
) are tab-delimited.First, we need to load the dataset into R and report its summary and dimensions.
<-read.csv("https://umich.instructure.com/files/399129/download?download_frd=1", sep = " ")
traumasummary(trauma); dim(trauma)
## id sex age ses
## Min. : 1.0 Min. :0.000 Min. : 2.000 Min. :0.00
## 1st Qu.: 250.8 1st Qu.:0.000 1st Qu.: 7.000 1st Qu.:0.00
## Median : 500.5 Median :1.000 Median : 9.000 Median :0.00
## Mean : 500.5 Mean :0.506 Mean : 8.982 Mean :0.18
## 3rd Qu.: 750.2 3rd Qu.:1.000 3rd Qu.:11.000 3rd Qu.:0.00
## Max. :1000.0 Max. :1.000 Max. :25.000 Max. :1.00
## race traumatype ptsd dissoc
## Length:1000 Length:1000 Min. :0.00 Min. :0.000
## Class :character Class :character 1st Qu.:0.00 1st Qu.:0.000
## Mode :character Mode :character Median :0.00 Median :1.000
## Mean :0.29 Mean :0.598
## 3rd Qu.:1.00 3rd Qu.:1.000
## Max. :1.00 Max. :1.000
## service
## Min. : 0.000
## 1st Qu.: 8.000
## Median :10.000
## Mean : 9.926
## 3rd Qu.:12.000
## Max. :20.000
## [1] 1000 9
In the summary we see two factors race
and traumatype
. Traumatype
codes the real classes we are interested in. If the clusters created by the model are quite similar to the trauma types, our model may have a quite reasonable interpretation. Let’s also create a dummy variable for each racial category.
$black<-ifelse(trauma$race=="black", 1, 0)
trauma$hispanic<-ifelse(trauma$race=="hispanic", 1, 0)
trauma$other<-ifelse(trauma$race=="other", 1, 0)
trauma$white<-ifelse(trauma$race=="white", 1, 0) trauma
Then, we will remove the (outcome-type) class variable, traumatype
, from the dataset to avoid biasing the clustering algorithm. Thus, we are simulating a real biomedical case-study where we do not necessarily have the actual class information available, i.e., classes are latent features.
<-trauma[, -c(1, 5, 6)] trauma_notype
Similar to case-study 1, let’s standardize the dataset and fit a k-means model.
<- as.data.frame(lapply(trauma_notype, scale))
tr_zstr(tr_z)
## 'data.frame': 1000 obs. of 10 variables:
## $ sex : num 0.988 0.988 -1.012 -1.012 0.988 ...
## $ age : num -0.997 1.677 -0.997 0.674 -0.662 ...
## $ ses : num -0.468 -0.468 -0.468 -0.468 -0.468 ...
## $ ptsd : num 1.564 -0.639 -0.639 -0.639 1.564 ...
## $ dissoc : num 0.819 -1.219 0.819 0.819 0.819 ...
## $ service : num 2.314 0.678 -0.303 0.351 1.66 ...
## $ black : num 2 2 2 2 2 ...
## $ hispanic: num -0.333 -0.333 -0.333 -0.333 -0.333 ...
## $ other : num -0.333 -0.333 -0.333 -0.333 -0.333 ...
## $ white : num -1.22 -1.22 -1.22 -1.22 -1.22 ...
set.seed(1234)
<-kmeans(tr_z, 5) trauma_clusters
Here we use k=5 in the hope that we have similar 5 clusters that match the 5 trauma types. In this case study, we have 1,000 observations and k=5 may be a reasonable option.
To assess the clustering model results, we can examine the resulting clusters.
$centers trauma_clusters
## sex age ses ptsd dissoc service
## 1 -0.007257555 0.01868539 0.01874134 -0.63878185 0.04658691 0.015681123
## 2 0.047979449 -0.10426313 0.15609566 0.02202696 -0.09784989 -0.103376956
## 3 0.067970886 0.04611638 -0.07804783 0.04405392 -0.07746450 0.128894052
## 4 -0.001999144 0.06115434 -0.09105580 -0.07709436 0.02446247 0.001308569
## 5 -0.045688295 -0.08034509 0.01403107 1.56391419 -0.03944230 -0.052982344
## black hispanic other white
## 1 -0.4997499 -0.3331666 -0.3331666 0.8160882
## 2 -0.4997499 2.9984996 -0.3331666 -1.2241323
## 3 -0.4997499 -0.3331666 2.9984996 -1.2241323
## 4 1.9989997 -0.3331666 -0.3331666 -1.2241323
## 5 -0.4997499 -0.3331666 -0.3331666 0.8160882
<- c("darkblue", "red", "green", "brown", "pink", "purple", "lightblue", "orange", "grey", "yellow")
myColors
# barplot(t(trauma_clusters$centers), beside = TRUE, xlab="cluster",
# ylab="value", col = myColors)
# legend("topleft", ncol=4, legend = c("sex", "age", "ses", "ptsd", "dissoc", "service", "black", "hispanic", "other", "white"), fill = myColors)
<- as.data.frame(t(trauma_clusters$centers))
df <- rownames(df)
rowNames colnames(df) <- paste0("Cluster",c(1:dim(trauma_clusters$centers)[1]))
plot_ly(df, x = rownames(df), y = ~Cluster1, type = 'bar', name = 'Cluster1') %>%
add_trace(y = ~Cluster2, name = 'Cluster2') %>%
add_trace(y = ~Cluster3, name = 'Cluster3') %>%
add_trace(y = ~Cluster4, name = 'Cluster4') %>%
add_trace(y = ~Cluster5, name = 'Cluster5') %>%
layout(title="Explicating Derived Cluster Labels",
yaxis = list(title = 'Cluster Centers'), barmode = 'group')
On this barplot, the bars in each cluster represents sex, age, ses, ptsd, dissoc, service, black, hispanic, other,
and white
, respectively. It is quite obvious that each cluster has some unique features.
Next, we can compare the k-means computed cluster labels to the original labels. Let’s evaluate the similarities between the automated cluster labels and their real class counterparts using a confusion matrix table, where rows represent the k-means clusters, columns show the actual labels, and the cell values include the frequencies of the corresponding pairings.
$clusters<-trauma_clusters$cluster
traumatable(trauma$clusters, trauma$traumatype)
##
## dvexp neglect physabuse psychabuse sexabuse
## 1 36 243 0 143 0
## 2 100 0 0 0 0
## 3 100 0 0 0 0
## 4 0 0 100 0 100
## 5 14 107 0 57 0
We can see that all of the children in cluster 4 belongs to dvexp
(exposure to domestic violence or intimate partner violence). The model groups all physabuse
and sexabuse
cases into cluster1 but can;t distinguish between them. Majority (200/250) of all dvexp
children are grouped in clusters 4 and 5. Finally, neglect
and psychabuse
types are mixed in clusters 2 and 3.
Let’s review the output Silhouette value summary. It works well as only a small portion of samples appear mis-clustered.
= dist(tr_z)
dis_tra = silhouette(trauma_clusters$cluster, dis_tra)
sil_tra summary(sil_tra)
## Silhouette of 1000 units in 5 clusters from silhouette.default(x = trauma_clusters$cluster, dist = dis_tra) :
## Cluster sizes and average silhouette widths:
## 422 100 100 200 178
## 0.2166778 0.3353976 0.3373487 0.2836607 0.1898492
## Individual silhouette widths:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.03672 0.19967 0.23675 0.24924 0.30100 0.41339
windows(width=7, height=7)
plot(sil_tra, col=1:length(trauma_clusters$centers[ ,1]), border=NA)
# report the overall mean silhouette value
mean(sil_tra[,"sil_width"])
## [1] 0.249238
# The sil object colnames are ("cluster", "neighbor", "sil_width")
Next, let’s try to tune \(k\) with k-means++ and see if \(k=5\) appears to be optimal.
= matrix(0,nrow = 11)
mat for (i in 2:11){
set.seed(321)
= kmeans(tr_z, kpp_init(tr_z, i), iter.max=100, algorithm='Lloyd')
clust_kpp = silhouette(clust_kpp$cluster, dis_tra)
sil = mean(as.matrix(sil)[,3])
mat[i]
} mat
## [,1]
## [1,] 0.0000000
## [2,] 0.2181421
## [3,] 0.1948499
## [4,] 0.2277780
## [5,] 0.2178744
## [6,] 0.2645193
## [7,] 0.2494296
## [8,] 0.2465316
## [9,] 0.2316334
## [10,] 0.2358937
## [11,] 0.2374859
# ggplot(data.frame(k=2:11,sil=mat[2:11]),aes(x=k,y=sil))+geom_line()+scale_x_continuous(breaks = 2:11)
<- data.frame(data.frame(k=2:11,sil=mat[2:11]))
df plot_ly(df, x = ~k, y = ~sil, type = 'scatter', mode = 'lines', name='Silhouette') %>%
layout(title="Average Silhouette Graph")
Finally, let’s use k-means++ with \(k=6\) and set the algorithm’s maximal iteration before rerunning the experiment:
set.seed(1234)
= kmeans(tr_z, kpp_init(tr_z, 6), iter.max=100, algorithm='Lloyd')
clust_kpp = silhouette(clust_kpp$cluster, dis_tra)
sil summary(sil)
## Silhouette of 1000 units in 6 clusters from silhouette.default(x = clust_kpp$cluster, dist = dis_tra) :
## Cluster sizes and average silhouette widths:
## 112 100 488 85 15 200
## 0.2552564 0.3321270 0.2485199 0.2478090 0.2294502 0.2846731
## Individual silhouette widths:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.07259 0.22965 0.26352 0.26452 0.29830 0.41173
# plot(sil)
# report the overall mean silhouette value
mean(sil[,"sil_width"])
## [1] 0.2645193
As we showed earlier, we can interpret the resulting kmeans
clusters in the context of this pediatric trauma study, by examining clust_kpp$centers
.
A very active area of research involves feature selection for unsupervised machine-learning clustering, including k-means clustering. We won’t go into details here, but we list some of the current strategies to chose salient features in situations where we don’t have ground-truth labels.
Use Boys Town Study of Youth Development data, second case study, CaseStudy02_Boystown_Data.csv, we used in Chapter 6, to find clusters using variables about GPA, alcohol abuse, attitudes on drinking, social status, parent closeness and delinquency for clustering(all variables other than gender and ID).
First we must load the data and transfer sex
, dadjob
and momjob
into dummy variables.
<-read.csv("https://umich.instructure.com/files/399119/download?download_frd=1", sep=" ")
boystown$sex<-boystown$sex-1
boystown$dadjob <- (-1)*(boystown$dadjob-2)
boystown$momjob <- (-1)*(boystown$momjob-2)
boystownstr(boystown)
## 'data.frame': 200 obs. of 11 variables:
## $ id : int 1 2 3 4 5 6 7 8 9 10 ...
## $ sex : num 0 0 0 0 1 1 0 0 1 1 ...
## $ gpa : int 5 0 3 2 3 3 1 5 1 3 ...
## $ Alcoholuse: int 2 4 2 2 6 3 2 6 5 2 ...
## $ alcatt : int 3 2 3 1 2 0 0 3 0 1 ...
## $ dadjob : num 1 1 1 1 1 1 1 1 1 1 ...
## $ momjob : num 0 0 0 0 1 0 0 0 1 1 ...
## $ dadclose : int 1 3 2 1 2 1 3 6 3 1 ...
## $ momclose : int 1 4 2 2 1 2 1 2 3 2 ...
## $ larceny : int 1 0 0 3 1 0 0 0 1 1 ...
## $ vandalism : int 3 0 2 2 2 0 5 1 4 0 ...
Then, extract all the variables, except the first two columns (subject identifiers and genders).
<-boystown[, -c(1, 2)] boystown_sub
Next, we need to standardize and clustering the data with k=3
. You may have the following centers (numbers could be a little different).
## gpa Alcoholuse alcatt dadjob momjob dadclose
## 1 -0.25418298 0.3762937 0.08863939 -0.25162083 -0.6066413 -0.411399321
## 2 0.27522795 -0.2325476 -0.02120468 0.19395772 -0.6066413 0.427700087
## 3 -0.01864578 -0.2055983 -0.09319588 0.08620343 1.6401784 -0.006497343
## momclose larceny vandalism
## 1 -0.54855252 -0.44754196 0.38327653
## 2 0.52304283 0.46972375 -0.35966892
## 3 0.05432967 -0.01300009 -0.04567224
Add k-means cluster labels as a new (last) column back in the original dataset.
To investigate the gender distribution within different clusters we may use aggregate()
.
# Compute the averages for the variable 'sex', grouped by cluster
aggregate(data=boystown, sex~clusters, mean)
## clusters sex
## 1 1 0.6216216
## 2 2 0.6527778
## 3 3 0.6481481
Here clusters
is the new vector indicating cluster labels. The gender distribution does not vary much between different cluster labels.
Recall from Chapter 6 (Lazy Learning) that there are three large classes of unsupervised clustering methods - Bayesian, partitioning-based, and hierarchical. Hierarchical clustering represents a family of techniques that build hierarchies of clusters using one of two complementary strategies:
In both situations, cluster splits and merges are determined by minimizing some objective function using a greedy algorithm (e.g., gradient descent). It’s common to illustrate hierarchical clustering results as dendrograms. One example of genomics data hierarchical clustering using probability distributions is available here (DOI: 10.1016/j.jtbi.2016.07.032).
Decisions about merging or splitting nodes in the hierarchy heavily depend the specific a distance metric used to measure the dissimilarity between sets of observations in the original cluster and the candidate children (sub)clusters. It’s common to employ standard metrics (\(d\)) for measuring distances between pairs of observations (e.g., Euclidean, Manhattan, Mahalanobis) and a linkage criterion connecting cluster-dissimilarity of sets to the paired distances of observations in the cluster sets (e.g., maximum/complete linkage clustering \(\max \{ d ( a , b ) : a \in A , b \in B \}\), minimum/single linkage clustering \(\min \{ d ( a , b ) : a \in A , b \in B \}\), mean linkage clustering \(\frac {1}{|A|.|B|} \sum_{a\in A} {\sum _{b\in B}d(a,b)}\)).
There are a number of R
hierarchical clustering packages, including:
hclust
in base R.agnes
in the cluster
package.Alternative distance measures (or linkages) can be used in all Hierarchical Clustering, e.g., single, complete and ward.
We will demonstrate hierarchical clustering using case-study 1 (Divorce and Consequences on Young Adults). Pre-set \(k=3\) and notice that we have to use normalized data for hierarchical clustering.
library(cluster)
= agnes(di_z, diss=FALSE, method='single')
divorce_sing = agnes(di_z, diss=FALSE, method='complete')
divorce_comp = agnes(di_z, diss=FALSE, method='ward')
divorce_ward = silhouette(cutree(divorce_sing, k=3), dis)
sil_sing = silhouette(cutree(divorce_comp, k=3), dis)
sil_comp # try 10 clusters, see plot above
= silhouette(cutree(divorce_ward, k=10), dis) sil_ward
You can generate the hierarchical plot by ggdendrogram
in the package ggdendro
.
# install.packages("ggdendro")
library(ggdendro)
ggdendrogram(as.dendrogram(divorce_ward), leaf_labels=FALSE, labels=FALSE)
mean(sil_ward[,"sil_width"])
## [1] 0.2398738
ggdendrogram(as.dendrogram(divorce_ward), leaf_labels=TRUE, labels=T, size=10)
library(data.tree)
<- as.hclust(divorce_ward)
DD_hcclust <- as.dendrogram(divorce_ward)
DD
# Dendogram --> Graph(Nodes)
<- data.tree::as.Node(DD)
DD_Node
$attributesAll DD_Node
## [1] "members" "midpoint" "plotHeight" "leaf" "value"
$totalCount DD_Node
## [1] 93
$leafCount DD_Node
## [1] 47
$height DD_Node
## [1] 9
# Get nodes, labels, values, IDs
<- DD_Node$Get("name")
IDs = DD_Node$Get("name")
labels = DD_Node$Get(function(x) x$parent$name)
parents = as.numeric(DD_Node$Get("name")) values
## Warning: NAs introduced by coercion
<- as.data.frame(cbind(labels=labels, parents=parents, values=values))
df
# remove node self-loops
<- subset(df, as.character(labels) != as.character(parents))
df1
# remove duplicates
<- distinct(df1, labels, .keep_all= TRUE)
df2
plot_ly(df2, labels=~labels, parents=~parents, values=~values, type='sunburst')
plot_ly(df2, labels=~labels, parents=~parents, values=~values, type='treemap')
Generally speaking, the best result should come from wald linkage, but you should also try complete linkage (method=‘complete’). We can see that the hierarchical clustering result (average silhouette value \(\sim 0.24\)) mostly agrees with the prior k-means (\(0.2\)) and k-means++ (\(0.2\)) results.
summary(sil_ward)
## Silhouette of 47 units in 10 clusters from silhouette.default(x = cutree(divorce_ward, k = 10), dist = dis) :
## Cluster sizes and average silhouette widths:
## 4 5 6 3 6 12
## 0.25905454 0.29195989 0.29305926 -0.02079056 0.19263836 0.26268274
## 5 2 3 1
## 0.32594365 0.44074717 0.08760990 0.00000000
## Individual silhouette widths:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -0.1477 0.1231 0.2577 0.2399 0.3524 0.5176
plot(sil_ward, col=1:length(unique(sil_ward[,1])))
Spectral clustering relies on decomposition of the similarity-matrix in terms of its spectrum of eigenvalues. The similarity matrix of the data is computed using some pairwise distances between all observations in the dataset. This spectral decomposition is used to reduce the data dimensionality prior to clustering. Typically, one precomputes the distance matrix first and feeds it as an input to the clustering method.
For a dataset of records, the similarity matrix is a symmetric matrix \(A=\{a_{ij}\geq 0\}_{ij}\) encoding the similarity measures between pairs of data points indexed by \(1\leq i,j \leq n\). Most spectral clustering methods employ a traditional cluster method like \(k\)-means clustering applied on the eigenvectors of the Laplacian similarity matrix. There are alternative approaches to define a Laplacian that lead to different mathematical interpretations of the spectral clustering protocol. The relevant eigenvectors correspond to the few smallest eigenvalues of the Laplacian. The exception is that the smallest eigenvalue, which will have a value of \(0\). This process (finding the smallest eigenvalues) is analogous to computing the largest few eigenvalues of an operator representing a function of the original Laplacian.
The underlying philosophy of spectral clustering has roots in physics, e.g., partitioning of a mass-spring system. The analytical concept corresponding to physical mass is data point and mass-characteristics (e.g., stiffness parameter) relates to weights of edges describing pairwise similarity of related data points. The eigenvalue problem in spectral clustering analytics maps to physical transversal vibration modes of mass-spring systems. Mathematically, the eigenvalue problem for the Laplacian matrix is \(L=D-A\), where \(D=\{ d_{i,i} = \sum_j a_{i,j};\ d_{i\not= j}=0 \}\) is a diagonal matrix.
Tightly coupled spring masses in the physical system jointly move in space from the equilibrium state in low-frequency vibration modes. Eigenvector components that correspond to the smallest eigenvalues of the Laplacian can be used to derive clustering of the masses (data points).
For instance, the normalized cuts spectral clustering algorithm partitions points in \(B\) into two sets \(B_1\) and \(B_2\) based on the eigenvector \(v\) corresponding to the second-smallest Laplacian eigenvalue, where the symmetrized-and-normalized Laplacian matrix is defined by:
\[L^\text{norm} = I-\left (D^{-1/2} A D^{-1/2}\right ).\]
Similarly, we can take the eigenvector corresponding to the largest eigenvalue of the adjacency matrix
\[P = D^{-1}A.\]
The key is to obtain the spectrum of the Laplacian. Then using the eigenvectors, we can cluster the observations in many alternative ways. For instance, the cases can be partitioned by computing the median \(m\) of the components of the second smallest eigenvector \(v\) and mapping all points whose component in \(v\) is greater than \(m\) in \(B_1\) and the remaining cases in its complement, \(B_2\). Repeated partitioning of the data into the subsets using this protocol will induce a classification scheme (spectral clustering) of the data.
The unnormalized spectral clustering pseudo algorithm is listed below.
Input: Similarity matrix, \(A\in R^n\times R^n\), \(k=\) number of clusters Construct a similarity graph modeling the local neighborhood relationships, where the similarity function encodes mainly local neighborhoods. For instance, a Gaussian similarity function \(a(x_i,x_j)=\exp{\left (-\frac{||x_i-x_j||^2}{2\sigma^2}\right )}\), where \(\sigma\) controls the width of the neighborhoods. Let \(W\) be its weighted adjacency matrix, corresponding to the similarity graph, \(W= (w_{i,j})_{i,j}\), where \(w_{i,j}=w_{j,i}\) and \(w_{i,j}= 0\) implies that the vertices \(x_i\) and \(x_j\) are not connected. Compute the unnormalized Laplacian \(L\). Compute the first \(k\) eigenvectors of \(L\) and let \(V\in R^{n\times k}\) be the matrix containing these \(k\) vectors as columns. For \(1\leq i\leq n\), let \(y_i\in R^k\) be the vector corresponding to the \(i^{th}\) row of \(V\). Cluster the points \(\{y_i \}_{1\leq i\leq n}\) in \(k\)-clusters, \(\{C_i\}_{i=1}^k\) in \(R^k\) using \(k\)-means clustering. Output: Clusters \(\{A_i\}_{i=1}^k\), where \(A_i=\{j | y_i \in C_i\}\).
Let’s look at one specific implementation of spectral clustering for segmenting/classifying a region of interest (ROI) representing brain hematoma in a 2D MRI image (MRI_ImageHematoma.jpg).
# Import the Brain 2D image MRI_ImageHematoma.jpg
library(jpeg)
<- "https://umich.instructure.com/files/1627149/download?download_frd=1"
img_url <- tempfile(); download.file(img_url, img_file, mode="wb")
img_file <- readJPEG(img_file)
img
# To expedite the calculations, reduce the size of 2D image
# install.packages("BiocManager")
# BiocManager::install("EBImage")
library("EBImage")
##
## Attaching package: 'EBImage'
## The following object is masked from 'package:plotly':
##
## toRGB
<- t(apply(img[ , , 1], 2, rev)) # take the first RGB-color channel; transpose to get it anatomically correct Viz
img # width and height of the original image
dim(img)[1:2]
## [1] 256 256
<- c(dim(img)[1], dim(img)[2])
olddim <- c(64, 64) # new smaller image dimensions
newdim <- resize(img, w = newdim[1], h = newdim[2])
img1
# image(img, main="Original (high) resolution", xaxt = "n", yaxt = "n", asp=1)
# image(img1, main="Downsample (low) resolution)", xaxt = "n", yaxt = "n", asp=1)
plot_ly(z = ~img, type="surface")
# Convert image matrix to long vector (i,j, value)
<- matrix(NA, prod(dim(img1)),3)
imgvec <- 1
counter for (r in 1:nrow(img1)) {
for (c in 1:ncol(img1)) {
1] <- r
imgvec[counter,2] <- c
imgvec[counter,3] <- img1[r,c]
imgvec[counter,<- counter+1
counter
}
}
# Compute the Similarity Matrix A
<- 2
pixdiff <- 0.01
sigma2 <- matrix(0, counter-1, counter-1)
simmatrix
for(r in 1:nrow(imgvec)) {
# Verbose
# cat(r, "out of", nrow(imgvec), "\n")
<- ifelse(abs(imgvec[r,1]-imgvec[,1])<=pixdiff & abs(imgvec[r,2]-imgvec[,2])<=pixdiff,exp(-(imgvec[r,3]-imgvec[,3])^2/sigma2),0)
simmatrix[r,]
}
# Compute the graph Laplacians
# U: unnormalized graph Laplacian (U=D-A)
# L: normalized graph Laplacian, which can be computed in different ways:
## L1: Simple Laplacian: I - D^{-1} A, which can be seen as a random walk, where D^{-1} A is the transition matrix, which yields spectral clustering with groups of nodes such that the random walk seldom transitions from one group to another.
## L2: Normalized Laplacian D^{-1/2} A D^{-1/2}, or
## L3: Generalized Laplacian: D^{-1} A.
<- diag(rowSums(simmatrix))
D <- diag(1/rowSums(simmatrix))
Dinv <- diag(rep(1,nrow(simmatrix)))-Dinv %*% simmatrix
L <- D-simmatrix
U
# Compute the eigen-spectra for the normalized and unnormalized Laplacians
<- eigen(L, symmetric=TRUE)
evL <- eigen(U, symmetric=TRUE)
evU
# Apply k-means clustering on the eigenspectra of both Laplacians
<- kmeans(evL$vectors[,(ncol(simmatrix)-1):(ncol(simmatrix)-0)],
kmL centers=2,nstart=5)
<- matrix(kmL$cluster-1, newdim[1], newdim[2], byrow=T)
segmatL
<- kmeans(evU$vectors[,(ncol(simmatrix)-1):(ncol(simmatrix)-0)],
kmU centers=2,nstart=5)
<- matrix(kmU$cluster-1, newdim[1], newdim[2], byrow=T)
segmatU
<- rep(1, length(img))
colorL dim(colorL) <- dim(img)
plot_ly(x=~seq(0, 4, length.out=olddim[1]),
y=~seq(0, 4, length.out=olddim[2]), z=~segmatL,
surfacecolor=colorL, cauto=F, cmax=1, cmin=0,
name="L = Normalized graph Laplacian", type="surface") %>%
add_trace(x=~seq(0, 4, length.out=olddim[1]),
y=~seq(0, 4, length.out=olddim[2]), z=~segmatU*(1),
colorscale = list(c(0, 1), c("tan", "red")),
name="U = Unnormalized graph Laplacian", type="surface") %>%
add_trace(x = ~seq(0, 1, length.out=olddim[1]),
y = ~seq(0, 1, length.out=olddim[2]),
z = ~img/2, type="surface", name="Original Image", opacity=0.5) %>%
layout(xaxis=list(name="X"), xaxis=list(name="X"), title="Spectral Laplacian Classification") %>%
hide_colorbar()
# Plot the pair of spectral clusters (hematoma and normal brain areas)
image(segmatL, col=grey((0:15)/15), main="Normalized Laplacian", xaxt = "n", yaxt = "n", asp=1)
image(segmatU, col=grey((0:15)/15), main="Unnormalized Laplacian", xaxt = "n", yaxt = "n", asp=1)
# Overlay the outline of the ROI-segmentation region on top of original image
image(seq(0, 1, length.out=olddim[1]), seq(0, 1, length.out=olddim[2]),
col = grey((0:15)/15), xlab="",ylab="", asp=1, xaxt = "n", yaxt = "n",
img, main="Original MRI with Overlay of the Boundaries of the \n Unnormalized (red) and Normalized (green) Laplacian Labels")
# Compute the outline of the spectral segmentation and plot it as piece-wise polygon - line segments
<- segmatU
segmat <- "red"
linecol <- 3
linew for(r in 2:newdim[1]) {
for (c in 2:newdim[2]) {
if(abs(segmat[r-1,c]-segmat[r,c])>0) {
<- (r-1)/(newdim[1])
xloc <- (c-1)/(newdim[2])
ymin <- (c-0)/(newdim[2])
ymax segments(xloc, ymin, xloc, ymax, col=linecol,lwd=linew)
}if(abs(segmat[r,c-1]-segmat[r,c])>0) {
<- (c-1)/(newdim[2])
yloc <- (r-1)/(newdim[1])
xmin <- (r-0)/(newdim[1])
xmax segments(xmin, yloc, xmax, yloc, col=linecol,lwd=linew)
}
}
}
# Add the normalized Laplacian contour
<- segmatL
segmat <- "green"
linecol <- 3
linew for(r in 2:newdim[1]) {
for (c in 2:newdim[2]) {
if(abs(segmat[r-1,c]-segmat[r,c])>0) {
<- (r-1)/(newdim[1])
xloc <- (c-1)/(newdim[2])
ymin <- (c-0)/(newdim[2])
ymax segments(xloc, ymin, xloc, ymax, col=linecol,lwd=linew)
}if(abs(segmat[r,c-1]-segmat[r,c])>0) {
<- (c-1)/(newdim[2])
yloc <- (r-1)/(newdim[1])
xmin <- (r-0)/(newdim[1])
xmax segments(xmin, yloc, xmax, yloc, col=linecol,lwd=linew)
}
} }
Let’s try spectral clustering on the Knee Pain Dataset using the kernlab::specc()
method.
#Get the data first
library("XML"); library("xml2"); library("rvest")
<- read_html("https://wiki.socr.umich.edu/index.php/SOCR_Data_KneePainData_041409")
wiki_url html_nodes(wiki_url, "#content")
## {xml_nodeset (1)}
## [1] <div id="content" class="mw-body" role="main">\n\t\t\t<a id="top"></a>\n\ ...
<- html_table(html_nodes(wiki_url, "table")[[2]])
kneeRawData <-function(x){
normalizereturn((x-min(x))/(max(x)-min(x)))
}<- as.data.frame(cbind(normalize(kneeRawData$x), normalize(kneeRawData$Y), as.factor(kneeRawData$View)))
kneeRawData_df colnames(kneeRawData_df) <- c("X", "Y", "Label")
# randomize the rows of the DF as RF, RB, LF and LB labels of classes
# which are by default sequentially ordered
set.seed(1234)
<- kneeRawData_df[sample(nrow(kneeRawData_df)), ]
kneeRawData_df # summary(kneeRawData_df)
# View(kneeRawData_df)
# Artificially reduce the size of the data from 8K to 1K to get results faster
<- data.frame(x=kneeRawData_df[1:1000, 1],
kneeDF y=kneeRawData_df[1:1000, 2],
class=as.factor(kneeRawData_df[1:1000, 3]))
head(kneeDF)
## x y class
## 1 0.69096672 0.4479769 1
## 2 0.88431062 0.7716763 3
## 3 0.67828843 0.4393064 1
## 4 0.88589540 0.4421965 3
## 5 0.68621236 0.4739884 1
## 6 0.09350238 0.5664740 4
# Do the spectral clustering
library(kernlab)
<- cbind(kneeDF$x, kneeDF$y); dim(knee_data) knee_data
## [1] 1000 2
<- specc(knee_data, iterations=10, centers=4)
spectral_knee
# plot(knee_data, col=spectral_knee, pch=1) # estimated clusters
# points(knee_data, col=kneeDF$class, pch=0)
plot_ly(x = ~knee_data[,1], y = ~knee_data[,2], type = 'scatter',
mode = 'markers', symbol = ~unlist(spectral_knee@.Data),
symbols = c('circle','x','o', 'diamond'),
color = ~unlist(spectral_knee@.Data), marker = list(size = 10)) %>%
layout("Knee-pain data (L+R & F+B) with derived Spectal Color/Symbol Clustering Labels",
xaxis=list(title="X"), yaxis=list(title="Y")) %>%
hide_colorbar()
More details about Gaussian mixture models (GMM) are provided here. Also see the SOCR Gaussian Mixture Model (Java) interactive activity. Below is a brief introduction to GMM using the Mclust
function in the R package mclust
.
For multivariate mixture, there are totally 14 possible models:
For more practical details, you may refer to Mclust
and its vignettes. Additional theoretical details are available in C. Fraley and A. E. Raftery (2002). Model-based clustering, discriminant analysis, and density estimation. Journal of the American Statistical Association 97:611:631.
Let’s use the Divorce and Consequences on Young Adults dataset for a demonstration.
library(mclust)
set.seed(1234)
<- Mclust(di_z)
gmm_clust summary(gmm_clust, parameters = TRUE)
## ----------------------------------------------------
## Gaussian finite mixture model fitted by EM algorithm
## ----------------------------------------------------
##
## Mclust VEI (diagonal, equal shape) model with 3 components:
##
## log-likelihood n df BIC ICL
## -366.2421 47 32 -855.6889 -855.6889
##
## Clustering table:
## 1 2 3
## 16 11 20
##
## Mixing probabilities:
## 1 2 3
## 0.3404255 0.2340426 0.4255319
##
## Means:
## [,1] [,2] [,3]
## DIVYEAR -1.31232783 0.6773305 0.677330492
## momint -0.12774695 0.3940885 -0.114551109
## dadint 0.20799207 -0.6091287 0.168627126
## momclose -0.06879301 0.1182558 -0.010006256
## depression 0.16395724 -0.2363539 -0.001171123
## livewithmom -0.05830267 1.3770536 -0.710737338
## gethitched 0.17425492 -0.1308860 -0.067416656
##
## Variances:
## [,,1]
## DIVYEAR momint dadint momclose depression livewithmom
## DIVYEAR 0.08984375 0.0000 0.00000 0.00000 0.00000 0.0000000
## momint 0.00000000 15.9914 0.00000 0.00000 0.00000 0.0000000
## dadint 0.00000000 0.0000 14.23757 0.00000 0.00000 0.0000000
## momclose 0.00000000 0.0000 0.00000 19.30599 0.00000 0.0000000
## depression 0.00000000 0.0000 0.00000 0.00000 12.66066 0.0000000
## livewithmom 0.00000000 0.0000 0.00000 0.00000 0.00000 0.3188004
## gethitched 0.00000000 0.0000 0.00000 0.00000 0.00000 0.0000000
## gethitched
## DIVYEAR 0.000000
## momint 0.000000
## dadint 0.000000
## momclose 0.000000
## depression 0.000000
## livewithmom 0.000000
## gethitched 2.988846
## [,,2]
## DIVYEAR momint dadint momclose depression livewithmom
## DIVYEAR 0.003245073 0.0000000 0.0000000 0.0000000 0.0000000 0.00000000
## momint 0.000000000 0.5775947 0.0000000 0.0000000 0.0000000 0.00000000
## dadint 0.000000000 0.0000000 0.5142479 0.0000000 0.0000000 0.00000000
## momclose 0.000000000 0.0000000 0.0000000 0.6973146 0.0000000 0.00000000
## depression 0.000000000 0.0000000 0.0000000 0.0000000 0.4572912 0.00000000
## livewithmom 0.000000000 0.0000000 0.0000000 0.0000000 0.0000000 0.01151478
## gethitched 0.000000000 0.0000000 0.0000000 0.0000000 0.0000000 0.00000000
## gethitched
## DIVYEAR 0.0000000
## momint 0.0000000
## dadint 0.0000000
## momclose 0.0000000
## depression 0.0000000
## livewithmom 0.0000000
## gethitched 0.1079543
## [,,3]
## DIVYEAR momint dadint momclose depression livewithmom
## DIVYEAR 0.003765412 0.0000000 0.0000000 0.000000 0.0000000 0.00000000
## momint 0.000000000 0.6702105 0.0000000 0.000000 0.0000000 0.00000000
## dadint 0.000000000 0.0000000 0.5967061 0.000000 0.0000000 0.00000000
## momclose 0.000000000 0.0000000 0.0000000 0.809127 0.0000000 0.00000000
## depression 0.000000000 0.0000000 0.0000000 0.000000 0.5306166 0.00000000
## livewithmom 0.000000000 0.0000000 0.0000000 0.000000 0.0000000 0.01336114
## gethitched 0.000000000 0.0000000 0.0000000 0.000000 0.0000000 0.00000000
## gethitched
## DIVYEAR 0.0000000
## momint 0.0000000
## dadint 0.0000000
## momclose 0.0000000
## depression 0.0000000
## livewithmom 0.0000000
## gethitched 0.1252645
$modelName gmm_clust
## [1] "VEI"
Thus, the optimal model, VEI
, has 3 components.
plot(gmm_clust$BIC, legendArgs = list(x = "bottom", ncol = 2, cex = 1))
plot(gmm_clust, what = "density")
plot(gmm_clust, what = "classification")
plot(gmm_clust, what = "uncertainty", dimens = c(6,7), main = "livewithmom vs. gethitched")
# Mclust Dimension Reduction clustering
<- MclustDR(gmm_clust, lambda=1)
gmm_clustDR summary(gmm_clustDR)
## -----------------------------------------------------------------
## Dimension reduction for model-based clustering and classification
## -----------------------------------------------------------------
##
## Mixture model type: Mclust (VEI, 3)
##
## Clusters n
## 1 16
## 2 11
## 3 20
##
## Estimated basis vectors:
## Dir1 Dir2
## DIVYEAR -0.963455 0.033455
## momint 0.018017 -0.024376
## dadint -0.020111 0.094546
## momclose -0.018771 0.107977
## depression 0.017151 0.089764
## livewithmom 0.069653 -0.971657
## gethitched 0.255983 0.159729
##
## Dir1 Dir2
## Eigenvalues 1.9604 1.007
## Cum. % 66.0653 100.000
plot(gmm_clustDR, what = "boundaries", ngrid = 200)
plot(gmm_clustDR, what = "pairs")
plot(gmm_clustDR, what = "scatterplot")
# Plot the Silhouette plot to assess the quality of
# the clustering based on the Mixture of 3 Gaussians
= silhouette(as.numeric(gmm_clustDR$classification), dis)
silGauss plot(silGauss, col=1:length(gmm_clustDR$class2mixcomp), border=NA)
To assess the model, we can print the confusion matrix comparing, say, the Mclust
clustering labels and divorce$depression
categories:
table(divorce$depression, gmm_clust$classification)
##
## 1 2 3
## 1 2 0 1
## 2 3 5 6
## 3 4 5 8
## 4 7 1 5
Try to replicate these results with other data from the list of our Case-Studies.