Created
July 7, 2011 15:08
-
-
Save actsasgeek/1069715 to your computer and use it in GitHub Desktop.
Modification of 1-NN algorithm to handle kNN
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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