source: gs3-extensions/mars-src/trunk/src/java/org/greenstone/gsdl3/util/WekaCLFindNN.java@ 36864

Last change on this file since 36864 was 35182, checked in by davidb, 3 years ago

Some useful code from StackOverflow

File size: 1.4 KB
Line 
1import weka.core.Instances;
2import weka.core.converters.ConverterUtils.DataSource;
3import weka.core.neighboursearch.LinearNNSearch;
4
5// Sourced from:
6// https://stackoverflow.com/questions/31350506/how-to-calculate-the-nearest-neighbors-using-weka-from-the-command-line
7
8public class WekaCLFindNN
9{
10 public static void main(String[] args) throws Exception
11 {
12
13 //report that the code is running
14 System.out.println("Weka Command Line Find Nearest " + args[0] + " Neighbors for each Instance in " + args[1]);
15
16 //setup datasources, grab instances, and calculate the nearest neighbors
17 DataSource source = new DataSource(""+args[1]);
18 Instances instances = source.getDataSet();
19 weka.core.neighboursearch.LinearNNSearch knn = new LinearNNSearch(instances);
20
21 //cycle through the dataset and get instances for the nearestneighbors
22 for (int j=0; j<instances.numInstances(); j++) {
23 Instances nearestInstances= knn.kNearestNeighbours(instances.instance(j), Integer.parseInt(args[0]));
24
25 //cycle through the instances and printout the nearestneighbors
26 System.out.println("\n\n" + instances.instance(j));
27 for(int i =0; i<Integer.parseInt(args[0]); i++) {
28 System.out.println("\n\t" + nearestInstances.instance(i));
29
30 }
31
32 }
33
34 //close the code
35 System.out.println("\n"+"Nearest Neighbors found"); // Display the string.
36 }
37}
Note: See TracBrowser for help on using the repository browser.