1、数据预处理
代码:
# Importing the dataset
dataset <- read.csv('Mall_Customers.csv')
X <- dataset[4:5]
2、手肘法则
代码:
# Using the elbow method to find the optimal number of clusters
set.seed(6)
wcss = vector()
for (i in 1:10) wcss[i] = sum(kmeans(X, i)$withinss)
plot(1:10,
wcss,
type = 'b',
main = paste('The Elbow Method'),
xlab = 'Number of cluster',
ylab = 'WCSS')
绘制组数与组间距的曲线,选取合适的分组个数。
3、拟合聚类器
代码:
# Fitting K-Means to the dataset
set.seed(29)
kmeans = kmeans(X, 5, iter.max =300, nstart =10)
y_kmeans = kmeans$cluster
这里的nstart参数是为了确定中心点随机选择多少组,每组都运行,最后选择最佳的那一个组。
得到聚类结果.PNG
4、可视化显示
代码:
# Visualising the clusters
library(cluster)
clusplot(X,
y_kmeans,
lines = 0,
shade = TRUE,
color = TRUE,
labels =2,
plotchar = FALSE,
span = TRUE,
main = paste('Clusters of customers'),
xlab = 'Annual Income',
ylab = 'Spending Score')
聚类结果.PNG
这里的有些参数是为了显示的美化,比如,span是为了显示外面的圈,plotchar是为了显示不同数据点的标记点图形显示。
网友评论