项目作者: pratikpc

项目描述 :
A Tensorflow.JS Library for Calculating KMeans
高级语言: TypeScript
项目地址: git://github.com/pratikpc/tf-kmeans.git
创建时间: 2020-04-15T09:38:47Z
项目社区:https://github.com/pratikpc/tf-kmeans

开源协议:MIT License

下载


TF-KMeans

Description

A Simple JavaScript Library to make it easy for people to use KMeans algorithms with Tensorflow JS.

The library was born out of another project in which except KMeans, our code completely depended on TF.JS

As such, moving to TF.JS helped standardise our code base substantially and reduce dependency on other libraries

Sample Code

  1. const KMeans = require("tf-kmeans");
  2. const tf = require("@tensorflow/tfjs");
  3. const kmeans = new KMeans.default({
  4. k: 2,
  5. maxIter: 30,
  6. distanceFunction: KMeans.default.EuclideanDistance
  7. });
  8. const dataset = tf.tensor([[2, 2, 2], [5, 5, 5], [3, 3, 3], [4, 4, 4], [7, 8, 7]]);
  9. const predictions = kmeans.Train(
  10. dataset
  11. );
  12. console.log("Assigned To ", predictions.arraySync());
  13. console.log("Centroids Used are ", kmeans.Centroids().arraySync());
  14. console.log("Prediction for Given Value is");
  15. kmeans.Predict(tf.tensor([2, 3, 2])).print();

You can use the Asynchronous TrainAsync if you want to use an asynchronous callback function

  1. const kmeans = new KMeans.default({
  2. k: 3,
  3. maxIter: 30,
  4. distanceFunction: KMeans.default.EuclideanDistance
  5. });
  6. const dataset = tf.tensor([[2, 2, 2], [5, 5, 5], [3, 3, 3], [4, 4, 4], [7, 8, 7]]);
  7. console.log("\n\nAsync Test");
  8. const predictions = await kmeans.TrainAsync(
  9. dataset,
  10. // Called At End of Every Iteration
  11. // This function is Asynchronous
  12. async(iter, centroid, preds)=>{
  13. console.log("===");
  14. console.log("Iteration Count", iter);
  15. console.log("Centroid ", await centroid.array());
  16. console.log("Prediction ", await preds.array());
  17. console.log("===");
  18. // You could instead use TFVIS for Plotting Here
  19. }
  20. );

Functions

  1. Constructor

    Takes 3 Optional parameters

    1. k:- Number of Clusters
    2. maxIter:- Max Iterations
    3. distanceFunction:- The Distance function Used
      1. Currently only Eucledian Distance Provided
  2. Train

    Takes Dataset as Parameter

    Performs Training on This Dataset

    Sync callback function is optional

  3. TrainAsync

    Takes Dataset as Parameter

    Performs Training on This Dataset

    Also takes async callback function called at the end of every iteration

  4. Centroids

    Returns the Centroids found for the dataset on which KMeans was Trained

  5. Predict

    Performs Predictions on the data Provided as Input

PEER DEPENDENCIES

  1. TensorFlow.JS

Typings

As the code is originally written in TypeScript, Type Support is provided out of the box

Contact Me

You could contact me via LinkedIn
You could file issues or add features via Pull Requests on GitHub