-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
39 lines (33 loc) · 1.12 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
require('@tensorflow/tfjs-node');
const tf = require('@tensorflow/tfjs');
const loadCSV = require('./load-csv');
function knn(features, labels, predictionPoint, k) {
const { mean, variance } = tf.moments(features, 0);
const scaledPrediction = predictionPoint.sub(mean).div(variance.pow(0.5))
return features
.sub(mean)
.div(variance.pow(0.5))
.sub(scaledPrediction)
.pow(2)
.sum(1)
.pow(0.5)
.expandDims(1)
.concat(labels, 1)
.unstack()
.sort((a, b) => a.get(0) > b.get(0) ? 1 : -1)
.slice(0, k)
.reduce((acc, pair) => acc + pair.get(1), 0) / k
}
let { features, labels, testFeatures, testLabels } = loadCSV('kc_house_data.csv', {
shuffle: true,
splitTest: 10,
dataColumns: ['lat', 'long', 'sqft_lot', 'sqft_living'],
labelColumns: ['price']
});
features = tf.tensor(features);
labels = tf.tensor(labels);
testFeatures.forEach((testPoint, i) => {
const result = knn(features, labels, tf.tensor(testPoint), 10);
const err = (testLabels[i][0] - result) / testLabels[i][0];
console.log('Error', err * 100);
});