-
Notifications
You must be signed in to change notification settings - Fork 0
/
K-mean_R.r
45 lines (37 loc) · 1.19 KB
/
K-mean_R.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#Clustering Method
#K-Means
rm(list = ls())
#importing dataset
dataset = read.csv("Mall_Customers.csv")
X = dataset[4:5]
#Using elbow method to find optimal value of k
set.seed(123)
wcss = vector()
for (i in 1:10)
wcss[i] = sum(kmeans(X, i)$withinss)
plot(1:10, wcss, type = "b" , main = "Eblow method", xlab = "Number of Clusbers",
ylab = "WCSS Score")
#Hence Optimized number of Cluster is 5
#Applying k-means to the mall dataset
set.seed(123)
kmeans = kmeans(X, 5 , iter.max = 300, nstart = 10)
#visualizing the clusters
library(cluster)
clusplot(x = X,
clus = kmeans$cluster,
lines = 0,
shade = TRUE,
color = TRUE,
labels = 5,
plotchar = TRUE,
span = TRUE,
main = "Clusters",
xlab = "Annual Income",
ylab = "Spending score")
# a plot without scaling
plot(x=X[,1], y=X[,2], col=kmeans$cluster, pch=19,
xlim=c(from=min(X[,1]), to=max(X[,1]+30)),
xlab="Annual Income", ylab="Spending Score",
main = "Clusters")
clusters=c("Careless", "Standard", "Sensible", "Target", "Careful")
legend('bottomright', legend=clusters, col=1:5, pch=19, horiz=F)