-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmeans-procedural.R
More file actions
221 lines (184 loc) · 5.42 KB
/
kmeans-procedural.R
File metadata and controls
221 lines (184 loc) · 5.42 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
fileName <- "dogs.csv"
seperator <- ","
medianAndDeviation <- data.frame()
#### setting the number of k-means clusters
k <- 3
#### retrieve the file into a global variable
fileData <<- read.delim(fileName,
sep=seperator, head=T)
cnames <- c("breed", "height", "weight")
names(fileData) <- cnames
##############################
#### getting the median
##############################
getMedian <- function(numCol){
numCol <- sort(numCol)
colLen <- length(numCol)
if(colLen %% 2 == 1){
numCol <- numCol[((length(numCol) + 1)/2)]
}else{
v1 <- numCol[((length(numCol) + 1)/2)]
v2 <- numCol[((length(numCol) + 1)/2)+1]
numCol <- (v1 + v2) / 2.0
}
}
################################
#### getting the asd
################################
getAbsoluteStandardDeviation <- function(numCol, median){
sum = 0
for (item in numCol){
sum <- (sum + abs(item - median))
}
return(sum / length(numCol))
}
################################
#### Normalize a column
################################
normalizeColumn <- function(colNumber, set){
col <- set[,colNumber]
median <- getMedian(col)
asd <- getAbsoluteStandardDeviation(col, median)
medianAndDeviation <<- rbind(
medianAndDeviation , cbind(median, asd))
for (i in 1:length(col)){
col[i] <- (col[i]-median)/asd
}
return(col)
}
#################################
#### calculate the manhattan distance
#################################
manhattanDistance <- function(vector1, vector2){
dist <- data.frame()
for (j in 1:nrow(vector2)){
dist <- rbind(dist, c(j, sum(abs(vector1 - vector2[j,]))))
}
return(dist)
}
################################
#### Start the normalization ###
################################
##fileData <- fileData2
dataCols <- length(fileData)
numCols <- fileData[,-1]
for (i in 1:length(numCols)){
numCols[,i] <- normalizeColumn(i,numCols)
}
fileData[,-1] <- numCols
################################
#### select random cluster centers
centroids <- fileData[sample(nrow(fileData), k), ]
#### which clusters do the data points belong to
#### default membership is "-1" for starters
membership <- vector()
for (i in 1:nrow(fileData)) membership <- c(membership, -1)
################################
################################
#### clustering
################################
#### keep track of how many points changed
pointsChanged <- 0
#### sum of squared error
sse <- 0
#### number of iterations made by the algorithm
#### to converge
iterationNumber <- 0
euclideanDistance <- function(x1, x2){
return(sqrt(sum((fileData[x1,-1] - centroids[x2,-1])^2)))
}
################################
#### assigning specific point to a cluster
#### depending on the distance from the mean
################################
assignPointToCluster <- function(i){
#### The minimum distance between the data point "i"
#### that has been pursed and all centroids - initially too high
#### but should be updated after distance between the two
#### points has been calculated
minDistance <- 999999
clusterNum <- -1
for (centroid in 1:k){
dist <- euclideanDistance(i, centroid)
if (dist < minDistance){
minDistance = dist
clusterNum = centroid
}
}
if(clusterNum != membership[i]){
pointsChanged <<- pointsChanged + 1
}
sse <<- sse + (minDistance^2)
return(clusterNum)
}
################################
#### assigning points to a cluster
################################
assignPointsTocluster <- function(){
pointsChanged <<- 0
sse <<- 0
for (i in 1:nrow(fileData)){
membership[i] <<- assignPointToCluster(i)
}
return(membership)
}
################################
#### updating the centroids
################################
updateCentroids <- function(){
#### number of members per cluster
clusterMembers <- data.frame(table(membership))
for (centroid in 1:nrow(centroids)){
currentCentroidMembers <- data.frame()
centroidFreq <-
clusterMembers[clusterMembers$membership == centroid, ]
for (k in 1:nrow(fileData)){
if(membership[k] == centroid){
currentCentroidMembers <-
rbind(currentCentroidMembers, fileData[k,])
}
}
for (name in 2:length(centroids)){
centroids[centroid,][[name]] <<-
sum(currentCentroidMembers[[name]])/centroidFreq$Freq
}
}
}
### clusters
startClusters <- function(){
assignPointsTocluster()
done <- FALSE
while (!done){
iterationNumber <<- iterationNumber + 1
updateCentroids()
assignPointsTocluster()
#### stop the
if ((pointsChanged / length(membership)) < 0.01){
done = TRUE
}
}
print(paste("Final SSE:", sse))
print(paste("iterations", iterationNumber))
}
cls <- data.frame()
#### show the dogs in the 3 clusters
showClusterMembers <- function(){
for (centroid in 1:nrow(centroids)){
currentCentroidMembers <- data.frame()
for (k in 1:nrow(fileData)){
if(membership[k] == centroid){
currentCentroidMembers <-
rbind(currentCentroidMembers, fileData[k,])
}
}
print(paste("**** cluster ", centroid))
print(currentCentroidMembers[1])
cluster <- rep(centroid, nrow(currentCentroidMembers))
currentCentroidMembers <- cbind(currentCentroidMembers, cluster)
cls <<- rbind(cls, currentCentroidMembers)
}
}
startClusters()
showClusterMembers()
cls$cluster <- as.factor(cls$cluster)
plot(cls$height, cls$weight, col=c("red","blue","green")[cls$cluster])