张量流js预测的预测问题

时间:2020-01-06 14:36:55

标签: javascript tensorflow tensorflow2.0 tensorflow.js

我的tensorflow js模型有问题,我遵循了课程(link to the course) 在这里我学会了创建一个张量流模型,并且一切正常,但是该课程没有显示如何使用该模型,所以我自己开发了这一部分,但是每次我尝试预测一个数字时,我都会得到相同的结果(2),不知道为什么,而且我不知道要解决这个问题,所以我希望有人可以帮助我解决这个问题并提供帮助。

代码的客人部分在这里:

GmailApp

该项目的GitHub在这里:github

提前感谢

1 个答案:

答案 0 :(得分:1)

仅在完成加载后才能预测图像

const img = document.getElementById('imageResult')
 img.onload = function(){
 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);
} 

此外,初始画布背景是透明的,因为尚未设置。转换为张量时,透明背景变为黑色。笔触样式也为黑色。黑色背景上的黑色图像...无论绘制什么,都会导致相同的张量。

要么更改了笔触样式,要么填充了画布背景,或者两者都填充(但出于上述相同的原因,两者不应具有相同的颜色)。

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;

    // canvas with white background
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvas.width, canvas.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");
}