Skip to content

Instantly share code, notes, and snippets.

@actsasgeek
Created July 7, 2011 15:08
Show Gist options
  • Select an option

  • Save actsasgeek/1069715 to your computer and use it in GitHub Desktop.

Select an option

Save actsasgeek/1069715 to your computer and use it in GitHub Desktop.
Modification of 1-NN algorithm to handle kNN
class NearestNeighbor( library: List[Instance]) {
def classify( query: Instance, k: Int = 3): Instance = {
val distanceMeasurements = library.map( example => (query.distanceTo( example), example))
val sortedDistanceMeasurements = distanceMeasurements.sortWith(( e1, e2) => ( e1._1 - e2._1) < 0)
val kNearestExamples = sortedDistanceMeasurements.take( k)
val groupedExamples = kNearestExamples.groupBy( x => x._2.classLabel).toList
val sortedClassesByCounts = groupedExamples.map { kv => (kv._1, kv._2.length)}.sortWith( _._2 > _._2)
val classWithMostVotes = sortedClassesByCounts.head
query.assignClassLabel( classWithMostVotes._1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment