ml5js / ml5-library

Friendly machine learning for the web! 🤖
https://ml5js.org
Other
6.46k stars 904 forks source link

retrieve json from KNN Classifier instead of saving #516

Open micuat opened 5 years ago

micuat commented 5 years ago

→ Description 📝

getting json object instead of saving directly to a file would be helpful when sending data to node.js, for example.

→ Screenshots 🖼

(Any relevant screenshots, sketches, or helpful concept diagrams)

I'm using this makeshift for now, but it should be included in the ml5 library (I think).

const dataset = knnClassifier.knnClassifier.getClassifierDataset();
if (knnClassifier.mapStringToIndex.length > 0) {
  Object.keys(dataset).forEach((key) => {
    if (knnClassifier.mapStringToIndex[key]) {
      dataset[key].label = knnClassifier.mapStringToIndex[key];
    }
  });
}
const tensors = Object.keys(dataset).map((key) => {
  const t = dataset[key];
  if (t) {
    return t.dataSync();
  }
  return null;
});
console.log({dataset, tensors});

→ Helpful Information 🦄

A list of relevant information for this issue. This will help people navigate the project and offer some clues of where to start. Depending on the nature of this issue, important and helpful information might include:

micuat commented 5 years ago

and of course loading

socket.on('lastModel', (data) => {
  // console.log(data)

  if (data) {
    const { dataset, tensors } = data;
    knnClassifier.mapStringToIndex = Object.keys(dataset).map(key => dataset[key].label);
    const tensorsData = tensors
      .map((tensor, i) => {
        if (tensor) {
          const values = Object.keys(tensor).map(v => tensor[v]);
          return ml5.tf.tensor(values, dataset[i].shape, dataset[i].dtype);
        }
        return null;
      })
      .reduce((acc, cur, j) => {
        acc[j] = cur;
        return acc;
      }, {});
    knnClassifier.knnClassifier.setClassifierDataset(tensorsData);
  }
});
oveddan commented 5 years ago

Yes this would be great; with the json you could even save the data to the cloud on something like firebase.