Skip to content

Instantly share code, notes, and snippets.

@faisal-w
Created October 13, 2014 13:39
Show Gist options
  • Save faisal-w/77495b78735255fc9e88 to your computer and use it in GitHub Desktop.
Save faisal-w/77495b78735255fc9e88 to your computer and use it in GitHub Desktop.
SimpleKMeans cluster classification example using Weka library.
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
import weka.clusterers.SimpleKMeans;
import weka.clusterers.ClusterEvaluation;
import java.io.File;
import java.io.FileWriter;
/**
* Simple K-Means Clusterer using Weka library
*
* @Author Faisal Wirakusuma, University of Manchester
*
*/
public class MyKMeansClusterer{
/**
* Expects an ARFF file as first argument.
*
* @param args the commandline arguments
* @throws Exception if something goes wrong
*/
public static void main(String[] args) throws Exception{
//load data from arguments
ArffLoader loader = new ArffLoader();
loader.setFile(new File(args[0]));
Instances structure = loader.getDataSet();
FileWriter writer = new FileWriter("lab2_2-ii_result.csv");
writer.append("NumClusters");
writer.append(',');
writer.append("SSE");
writer.append('\n');
for(int i = 2; i<=50; i++){
SimpleKMeans mySKMeans = new SimpleKMeans();
mySKMeans.setPreserveInstancesOrder(true);
mySKMeans.setMaxIterations(500);
mySKMeans.setNumClusters(i);
mySKMeans.setSeed(10);
mySKMeans.buildClusterer(structure);
//ClusterEvaluation eval = new ClusterEvaluation();
//eval.setClusterer(mySKMeans);
//eval.evaluateClusterer(new Instances(structure));
//System.out.println(structure);
//System.out.println("SSE "+i+" : "+mySKMeans.getSquaredError());
writer.append(i+"");
writer.append(',');
writer.append(mySKMeans.getSquaredError()+"");
writer.append('\n');
mySKMeans = null;
}
writer.flush();
writer.close();
}
}
@arch28
Copy link

arch28 commented Jun 17, 2016

Hi,
When I am trying to run this, it is saying weka.core package does not exist..not sure, how to get this work.Any help would be appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment