Untitled

 avatar
unknown
plain_text
a year ago
1.9 kB
29
Indexable
require('@tensorflow/tfjs-node');   //running tfjs on laptop cpu
const tf = require('@tensorflow/tfjs'); //require in Tensorflow JS lib
const  Users = require('../../mongodb/models/users')
const Posts = require('../../mongodb/models/posts')

function knn(features, labels, predictionPoint, k) { 
features = tf.tensor(features);
labels = tf.tensor(labels);
    const {mean, variance} = tf.moments(features, 0);
    const scaledPrediction = predictionPoint.sub(mean).div(variance.pow(0.5))    //Scaled Prediction const for standardization
    const apple = features.sub(mean)
    /* Step 0 - Standarization of features for  */
        .div(variance.pow(0.5))
    /* Step 1 - Find Distance between features & prediction point features */
        .sub(scaledPrediction)	//Broadcasting operation
        .pow(2)	//Elementwise operation to square each element
        .sum(1) //Sums along x(1)-axis
        .sqrt()	//Elementwise operation to take power of .5 = sqrt of each element
    /* Step 2 - Sort from lowest distance to greatest distance */
        .expandDims(1) //We expand dimensions of distances tensor across the x-axis to get the shape of [4,1], the same as the labels distance
        .concat(labels, 1) //We concatenate labels to distances across the x-axis so they are linked by the same indices in one tensor
        .unstack() //We unstack our 1 tensor into 1 Vanilla JS array containing multiple tensors
    /* After unstacking our tensor, we are dealing with vanilla JS array and we can ONLY use vanilla JS methods from this point on */
        .sort((a,b) => a.get(0) > b.get(0) ? 1 : -1) //Sorting function tp sprt tensors in order of least to greatest distance
        /* Step 3 - Average the label value of the top k records */ 
        .slice(0, k)//Get Top k records
 
return apple
}
module.exports = knn
Editor is loading...
Leave a Comment