/* * WekaFindInstanceKNN.java * Copyright (C) 2011 New Zealand Digital Library, http://www.nzdl.org * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.greenstone.gsdl3.util; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import weka.core.converters.ConverterUtils.DataSource; import weka.core.neighboursearch.LinearNNSearch; import weka.core.neighboursearch.NearestNeighbourSearch; //import weka.core.neighboursearch.KDTree; // Based on StackOverflow: // https://stackoverflow.com/questions/31350506/how-to-calculate-the-nearest-neighbors-using-weka-from-the-command-line // The following was also useful as a reference: // https://waikato.github.io/weka-blog/posts/2018-10-08-making-a-weka-classifier/ public class WekaFindInstanceKNN { public static Instances loadDataset(String input_filename) { Instances instances = null; try { DataSource source = new DataSource(input_filename); instances = source.getDataSet(); } catch (Exception e) { e.printStackTrace(); } return instances; } public static NearestNeighbourSearch initKNN(Instances instances) { LinearNNSearch knn = new LinearNNSearch(instances); return knn; } public static void printNearestKNN(Instance sample_instance, Instances nearest_instances, int k_nearest) { try { //cycle through the instances and printout the nearestneighbors System.err.println("\n" + sample_instance); for(int i =0; i