source: main/trunk/model-sites-dev/mars/src/java/org/greenstone/mars/WekaFindInstanceKNN.java@ 35228

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

Renamed

File size: 1.9 KB
Line 
1package org.greenstone.mars;
2
3import weka.core.Instance;
4import weka.core.Instances;
5import weka.core.converters.ConverterUtils.DataSource;
6
7import weka.core.neighboursearch.LinearNNSearch;
8import weka.core.neighboursearch.NearestNeighbourSearch;
9//import weka.core.neighboursearch.KDTree;
10
11// Based on StackOverflow:
12// https://stackoverflow.com/questions/31350506/how-to-calculate-the-nearest-neighbors-using-weka-from-the-command-line
13
14public class WekaCLFindNN
15{
16 public static void findNearestNN(NearestNeighbourSearch knn, Instance sample_instance, int k_nearest)
17 {
18 try {
19 Instances nearest_instances= knn.kNearestNeighbours(sample_instance, k_nearest);
20
21 //cycle through the instances and printout the nearestneighbors
22
23 System.out.println("\n" + sample_instance);
24 for(int i =0; i<k_nearest; i++) {
25 System.out.println("\t" + nearest_instances.instance(i));
26 }
27 }
28 catch (Exception e) {
29 e.printStackTrace();
30 }
31
32 }
33
34
35 public static void main(String[] args) throws Exception {
36
37 if (args.length != 2) {
38 System.err.println("Usage: k-nearest-num file.{arff,csv}");
39 System.exit(1);
40 }
41 String k_nearest_str = args[0];
42 String input_filename = args[1];
43
44 int k_nearest = Integer.parseInt(k_nearest_str);
45
46 System.out.println("Weka Command Line Find Nearest " + k_nearest_str
47 + " Neighbors for each Instance in " + input_filename);
48
49 DataSource source = new DataSource(input_filename);
50 Instances instances = source.getDataSet();
51
52 LinearNNSearch knn = new LinearNNSearch(instances);
53 //KDTree knn = new KDTree(instances);
54
55 //cycle through the dataset and get instances for the nearestneighbors
56
57 int num_instances = instances.numInstances();
58 for(int j=0; j<num_instances; j++) {
59 Instances nearestInstances= knn.kNearestNeighbours(instances.instance(j), k_nearest);
60
61 Instance sample_instance = instances.instance(j);
62 findNearestNN(knn,sample_instance,k_nearest);
63 }
64 }
65}
Note: See TracBrowser for help on using the repository browser.