Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save csetzkorn/8ab0c61b06107f10ed5bc542da47240a to your computer and use it in GitHub Desktop.
Save csetzkorn/8ab0c61b06107f10ed5bc542da47240a to your computer and use it in GitHub Desktop.
Fit SOM, cluster prototypes and add cluster membership to original dataset
library(dplyr)
library(kohonen)
setwd('C:\\Users\\Christian\\Source\\Repos\\RClusteringMixedDataPam')
OrginalData <- read.table("IrisData.txt",
header = TRUE, sep = "\t")
SubsetData <- subset(OrginalData, select = c("SepalLength", "SepalWidth", "PetalLength", "PetalWidth"))
#TrainingMatrix <- as.matrix(scale(SubsetData))
TrainingMatrix <- as.matrix(SubsetData)
GridDefinition <- somgrid(xdim = 5, ydim = 5, topo = "hexagonal")
SomModel <- kohonen::supersom(data = TrainingMatrix, grid = GridDefinition, rlen = 3000, alpha = c(0.05, 0.001),
keep.data = TRUE)
groups = 3
iris.hc = cutree(hclust(dist(SomModel$codes[[1]])), groups)
plot(SomModel, type = "codes", bgcol = rainbow(groups)[iris.hc])
add.cluster.boundaries(SomModel, iris.hc)
# plot
#plot(SomModel, type = "codes", bgcol = rainbow(groups)[iris.hc])
result <- OrginalData
result$Cluster <- iris.hc[SomModel$unit.classif]
result$X <- SomModel$grid$pts[SomModel$unit.classif,"x"]
result$Y <- SomModel$grid$pts[SomModel$unit.classif,"y"]
write.table(result, file = "foo.csv", sep = ",", col.names = NA,
qmethod = "double")
points(jitter(result$X), jitter(result$Y), col=result$Species)
legend(5,0, legend=unique(result$Species), col=unique(result$Species), pch=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment