-
Notifications
You must be signed in to change notification settings - Fork 38
/
kmeans.cpp
363 lines (303 loc) · 9.26 KB
/
kmeans.cpp
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
#include <omp.h>
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
class Point
{
private:
int pointId, clusterId;
int dimensions;
vector<double> values;
vector<double> lineToVec(string &line)
{
vector<double> values;
string tmp = "";
for (int i = 0; i < (int)line.length(); i++)
{
if ((48 <= int(line[i]) && int(line[i]) <= 57) || line[i] == '.' || line[i] == '+' || line[i] == '-' || line[i] == 'e')
{
tmp += line[i];
}
else if (tmp.length() > 0)
{
values.push_back(stod(tmp));
tmp = "";
}
}
if (tmp.length() > 0)
{
values.push_back(stod(tmp));
tmp = "";
}
return values;
}
public:
Point(int id, string line)
{
pointId = id;
values = lineToVec(line);
dimensions = values.size();
clusterId = 0; // Initially not assigned to any cluster
}
int getDimensions() { return dimensions; }
int getCluster() { return clusterId; }
int getID() { return pointId; }
void setCluster(int val) { clusterId = val; }
double getVal(int pos) { return values[pos]; }
};
class Cluster
{
private:
int clusterId;
vector<double> centroid;
vector<Point> points;
public:
Cluster(int clusterId, Point centroid)
{
this->clusterId = clusterId;
for (int i = 0; i < centroid.getDimensions(); i++)
{
this->centroid.push_back(centroid.getVal(i));
}
this->addPoint(centroid);
}
void addPoint(Point p)
{
p.setCluster(this->clusterId);
points.push_back(p);
}
bool removePoint(int pointId)
{
int size = points.size();
for (int i = 0; i < size; i++)
{
if (points[i].getID() == pointId)
{
points.erase(points.begin() + i);
return true;
}
}
return false;
}
void removeAllPoints() { points.clear(); }
int getId() { return clusterId; }
Point getPoint(int pos) { return points[pos]; }
int getSize() { return points.size(); }
double getCentroidByPos(int pos) { return centroid[pos]; }
void setCentroidByPos(int pos, double val) { this->centroid[pos] = val; }
};
class KMeans
{
private:
int K, iters, dimensions, total_points;
vector<Cluster> clusters;
string output_dir;
void clearClusters()
{
for (int i = 0; i < K; i++)
{
clusters[i].removeAllPoints();
}
}
int getNearestClusterId(Point point)
{
double sum = 0.0, min_dist;
int NearestClusterId;
if(dimensions==1) {
min_dist = abs(clusters[0].getCentroidByPos(0) - point.getVal(0));
}
else
{
for (int i = 0; i < dimensions; i++)
{
sum += pow(clusters[0].getCentroidByPos(i) - point.getVal(i), 2.0);
// sum += abs(clusters[0].getCentroidByPos(i) - point.getVal(i));
}
min_dist = sqrt(sum);
}
NearestClusterId = clusters[0].getId();
for (int i = 1; i < K; i++)
{
double dist;
sum = 0.0;
if(dimensions==1) {
dist = abs(clusters[i].getCentroidByPos(0) - point.getVal(0));
}
else {
for (int j = 0; j < dimensions; j++)
{
sum += pow(clusters[i].getCentroidByPos(j) - point.getVal(j), 2.0);
// sum += abs(clusters[i].getCentroidByPos(j) - point.getVal(j));
}
dist = sqrt(sum);
// dist = sum;
}
if (dist < min_dist)
{
min_dist = dist;
NearestClusterId = clusters[i].getId();
}
}
return NearestClusterId;
}
public:
KMeans(int K, int iterations, string output_dir)
{
this->K = K;
this->iters = iterations;
this->output_dir = output_dir;
}
void run(vector<Point> &all_points)
{
total_points = all_points.size();
dimensions = all_points[0].getDimensions();
// Initializing Clusters
vector<int> used_pointIds;
for (int i = 1; i <= K; i++)
{
while (true)
{
int index = rand() % total_points;
if (find(used_pointIds.begin(), used_pointIds.end(), index) ==
used_pointIds.end())
{
used_pointIds.push_back(index);
all_points[index].setCluster(i);
Cluster cluster(i, all_points[index]);
clusters.push_back(cluster);
break;
}
}
}
cout << "Clusters initialized = " << clusters.size() << endl
<< endl;
cout << "Running K-Means Clustering.." << endl;
int iter = 1;
while (true)
{
cout << "Iter - " << iter << "/" << iters << endl;
bool done = true;
// Add all points to their nearest cluster
#pragma omp parallel for reduction(&&: done) num_threads(16)
for (int i = 0; i < total_points; i++)
{
int currentClusterId = all_points[i].getCluster();
int nearestClusterId = getNearestClusterId(all_points[i]);
if (currentClusterId != nearestClusterId)
{
all_points[i].setCluster(nearestClusterId);
done = false;
}
}
// clear all existing clusters
clearClusters();
// reassign points to their new clusters
for (int i = 0; i < total_points; i++)
{
// cluster index is ID-1
clusters[all_points[i].getCluster() - 1].addPoint(all_points[i]);
}
// Recalculating the center of each cluster
for (int i = 0; i < K; i++)
{
int ClusterSize = clusters[i].getSize();
for (int j = 0; j < dimensions; j++)
{
double sum = 0.0;
if (ClusterSize > 0)
{
#pragma omp parallel for reduction(+: sum) num_threads(16)
for (int p = 0; p < ClusterSize; p++)
{
sum += clusters[i].getPoint(p).getVal(j);
}
clusters[i].setCentroidByPos(j, sum / ClusterSize);
}
}
}
if (done || iter >= iters)
{
cout << "Clustering completed in iteration : " << iter << endl
<< endl;
break;
}
iter++;
}
ofstream pointsFile;
pointsFile.open(output_dir + "/" + to_string(K) + "-points.txt", ios::out);
for (int i = 0; i < total_points; i++)
{
pointsFile << all_points[i].getCluster() << endl;
}
pointsFile.close();
// Write cluster centers to file
ofstream outfile;
outfile.open(output_dir + "/" + to_string(K) + "-clusters.txt");
if (outfile.is_open())
{
for (int i = 0; i < K; i++)
{
cout << "Cluster " << clusters[i].getId() << " centroid : ";
for (int j = 0; j < dimensions; j++)
{
cout << clusters[i].getCentroidByPos(j) << " "; // Output to console
outfile << clusters[i].getCentroidByPos(j) << " "; // Output to file
}
cout << endl;
outfile << endl;
}
outfile.close();
}
else
{
cout << "Error: Unable to write to clusters.txt";
}
}
};
int main(int argc, char **argv)
{
// Need 3 arguments (except filename) to run, else exit
if (argc != 4)
{
cout << "Error: command-line argument count mismatch. \n ./kmeans <INPUT> <K> <OUT-DIR>" << endl;
return 1;
}
string output_dir = argv[3];
// Fetching number of clusters
int K = atoi(argv[2]);
// Open file for fetching points
string filename = argv[1];
ifstream infile(filename.c_str());
if (!infile.is_open())
{
cout << "Error: Failed to open file." << endl;
return 1;
}
// Fetching points from file
int pointId = 1;
vector<Point> all_points;
string line;
while (getline(infile, line))
{
Point point(pointId, line);
all_points.push_back(point);
pointId++;
}
infile.close();
cout << "\nData fetched successfully!" << endl
<< endl;
// Return if number of clusters > number of points
if ((int)all_points.size() < K)
{
cout << "Error: Number of clusters greater than number of points." << endl;
return 1;
}
// Running K-Means Clustering
int iters = 100;
KMeans kmeans(K, iters, output_dir);
kmeans.run(all_points);
return 0;
}