### Question:
NearestNeighbor { public List<NearestNeighborsResult> search() { INDArray input = points.slice(record.getInputIndex()); List<NearestNeighborsResult> results = new ArrayList<>(); if (input.isVector()) { List<DataPoint> add = new ArrayList<>(); List<Double> distances = new ArrayList<>(); tree.search(input, record.getK(), add, distances); if (add.size() != distances.size()) { throw new IllegalStateException( String.format("add.size == %d != %d == distances.size", add.size(), distances.size())); } for (int i=0; i<add.size(); i++) { results.add(new NearestNeighborsResult(add.get(i).getIndex(), distances.get(i))); } } return results; }  List<NearestNeighborsResult> search();  }### Answer:
@Test public void testNearestNeighbor() { double[][] data = new double[][] {{1, 2, 3, 4}, {1, 2, 3, 5}, {3, 4, 5, 6}}; INDArray arr = Nd4j.create(data); VPTree vpTree = new VPTree(arr, false); NearestNeighborRequest request = new NearestNeighborRequest(); request.setK(2); request.setInputIndex(0); NearestNeighbor nearestNeighbor = NearestNeighbor.builder().tree(vpTree).points(arr).record(request).build(); List<NearestNeighborsResult> results = nearestNeighbor.search(); assertEquals(1, results.get(0).getIndex()); assertEquals(2, results.size()); assertEquals(1.0, results.get(0).getDistance(), 1e-4); assertEquals(4.0, results.get(1).getDistance(), 1e-4); }
@Test public void testNearestNeighborInverted() { double[][] data = new double[][] {{1, 2, 3, 4}, {1, 2, 3, 5}, {3, 4, 5, 6}}; INDArray arr = Nd4j.create(data); VPTree vpTree = new VPTree(arr, true); NearestNeighborRequest request = new NearestNeighborRequest(); request.setK(2); request.setInputIndex(0); NearestNeighbor nearestNeighbor = NearestNeighbor.builder().tree(vpTree).points(arr).record(request).build(); List<NearestNeighborsResult> results = nearestNeighbor.search(); assertEquals(2, results.get(0).getIndex()); assertEquals(2, results.size()); assertEquals(-4.0, results.get(0).getDistance(), 1e-4); assertEquals(-1.0, results.get(1).getDistance(), 1e-4); }
@Test public void testFullSearch() throws Exception { int numRows = 1000; int numCols = 100; int numNeighbors = 42; INDArray points = Nd4j.rand(numRows, numCols); VPTree tree = new VPTree(points); INDArray query = Nd4j.rand(new int[] {1, numCols}); VPTreeFillSearch fillSearch = new VPTreeFillSearch(tree, numNeighbors, query); fillSearch.search(); List<DataPoint> results = fillSearch.getResults(); List<Double> distances = fillSearch.getDistances(); assertEquals(numNeighbors, distances.size()); assertEquals(numNeighbors, results.size()); }
@Test public void testDistances() { INDArray indArray = Nd4j.create(new float[][]{{3, 4}, {1, 2}, {5, 6}}); INDArray record = Nd4j.create(new float[][]{{7, 6}}); VPTree vpTree = new VPTree(indArray, "euclidean", false); VPTreeFillSearch vpTreeFillSearch = new VPTreeFillSearch(vpTree, 3, record); vpTreeFillSearch.search(); System.out.println(vpTreeFillSearch.getDistances()); }