2015년 9월 11일 금요일

[R] K-means & Hierarchical Clustering

# Load the Iris dataset
data(iris)

# Remove the class label
newiris <- iris
newiris$Species <- NULL

# Perform K-Means Clustering with K=3
kc <- kmeans(newiris,3)

str(kc)
kc$centers
kc$size
kc$cluster

# Compare the assigned clusters and the Species
table(iris$Species, kc$cluster)

plot(newiris[,c("Sepal.Length", "Sepal.Width")], col = kc$cluster)
points(kc$centers[,c("Sepal.Length", "Sepal.Width")], col = 1:3, pch = 8, cex=2)

# Perform K-Means Clustering with K=5
kc <- kmeans(newiris,5)

# Compare the assigned clusters and the Species
table(iris$Species, kc$cluster)

plot(newiris[,c("Sepal.Length", "Sepal.Width")], col = kc$cluster)
points(kc$centers[,c("Sepal.Length", "Sepal.Width")], col = 1:5, pch = 8, cex=2)

# Creates a sample dataset
y <- matrix(rnorm(50), 10, 5, dimnames=list(paste("g", 1:10, sep=""), paste("t", 1:5, sep="")))

# Compute the similarity using the spearman coefficient
c <- cor(t(y), method="spearman")
d <- as.dist(1-c)

# Perform hierarchical clustering
hr <- hclust(d, method = "complete", members=NULL)

# plot the results
par(mfrow = c(2, 2))
plot(hr, hang = 0.1)
plot(hr, hang = -1)
plot(as.dendrogram(hr), edgePar=list(col=3, lwd=4), horiz=T)

# Prints the full content of the hclust object
unclass(hr)

# Prints dendrogram structure as text
str(as.dendrogram(hr))

# Prints the row labels in the order they appear in the tree
hr$labels[hr$order]

# Find the clusters
mycl <- cutree(hr, h=max(hr$height)/2)
mycl
plot(hr)
rect.hclust(hr, k=5, border="red")

# Imports color function to obtain heat maps in red and green.
# Use this color function in heatmap color argument like this: 'col=my.colorFct()'
source("http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/My_R_Scripts/my.colorFct.R")

# Clusters rows by Pearson correlation as distance method.
hr <- hclust(as.dist(1-cor(t(y), method="pearson")), method="complete")

# Clusters columns by Spearman correlation as distance method.
hc <- hclust(as.dist(1-cor(y, method="spearman")), method="complete")

# The previous two hclust objects are used to obtain a heatmap
# where the rows are clusterd by Pearson and the columns by Spearman correlation distances.
# The 'scale' argument allows to scale the input matrix by rows or columns.
# The default is by rows and "none" turns the scaling off.
heatmap(y, Rowv=as.dendrogram(hr), Colv=as.dendrogram(hc), col=my.colorFct(), scale="row")

mycl <- cutree(hr, h=max(hr$height)/1.5)
mycol <- sample(rainbow(256))
mycol <- mycol[as.vector(mycl)]
heatmap(y, Rowv=as.dendrogram(hr), Colv=as.dendrogram(hc), col=my.colorFct(),
        scale="row", ColSideColors=heat.colors(length(hc$labels)), RowSideColors=mycol)

댓글 없음:

댓글 쓰기