Skip to content

Instantly share code, notes, and snippets.

@rofr
Created November 18, 2012 18:53
Show Gist options
  • Save rofr/4106828 to your computer and use it in GitHub Desktop.
Save rofr/4106828 to your computer and use it in GitHub Desktop.
NearestNeighborClassifier.classify()
/**
* Classify using the kNN algorithm
* @param item The item to classify
* @return The predicted class of the item
*/
public double classify(T item) {
int numItems = items.size();
// calculated distances in same order as the items list
double[] distances = new double[numItems];
//calculate the distance to each instance using a single thread
for (int i = 0; i < numItems; i++) {
distances[i] = distanceFunction.calculateDistance(item, items.get(i));
}
//Find the k nearest items
List<T> nearestItems = getNearestItems(distances);
double result = averageFunction.calculateAverage(nearestItems);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment