Site icon R-bloggers

Unsupervised Machine Learning in R: K-Means

[This article was first published on R code – data technik, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

K-Means clustering is unsupervised machine learning because there is not a target variable. Clustering can be used to create a target variable, or simply group data by certain characteristics.

Here’s a great and simple way to use R to find clusters, visualize and then tie back to the data source to implement a marketing strategy.

setwd
#import dataset
ABC <-read.table("AbcBank.csv",header=TRUE, 
                  sep=",")

#choose variables to be clustered 
# make sure to exclude ID fields or Dates
ABC_num<- ABC[,2:5]
#scale the data! so they are all normalized 
ABC_scaled <-as.data.frame(scale(ABC_num))

#kmeans function
k3<- kmeans(ABC_scaled, centers=3, nstart=25)
#library with the visualization
library(factoextra)
fviz_cluster(k3, data=ABC_scaled,
             ellipse.type="convex",
             axes =c(1,2),
             geom="point",
             label="none",
             ggtheme=theme_classic())
#check out the centers 
# remember these are normalized but 
#higher values are higher values for the original data
    k3$centers          
#add the cluster to the original dataset!
    ABC$Cluster<-as.numeric(k3$cluster)
    

Check out our awesome clusters:

Repo here with dataset: https://github.com/emileemc/kmeans

To leave a comment for the author, please follow the link and comment on their blog: R code – data technik.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.