Last active
September 21, 2019 18:28
-
-
Save gabrielrufino/10a61915a5d306d0e0f846af2a4eb6f8 to your computer and use it in GitHub Desktop.
KNN with tensorflow
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
[ | |
{ | |
"x": 1, | |
"y": 1, | |
"label": "A" | |
}, | |
{ | |
"x": 1, | |
"y": 2, | |
"label": "A" | |
}, | |
{ | |
"x": 2, | |
"y": 1, | |
"label": "A" | |
}, | |
{ | |
"x": 2, | |
"y": 2, | |
"label": "A" | |
}, | |
{ | |
"x": 1, | |
"y": 6, | |
"label": "B" | |
}, | |
{ | |
"x": 2, | |
"y": 6, | |
"label": "B" | |
}, | |
{ | |
"x": 5, | |
"y": 5, | |
"label": "C" | |
}, | |
{ | |
"x": 5, | |
"y": 6, | |
"label": "C" | |
}, | |
{ | |
"x": 6, | |
"y": 5, | |
"label": "C" | |
}, | |
{ | |
"x": 6, | |
"y": 6, | |
"label": "C" | |
} | |
] |
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
const tf = require('@tensorflow/tfjs-node') | |
const data = require('./data.json') | |
const xs = tf.tensor(data.map(d => d.x)) | |
const ys = tf.tensor(data.map(d => d.y)) | |
const labels = data.map(d => d.label) | |
const xInput = tf.scalar(Math.random() * xs.max().dataSync()) | |
const yInput = tf.scalar(Math.random() * ys.max().dataSync()) | |
const distances = xInput | |
.sub(xs) | |
.square() | |
.add( | |
yInput | |
.sub(ys) | |
.square() | |
) | |
.sqrt() | |
const minorDistance = distances.min().dataSync()[0] | |
const index = distances.dataSync().indexOf(minorDistance) | |
console.table({ | |
x: xInput.arraySync(), | |
y: yInput.arraySync(), | |
label: labels[index] | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment