Проблема при прогнозировании по тензорному потоку js прогноз - PullRequest
2 голосов
/ 06 января 2020

У меня проблема с моей моделью тензорного потока js, я прошел курс ( ссылка на курс ), где я научился создавать модель тензорного потока, и все работало нормально, но курс не показывает как использовать модель, чтобы я разработал эту часть, но каждый раз, когда я пытаюсь предсказать число, я получаю один и тот же результат (2), я не знаю, почему, и у меня нет знаний, чтобы это исправить, поэтому я надеюсь, что кто-то может помочь мне исправить это и предоставить объяснение.

Гостевая часть кода находится здесь:

    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);

GitHub проекта находится здесь: github

заранее спасибо

1 Ответ

1 голос
/ 06 января 2020

Изображение должно быть предсказано только после завершения загрузки

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");
}
...