I have a problem on my tensorflow js model, I followed a course (link to the course) where I learned to create a tensorflow model and everything worked fine but the course doesn't show how to use the model so I developped myself this part but every time I try to predict a number I got the same result (2), I don't know why and I don't have the knowledge to fix that so I hope someone could help me fix that and provide an explenation.
The guest part of the code is here :
function guessIt(){
let inputTensor = tf.browser.fromPixels(document.getElementById('imageResult'), 1)// imageResult is an <img/> tag
.reshape([1, 28, 28, 1])
.cast('float32');
let predictionResult = modelJson.predict(inputTensor).dataSync();
let recognizedDigit = predictionResult.indexOf(Math.max(...predictionResult));
console.log(recognizedDigit);
console.log(predictionResult);
}
var mousePressed = false;
var lastX, lastY;
var ctx;
//resize image with off-screen canvas
function imageToDataUri(img, width, height) {
// create an off-screen canvas
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
// set its dimension to target size
canvas.width = width;
canvas.height = height;
// draw source image into the off-screen canvas:
ctx.drawImage(img, 0, 0, width, height);
// encode image to data-uri with base64 version of compressed image
return canvas.toDataURL("image/png");
}
function InitThis() {
ctx = document.getElementById('sheet').getContext("2d");
$('#sheet').mousedown(function (e) {
mousePressed = true;
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
});
$('#sheet').mousemove(function (e) {
if (mousePressed) {
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
}
});
$('#sheet').mouseup(function (e) {
mousePressed = false;
let img = imageToDataUri(document.getElementById("sheet"),28,28)//resize it
let imgElement = document.getElementById("imageResult").setAttribute("src",img);// display it
guessIt();
});
$('#sheet').mouseleave(function (e) {
mousePressed = false;
});
}
function Draw(x, y, isDown) {
if (isDown) {
ctx.beginPath();
ctx.strokeStyle = "000000";
ctx.lineWidth = 9;
ctx.lineJoin = "round";
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke();
}
lastX = x; lastY = y;
}
function clearArea() {
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
document.getElementById("imageResult").setAttribute("src","");
}
// init the cancas
document.addEventListener('DOMContentLoaded', InitThis);
The GitHub of the project is here : github
thanks in advance