1 /* =============================================================================
5 * =============================================================================
9 * Takes as input a file:
10 * ascii file: containing 1 data point per line
11 * binary file: first int is the number of objects
12 * 2nd int is the no. of features of each object
14 * This example performs a fuzzy c-means clustering on the data. Fuzzy clustering
15 * is performed using min to max clusters and the clustering that gets the best
16 * score according to a compactness and separation criterion are returned.
22 * ECE Department Northwestern University
23 * email: wkliao@ece.northwestern.edu
29 * Northwestern University
34 * Port to Java version
36 * University of California, Irvine
38 * =============================================================================
40 * ------------------------------------------------------------------------
42 * For the license of kmeans, please see kmeans/LICENSE.kmeans
44 * ------------------------------------------------------------------------
46 * Unless otherwise noted, the following license applies to STAMP files:
48 * Copyright (c) 2007, Stanford University
49 * All rights reserved.
51 * Redistribution and use in source and binary forms, with or without
52 * modification, are permitted provided that the following conditions are
55 * * Redistributions of source code must retain the above copyright
56 * notice, this list of conditions and the following disclaimer.
58 * * Redistributions in binary form must reproduce the above copyright
59 * notice, this list of conditions and the following disclaimer in
60 * the documentation and/or other materials provided with the
63 * * Neither the name of Stanford University nor the names of its
64 * contributors may be used to endorse or promote products derived
65 * from this software without specific prior written permission.
67 * THIS SOFTWARE IS PROVIDED BY STANFORD UNIVERSITY ``AS IS'' AND ANY
68 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
69 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
70 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE
71 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
72 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
73 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
74 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
75 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
76 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
77 * THE POSSIBILITY OF SUCH DAMAGE.
79 * =============================================================================
82 public class KMeans /*extends Thread*/ {
84 * User input for max clusters
89 * User input for min clusters
94 * Check for Binary file
99 * Using zscore transformation for cluster center
100 * deviating from distribution's mean
102 int use_zscore_transform;
105 * Input file name used for clustering
110 * Total number of threads
115 * threshold until which kmeans cluster continues
125 * Global arguments for threads
130 * Output: Number of best clusters
135 * Output: Cluster centers
137 float[][] cluster_centres;
139 public boolean validationTest;
145 use_zscore_transform = 1;
146 threshold = (float) 0.001;
148 validationTest=false;
151 public KMeans(int threadid, GlobalArgs g_args) {
152 this.threadid = threadid;
153 this.g_args = g_args;
158 // Barrier.enterBarrier();
159 Normal.work(threadid, g_args);
160 // Barrier.enterBarrier();
164 /* =============================================================================
166 * =============================================================================
168 public static void main(String[] args) {
170 int MAX_LINE_LENGTH = 1000000; /* max input is 400000 one digit input + spaces */
173 * Read options fron the command prompt
175 KMeans kms = new KMeans();
176 KMeans.parseCmdLine(args, kms);
177 nthreads = kms.nthreads;
179 /* Initiate Barriers */
180 // Barrier.setBarrier(nthreads);
182 if (kms.max_nclusters < kms.min_nclusters) {
183 System.out.println("Error: max_clusters must be >= min_clusters\n");
188 float[][] attributes;
189 int numAttributes = 0;
193 * From the input file, get the numAttributes (columns in txt file) and numObjects (rows in txt file)
195 if (kms.isBinaryFile == 1) {
196 System.out.println("TODO: Unimplemented Binary file option\n");
200 FileInputStream inputFile = new FileInputStream(kms.filename);
201 byte b[] = new byte[MAX_LINE_LENGTH];
203 while ((n = inputFile.read(b)) != 0) {
204 for (int i = 0; i < n; i++) {
210 inputFile = new FileInputStream(kms.filename);
212 if((line = inputFile.readLine()) != null) {
214 boolean prevWhiteSpace = true;
215 while(index < line.length()) {
216 char c = line.charAt(index++);
217 boolean currWhiteSpace = Character.isWhitespace(c);
218 if(prevWhiteSpace && !currWhiteSpace){
221 prevWhiteSpace = currWhiteSpace;
226 /* Ignore the first attribute: numAttributes = 1; */
227 numAttributes = numAttributes - 1;
228 System.out.println("numObjects= " + numObjects + " numAttributes= " + numAttributes);
230 /* Allocate new shared objects and read attributes of all objects */
231 buf = new float[numObjects][numAttributes];
232 attributes = new float[numObjects][numAttributes];
233 KMeans.readFromFile(inputFile, kms.filename, buf, MAX_LINE_LENGTH);
234 System.out.println("Finished Reading from file ......");
235 long startT=System.currentTimeMillis();
237 * The core of the clustering
241 int len = kms.max_nclusters - kms.min_nclusters + 1;
243 KMeans[] km = new KMeans[nthreads];
244 GlobalArgs g_args = new GlobalArgs();
245 g_args.nthreads = nthreads;
247 /* Create and Start Threads */
248 for(int i = 1; i<nthreads; i++) {
249 km[i] = new KMeans(i, g_args);
252 for(int i = 1; i<nthreads; i++) {
256 System.out.println("Finished Starting threads......");
258 for (int i = 0; i < nloops; i++) {
260 * Since zscore transform may perform in cluster() which modifies the
261 * contents of attributes[][], we need to re-store the originals
263 for(int x = 0; x < numObjects; x++) {
264 for(int y = 0; y < numAttributes; y++) {
265 attributes[x][y] = buf[x][y];
269 Cluster.cluster_exec(nthreads,
272 attributes, // [numObjects][numAttributes]
273 kms, //main class that holds users inputs from command prompt and output arrays that need to be filled
274 g_args); // Global arguments common to all threads
277 long endT=System.currentTimeMillis();
278 if(!kms.validationTest){
279 System.out.println("running time="+(endT-startT));
281 // System.out.println("TIME="+g_args.global_time);
283 System.out.println("Printing output......");
284 System.out.println("Best_nclusters= " + kms.best_nclusters);
286 /* Output: the coordinates of the cluster centres */
287 if(kms.validationTest){
288 for (int i = 0; i < kms.best_nclusters; i++) {
289 System.out.print(i + " ");
290 for (int j = 0; j < numAttributes; j++) {
291 System.out.print(kms.cluster_centres[i][j] + " ");
293 System.out.println("\n");
297 System.out.println("Finished......");
301 public static void parseCmdLine(String args[], KMeans km) {
304 while (i < args.length && args[i].startsWith("-")) {
307 if(arg.equals("-m")) {
308 if(i < args.length) {
309 km.max_nclusters = new Integer(args[i++]).intValue();
311 } else if(arg.equals("-n")) {
312 if(i < args.length) {
313 km.min_nclusters = new Integer(args[i++]).intValue();
315 } else if(arg.equals("-t")) {
316 if(i < args.length) {
317 km.threshold = (float) Double.parseDouble(args[i++]);
319 } else if(arg.equals("-i")) {
320 if(i < args.length) {
321 km.filename = args[i++];
323 } else if(arg.equals("-b")) {
324 if(i < args.length) {
325 km.isBinaryFile = new Integer(args[i++]).intValue();
327 } else if(arg.equals("-z")) {
328 km.use_zscore_transform=0;
329 } else if(arg.equals("-nthreads")) {
330 if(i < args.length) {
331 km.nthreads = new Integer(args[i++]).intValue();
333 } else if(arg.equals("-h")) {
335 } else if(arg.equals("-v")){
336 km.validationTest=true;
339 if(km.nthreads == 0 || km.filename == null) {
345 * The usage routine which describes the program options.
347 public void usage() {
348 System.out.println("usage: ./kmeans -m <max_clusters> -n <min_clusters> -t <threshold> -i <filename> -nthreads <threads>\n");
349 System.out.println( " -i filename: file containing data to be clustered\n");
350 System.out.println( " -b input file is in binary format\n");
351 System.out.println( " -m max_clusters: maximum number of clusters allowed\n");
352 System.out.println( " -n min_clusters: minimum number of clusters allowed\n");
353 System.out.println( " -z : don't zscore transform data\n");
354 System.out.println( " -t threshold : threshold value\n");
355 System.out.println( " -nthreads : number of threads\n");
360 * Read attributes from the input file into an array
362 public static void readFromFile(FileInputStream inputFile, String filename, float[][] buf, int MAX_LINE_LENGTH) {
363 inputFile = new FileInputStream(filename);
367 byte b[] = new byte[MAX_LINE_LENGTH];
369 byte oldbytes[]=null;
373 while ((n = inputFile.read(b)) != 0) {
376 if (oldbytes!=null) {
387 byte newbytes[]=new byte[x+oldbytes.length];
388 boolean isnumber=false;
389 for(int ii=0;ii<oldbytes.length;ii++) {
390 if (oldbytes[ii]>='0'&&oldbytes[ii]<='9')
392 newbytes[ii]=oldbytes[ii];
394 for(int ii=0;ii<x;ii++) {
395 if (b[ii]>='0'&&b[ii]<='9')
397 newbytes[ii+oldbytes.length]=b[ii];
400 x++; //skip past space or cr
403 buf[i][j]=(float)Double.parseDouble(new String(newbytes, 0, newbytes.length));
417 boolean isnumber=false;
419 if ((b[y]>='0')&&(b[y]<='9'))
429 //need to continue for another read
430 oldbytes=new byte[y-x];
431 for(int ii=0;ii<(y-x);ii++)
432 oldbytes[ii]=b[ii+x];
436 //otherwise x is beginning of character string, y is end
439 buf[i][j]=(float)Double.parseDouble(new String(b,x,y-x));
444 i++;//skip to next line
445 j = -1;//don't store line number
446 x=y;//skip to end of number
447 x++;//skip past return
449 x=y;//skip to end of number
450 x++;//skip past space
458 /* =============================================================================
462 * =============================================================================