Skip to content

Instantly share code, notes, and snippets.

@leonidkuznetsov18
Created December 18, 2022 20:17
Show Gist options
  • Save leonidkuznetsov18/4ad51c815cbefcbc3eba95dcca07134e to your computer and use it in GitHub Desktop.
Save leonidkuznetsov18/4ad51c815cbefcbc3eba95dcca07134e to your computer and use it in GitHub Desktop.
KNN algorithm by lodash
const outputs = [
[10, .5, 16, 1],
[200, .5, 16, 4],
[350, .5, 16, 4],
[600, .5, 16, 5],
]
const predictionPoint = 300;
const k = 3
function distance(point) {
return Math.abs(point - predictionPoint)
}
_.chain(outputs)
.map(row => [distance(row[0]), row[3]])
.sortBy(row => row[0])
.slice(0, k)
.countBy(row => row[1])
.toPairs()
.sortBy(row => row[1])
.last()
.first()
.parseInt()
.value()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment