-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKMEANS.c
441 lines (390 loc) · 10.7 KB
/
KMEANS.c
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/*
* k-Means clustering algorithm
*
* Reference sequential version (Do not modify this code)
*
* Parallel computing (Degree in Computer Engineering)
* 2022/2023
*
* Version: 1.0
*
* (c) 2022 Diego García-Álvarez, Arturo Gonzalez-Escribano
* Grupo Trasgo, Universidad de Valladolid (Spain)
*
* This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
* https://creativecommons.org/licenses/by-sa/4.0/
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include <float.h>
#define MAXLINE 2000
#define MAXCAD 200
//Macros
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
/*
Function showFileError: It displays the corresponding error during file reading.
*/
void showFileError(int error, char* filename)
{
printf("Error\n");
switch (error)
{
case -1:
fprintf(stderr,"\tFile %s has too many columns.\n", filename);
fprintf(stderr,"\tThe maximum number of columns has been exceeded. MAXLINE: %d.\n", MAXLINE);
break;
case -2:
fprintf(stderr,"Error reading file: %s.\n", filename);
break;
case -3:
fprintf(stderr,"Error writing file: %s.\n", filename);
break;
}
fflush(stderr);
}
/*
Function readInput: It reads the file to determine the number of rows and columns.
*/
int readInput(char* filename, int *lines, int *samples)
{
FILE *fp;
char line[MAXLINE] = "";
char *ptr;
const char *delim = "\t";
int contlines, contsamples = 0;
contlines = 0;
if ((fp=fopen(filename,"r"))!=NULL)
{
while(fgets(line, MAXLINE, fp)!= NULL)
{
if (strchr(line, '\n') == NULL)
{
return -1;
}
contlines++;
ptr = strtok(line, delim);
contsamples = 0;
while(ptr != NULL)
{
contsamples++;
ptr = strtok(NULL, delim);
}
}
fclose(fp);
*lines = contlines;
*samples = contsamples;
return 0;
}
else
{
return -2;
}
}
/*
Function readInput2: It loads data from file.
*/
int readInput2(char* filename, float* data)
{
FILE *fp;
char line[MAXLINE] = "";
char *ptr;
const char *delim = "\t";
int i = 0;
if ((fp=fopen(filename,"rt"))!=NULL)
{
while(fgets(line, MAXLINE, fp)!= NULL)
{
ptr = strtok(line, delim);
while(ptr != NULL)
{
data[i] = atof(ptr);
i++;
ptr = strtok(NULL, delim);
}
}
fclose(fp);
return 0;
}
else
{
return -2; //No file found
}
}
/*
Function writeResult: It writes in the output file the cluster of each sample (point).
*/
int writeResult(int *classMap, int lines, const char* filename)
{
FILE *fp;
if ((fp=fopen(filename,"wt"))!=NULL)
{
for(int i=0; i<lines; i++)
{
fprintf(fp,"%d\n",classMap[i]);
}
fclose(fp);
return 0;
}
else
{
return -3; //No file found
}
}
/*
Function initCentroids: This function copies the values of the initial centroids, using their
position in the input data structure as a reference map.
*/
void initCentroids(const float *data, float* centroids, int* centroidPos, int samples, int K)
{
int i;
int idx;
for(i=0; i<K; i++)
{
idx = centroidPos[i];
memcpy(¢roids[i*samples], &data[idx*samples], (samples*sizeof(float)));
}
}
/*
Function euclideanDistance: Euclidean distance
This function could be modified
*/
float euclideanDistance(float *point, float *center, int samples)
{
float dist=0.0;
for(int i=0; i<samples; i++)
{
dist+= (point[i]-center[i])*(point[i]-center[i]);
}
dist = sqrt(dist);
return(dist);
}
/*
Function zeroFloatMatriz: Set matrix elements to 0
This function could be modified
*/
void zeroFloatMatriz(float *matrix, int rows, int columns)
{
int i,j;
for (i=0; i<rows; i++)
for (j=0; j<columns; j++)
matrix[i*columns+j] = 0.0;
}
/*
Function zeroIntArray: Set array elements to 0
This function could be modified
*/
void zeroIntArray(int *array, int size)
{
int i;
for (i=0; i<size; i++)
array[i] = 0;
}
int main(int argc, char* argv[])
{
//START CLOCK***************************************
clock_t start, end;
start = clock();
//**************************************************
/*
* PARAMETERS
*
* argv[1]: Input data file
* argv[2]: Number of clusters
* argv[3]: Maximum number of iterations of the method. Algorithm termination condition.
* argv[4]: Minimum percentage of class changes. Algorithm termination condition.
* If between one iteration and the next, the percentage of class changes is less than
* this percentage, the algorithm stops.
* argv[5]: Precision in the centroid distance after the update.
* It is an algorithm termination condition. If between one iteration of the algorithm
* and the next, the maximum distance between centroids is less than this precision, the
* algorithm stops.
* argv[6]: Output file. Class assigned to each point of the input file.
* */
if(argc != 7)
{
fprintf(stderr,"EXECUTION ERROR K-MEANS: Parameters are not correct.\n");
fprintf(stderr,"./KMEANS [Input Filename] [Number of clusters] [Number of iterations] [Number of changes] [Threshold] [Output data file]\n");
fflush(stderr);
exit(-1);
}
// Reading the input data
// lines = number of points; samples = number of dimensions per point
int lines = 0, samples= 0;
int error = readInput(argv[1], &lines, &samples);
if(error != 0)
{
showFileError(error,argv[1]);
exit(error);
}
float *data = (float*)calloc(lines*samples,sizeof(float));
if (data == NULL)
{
fprintf(stderr,"Memory allocation error.\n");
exit(-4);
}
error = readInput2(argv[1], data);
if(error != 0)
{
showFileError(error,argv[1]);
exit(error);
}
// Parameters
int K=atoi(argv[2]);
int maxIterations=atoi(argv[3]);
int minChanges= (int)(lines*atof(argv[4])/100.0);
float maxThreshold=atof(argv[5]);
int *centroidPos = (int*)calloc(K,sizeof(int));
float *centroids = (float*)calloc(K*samples,sizeof(float));
int *classMap = (int*)calloc(lines,sizeof(int));
if (centroidPos == NULL || centroids == NULL || classMap == NULL)
{
fprintf(stderr,"Memory allocation error.\n");
exit(-4);
}
// Initial centrodis
srand(0);
int i;
for(i=0; i<K; i++)
centroidPos[i]=rand()%lines;
// Loading the array of initial centroids with the data from the array data
// The centroids are points stored in the data array.
initCentroids(data, centroids, centroidPos, samples, K);
printf("\n\tData file: %s \n\tPoints: %d\n\tDimensions: %d\n", argv[1], lines, samples);
printf("\tNumber of clusters: %d\n", K);
printf("\tMaximum number of iterations: %d\n", maxIterations);
printf("\tMinimum number of changes: %d [%g%% of %d points]\n", minChanges, atof(argv[4]), lines);
printf("\tMaximum centroid precision: %f\n", maxThreshold);
//END CLOCK*****************************************
end = clock();
printf("\nMemory allocation: %f seconds\n", (double)(end - start) / CLOCKS_PER_SEC);
fflush(stdout);
//**************************************************
//START CLOCK***************************************
start = clock();
//**************************************************
char *outputMsg = (char *)calloc(10000,sizeof(char));
char line[100];
int j;
int class;
float dist, minDist;
int it=0;
int changes = 0;
float maxDist;
//pointPerClass: number of points classified in each class
//auxCentroids: mean of the points in each class
int *pointsPerClass = (int *)malloc(K*sizeof(int));
float *auxCentroids = (float*)malloc(K*samples*sizeof(float));
float *distCentroids = (float*)malloc(K*sizeof(float));
if (pointsPerClass == NULL || auxCentroids == NULL || distCentroids == NULL)
{
fprintf(stderr,"Memory allocation error.\n");
exit(-4);
}
/*
*
* START HERE: DO NOT CHANGE THE CODE ABOVE THIS POINT
*
*/
do{
it++;
//1. Calculate the distance from each point to the centroid
//Assign each point to the nearest centroid.
changes = 0;
for(i=0; i<lines; i++)
{
class=1;
minDist=FLT_MAX;
for(j=0; j<K; j++)
{
dist=euclideanDistance(&data[i*samples], ¢roids[j*samples], samples);
if(dist < minDist)
{
minDist=dist;
class=j+1;
}
}
if(classMap[i]!=class)
{
changes++;
}
classMap[i]=class;
}
// 2. Recalculates the centroids: calculates the mean within each cluster
zeroIntArray(pointsPerClass,K);
zeroFloatMatriz(auxCentroids,K,samples);
for(i=0; i<lines; i++)
{
class=classMap[i];
pointsPerClass[class-1] = pointsPerClass[class-1] +1;
for(j=0; j<samples; j++){
auxCentroids[(class-1)*samples+j] += data[i*samples+j];
}
}
for(i=0; i<K; i++)
{
for(j=0; j<samples; j++){
auxCentroids[i*samples+j] /= pointsPerClass[i];
}
}
maxDist=FLT_MIN;
for(i=0; i<K; i++){
distCentroids[i]=euclideanDistance(¢roids[i*samples], &auxCentroids[i*samples], samples);
if(distCentroids[i]>maxDist) {
maxDist=distCentroids[i];
}
}
memcpy(centroids, auxCentroids, (K*samples*sizeof(float)));
sprintf(line,"\n[%d] Cluster changes: %d\tMax. centroid distance: %f", it, changes, maxDist);
outputMsg = strcat(outputMsg,line);
} while((changes>minChanges) && (it<maxIterations) && (maxDist>maxThreshold));
/*
*
* STOP HERE: DO NOT CHANGE THE CODE BELOW THIS POINT
*
*/
// Output and termination conditions
printf("%s",outputMsg);
//END CLOCK*****************************************
end = clock();
printf("\nComputation: %f seconds", (double)(end - start) / CLOCKS_PER_SEC);
fflush(stdout);
//**************************************************
//START CLOCK***************************************
start = clock();
//**************************************************
if (changes <= minChanges) {
printf("\n\nTermination condition:\nMinimum number of changes reached: %d [%d]", changes, minChanges);
}
else if (it >= maxIterations) {
printf("\n\nTermination condition:\nMaximum number of iterations reached: %d [%d]", it, maxIterations);
}
else {
printf("\n\nTermination condition:\nCentroid update precision reached: %g [%g]", maxDist, maxThreshold);
}
// Writing the classification of each point to the output file.
error = writeResult(classMap, lines, argv[6]);
if(error != 0)
{
showFileError(error, argv[6]);
exit(error);
}
//Free memory
free(data);
free(classMap);
free(centroidPos);
free(centroids);
free(distCentroids);
free(pointsPerClass);
free(auxCentroids);
//END CLOCK*****************************************
end = clock();
printf("\n\nMemory deallocation: %f seconds\n", (double)(end - start) / CLOCKS_PER_SEC);
fflush(stdout);
//***************************************************/
return 0;
}