Skip to content

Instantly share code, notes, and snippets.

@dgrapov
Last active March 11, 2023 11:21
Show Gist options
  • Save dgrapov/f67d0696c4fb02731f55da3e1b9e8c4d to your computer and use it in GitHub Desktop.
Save dgrapov/f67d0696c4fb02731f55da3e1b9e8c4d to your computer and use it in GitHub Desktop.
Self-organizing map (SOM) example in R
#SOM example using wines data set
library(kohonen)
data(wines)
set.seed(7)
#create SOM grid
sommap <- som(scale(wines), grid = somgrid(2, 2, "hexagonal"))
## use hierarchical clustering to cluster the codebook vectors
groups<-3
som.hc <- cutree(hclust(dist(sommap$codes)), groups)
#plot
plot(sommap, type="codes", bgcol=rainbow(groups)[som.hc])
#cluster boundaries
add.cluster.boundaries(sommap, som.hc)
@mfokaMapuma
Copy link

mfokaMapuma commented May 19, 2017

Getting

Error in dist(sommap$codes) :
(list) object cannot be coerced to type 'double'

Any one to assist. Am a newbie in R

@Xnsam
Copy link

Xnsam commented May 30, 2017

I tried this
som.hc <- cutree(hclust(dist(as.numeric(unlist(sommap$codes)))), groups)
for the error:
Error in dist(sommap$codes) :
(list) object cannot be coerced to type 'double'

and then no more error

but not sure if this is the correct way. I am a newbie too

@jokergoo
Copy link

following works

som.hc <- cutree(hclust(dist(sommap$codes[[1]])), groups)

@alleztous
Copy link

i am a little confused about how to do clustering using the result of SOM...

@mustikarizki
Copy link

How can you define the number of groups to be 3?

@mazroyal
Copy link

som.hc <- cutree(hclust(dist(sommap$codes[[1]])), groups)
thanks. this gives no error.

@liphyra
Copy link

liphyra commented Jul 18, 2019

following works

som.hc <- cutree(hclust(dist(sommap$codes[[1]])), groups)

I follow yours suggested and it works

@dgrapov
Copy link
Author

dgrapov commented Nov 29, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment