Agrupamiento o clustering es una tecnica de aprendizaje
automatico no supervisado que agrupa datos en funcion de su
similitud.
Algunos usos típicos de esta técnica son:
#install.packages("cluster") # Análisis de Agrupamiento
library(cluster)
#install.packages("ggplot2") # Graficar
library(ggplot2)
#install.packages("data.table") #Manejo de muchos datos
library(data.table)
#install.packages("factoextra") # Grafica optimizacion de numero de clusters
library(factoextra)
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
df1 <- data.frame(x=c(2,2,8,5,7,6,1,4), y=c(10,5,4,8,5,4,2,9))
summary(df1)
## x y
## Min. :1.000 Min. : 2.000
## 1st Qu.:2.000 1st Qu.: 4.000
## Median :4.500 Median : 5.000
## Mean :4.375 Mean : 5.875
## 3rd Qu.:6.250 3rd Qu.: 8.250
## Max. :8.000 Max. :10.000
str(df1)
## 'data.frame': 8 obs. of 2 variables:
## $ x: num 2 2 8 5 7 6 1 4
## $ y: num 10 5 4 8 5 4 2 9
# Sólo si los datos no estan en la misma escala.
# datos_escalados <- scale(datos_originales)
# Siempre es un valor inicial cualquiera, luego se optimiza.
plot(df1$x,df1$y)
grupos1 <- 3
set.seed(123)
clusters1 <- kmeans(df1, grupos1)
clusters1
## K-means clustering with 3 clusters of sizes 2, 3, 3
##
## Cluster means:
## x y
## 1 1.500000 3.500000
## 2 3.666667 9.000000
## 3 7.000000 4.333333
##
## Clustering vector:
## [1] 2 1 3 2 3 3 1 2
##
## Within cluster sum of squares by cluster:
## [1] 5.000000 6.666667 2.666667
## (between_SS / total_SS = 85.8 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
set.seed(123)
optimizacion1 <- clusGap(df1, FUN=kmeans, nstart=1, K.max=7)
# El K.max normalmente es 10, en este ejercicio al ser 8 datos se dejo en 7.
plot(optimizacion1, xlab="Número de clusters k", main="Optimización de clusters")
# Se selecciona como óptimo el primer punto mas alto.
fviz_cluster(clusters1, data=df1)
df1_clusters <- cbind(df1, cluster = clusters1$cluster)
head(df1_clusters)
La técnica de clustering permite identificar patrones o grupos naturales en los datos sin necesidad de etiquetas previas.