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;
143 use_zscore_transform = 1;
144 threshold = (float) 0.001;
148 public KMeans(int threadid, GlobalArgs g_args) {
149 this.threadid = threadid;
150 this.g_args = g_args;
155 Barrier.enterBarrier();
156 Normal.work(threadid, g_args);
157 Barrier.enterBarrier();
161 /* =============================================================================
163 * =============================================================================
165 public static void main(String[] args) {
167 int MAX_LINE_LENGTH = 1000000; /* max input is 400000 one digit input + spaces */
170 * Read options fron the command prompt
172 KMeans kms = new KMeans();
173 KMeans.parseCmdLine(args, kms);
174 nthreads = kms.nthreads;
176 /* Initiate Barriers */
177 Barrier.setBarrier(nthreads);
179 if (kms.max_nclusters < kms.min_nclusters) {
180 System.out.println("Error: max_clusters must be >= min_clusters\n");
185 float[][] attributes;
186 int numAttributes = 0;
190 * From the input file, get the numAttributes (columns in txt file) and numObjects (rows in txt file)
192 if (kms.isBinaryFile == 1) {
193 System.out.println("TODO: Unimplemented Binary file option\n");
197 FileInputStream inputFile = new FileInputStream(kms.filename);
198 byte b[] = new byte[MAX_LINE_LENGTH];
200 while ((n = inputFile.read(b)) != 0) {
201 for (int i = 0; i < n; i++) {
207 inputFile = new FileInputStream(kms.filename);
209 if((line = inputFile.readLine()) != null) {
211 boolean prevWhiteSpace = true;
212 while(index < line.length()) {
213 char c = line.charAt(index++);
214 boolean currWhiteSpace = Character.isWhitespace(c);
215 if(prevWhiteSpace && !currWhiteSpace){
218 prevWhiteSpace = currWhiteSpace;
223 /* Ignore the first attribute: numAttributes = 1; */
224 numAttributes = numAttributes - 1;
225 System.out.println("numObjects= " + numObjects + " numAttributes= " + numAttributes);
227 /* Allocate new shared objects and read attributes of all objects */
228 buf = new float[numObjects][numAttributes];
229 attributes = new float[numObjects][numAttributes];
230 KMeans.readFromFile(inputFile, kms.filename, buf, MAX_LINE_LENGTH);
231 System.out.println("Finished Reading from file ......");
234 * The core of the clustering
237 int[] cluster_assign = new int[numObjects];
239 int len = kms.max_nclusters - kms.min_nclusters + 1;
241 KMeans[] km = new KMeans[nthreads];
242 GlobalArgs g_args = new GlobalArgs();
243 g_args.nthreads = nthreads;
245 /* Create and Start Threads */
246 for(int i = 1; i<nthreads; i++) {
247 km[i] = new KMeans(i, g_args);
250 for(int i = 1; i<nthreads; i++) {
254 System.out.println("Finished Starting threads......");
256 for (int i = 0; i < nloops; i++) {
258 * Since zscore transform may perform in cluster() which modifies the
259 * contents of attributes[][], we need to re-store the originals
261 for(int x = 0; x < numObjects; x++) {
262 for(int y = 0; y < numAttributes; y++) {
263 attributes[x][y] = buf[x][y];
267 Cluster.cluster_exec(nthreads,
270 attributes, // [numObjects][numAttributes]
271 kms, //main class that holds users inputs from command prompt and output arrays that need to be filled
272 g_args); // Global arguments common to all threads
275 System.out.println("Printing output......");
276 System.out.println("Best_nclusters= " + kms.best_nclusters);
278 /* Output: the coordinates of the cluster centres */
280 for (int i = 0; i < kms.best_nclusters; i++) {
281 System.out.print(i + " ");
282 for (int j = 0; j < numAttributes; j++) {
283 System.out.print(kms.cluster_centres[i][j] + " ");
285 System.out.println("\n");
289 System.out.println("Finished......");
293 public static void parseCmdLine(String args[], KMeans km) {
296 while (i < args.length && args[i].startsWith("-")) {
299 if(arg.equals("-m")) {
300 if(i < args.length) {
301 km.max_nclusters = new Integer(args[i++]).intValue();
303 } else if(arg.equals("-n")) {
304 if(i < args.length) {
305 km.min_nclusters = new Integer(args[i++]).intValue();
307 } else if(arg.equals("-t")) {
308 if(i < args.length) {
309 km.threshold = (float) Double.parseDouble(args[i++]);
311 } else if(arg.equals("-i")) {
312 if(i < args.length) {
313 km.filename = args[i++];
315 } else if(arg.equals("-b")) {
316 if(i < args.length) {
317 km.isBinaryFile = new Integer(args[i++]).intValue();
319 } else if(arg.equals("-z")) {
320 if(i < args.length) {
323 } else if(arg.equals("-nthreads")) {
324 if(i < args.length) {
325 km.nthreads = new Integer(args[i++]).intValue();
327 } else if(arg.equals("-h")) {
331 if(km.nthreads == 0 || km.filename == null) {
337 * The usage routine which describes the program options.
339 public void usage() {
340 System.out.println("usage: ./kmeans -m <max_clusters> -n <min_clusters> -t <threshold> -i <filename> -nthreads <threads>\n");
341 System.out.println( " -i filename: file containing data to be clustered\n");
342 System.out.println( " -b input file is in binary format\n");
343 System.out.println( " -m max_clusters: maximum number of clusters allowed\n");
344 System.out.println( " -n min_clusters: minimum number of clusters allowed\n");
345 System.out.println( " -z : don't zscore transform data\n");
346 System.out.println( " -t threshold : threshold value\n");
347 System.out.println( " -nthreads : number of threads\n");
352 * Read attributes from the input file into an array
354 public static void readFromFile(FileInputStream inputFile, String filename, float[][] buf, int MAX_LINE_LENGTH) {
355 inputFile = new FileInputStream(filename);
359 byte b[] = new byte[MAX_LINE_LENGTH];
361 byte oldbytes[]=null;
364 while ((n = inputFile.read(b)) != 0) {
368 if (oldbytes!=null) {
374 byte newbytes[]=new byte[x+oldbytes.length];
375 for(int ii=0;ii<oldbytes.length;ii++)
376 newbytes[ii]=oldbytes[ii];
377 for(int ii=0;ii<x;ii++)
378 newbytes[ii+oldbytes.length]=b[ii];
379 x++; //skip past space
381 buf[i][j]=(float)Double.parseDouble(new String(newbytes, 0, newbytes.length));
395 x=y;//push end to current character
399 //need to continue for another read
400 oldbytes=new byte[y-x];
401 for(int ii=0;ii<(y-x);ii++)
402 oldbytes[ii]=b[ii+x];
406 //otherwise x is beginning of character string, y is end
409 buf[i][j]=(float)Double.parseDouble(new String(b,x,y-x));
411 x=y;//skip to end of number
412 x++;//skip past space
420 /* =============================================================================
424 * =============================================================================