I've been trying to put together a simple example of Tensorflow.js and appear to have the code below all working apart from when I do the final predict, when I always get NaN returned.
What I was looking for was some sort of example where data when into a model and some predictions came out, and I couldn't really find anything suitable from the Tensorflow.js examples, however the code in this video seemed just what I wanted:
This is training the model where simpleInput and simpleOutput are just one dimensional arrays.
function ML_RunTensor2(simpleInput, simpleOutput) {
try {
// define a model for linear regression
linearModel = tf.sequential();
linearModel.add(tf.layers.dense({ units: 1, inputShape: [1] }));
// prepare the model for training: specify the loss and the optimizer
linearModel.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });
// training data
const xs = tf.tensor1d(simpleInput);
const ys = tf.tensor1d(simpleOutput);
// train
linearModel.fit(xs, ys);
} catch (e) {
debugger;
console.log(e.Message);
}
}
Then ones the model is trained I call this for a prediction:
function ML_PredictClicked() {
var inputPrediction = jQuery('#' + predictionInput).val();
var inputPredictionNumber = parseFloat(inputPrediction);
const output = linearModel.predict(tf.tensor2d([inputPredictionNumber], [1, 1]));
var outputPrediction = Array.from(output.dataSync())[0];
jQuery('#' + predictionOutput).val(outputPrediction);
}
Here is the code in the debugger - I tried just output.dataSync() as well.
