# K mean clustering ###### tags: `R教學` `基礎統計` ```r= # Loading package library(cluster) # Removing initial label of # Species from original dataset iris_1 <- iris[, -5] # Fitting K-Means clustering Model # to training dataset set.seed(240) # Setting seed kmeans.re <- kmeans(iris_1, centers = 3, nstart = 20) kmeans.re # Cluster identification for # each observation kmeans.re$cluster # Confusion Matrix cm <- table(iris$Species, kmeans.re$cluster) cm jpeg(filename = "k-mean.jpg", width = 510*2, height = 380*2, pointsize = 20, quality = 75) # Model Evaluation and visualization plot(iris_1[c("Sepal.Length", "Sepal.Width")], col = kmeans.re$cluster) ## Plotiing cluster centers kmeans.re$centers kmeans.re$centers[, c("Sepal.Length", "Sepal.Width")] # cex is font size, pch is symbol points (kmeans.re$centers[,1:2], pch = 19, col = 1:3, cex = 3) dev.off() ``` ![](https://i.imgur.com/OYgT0Q1.jpg)