【问题标题】:My converted tensorflow Transfer Learning model always returns same results in Tensorflow JS我转换后的 tensorflow 迁移学习模型总是在 Tensorflow JS 中返回相同的结果
【发布时间】:2021-10-05 01:12:42
【问题描述】:

我创建了一个模型,该模型将 Mobilenet V2 应用于 Google colab 中的卷积基础层。然后我使用以下命令对其进行了转换:

path_to_h5 = working_dir + '/Tensorflow_PY_Model/SavedModel.h5'
path_tfjs = working_dir + '/TensorflowJS'

!tensorflowjs_converter --input_format keras \
                        {path_to_h5} \
                       {path_tfjs}

我用一张图片来测试对两者进行分类。在 python 中,我使用下面的代码进行预测:

from google.colab import files
from io import BytesIO
from PIL import Image
import matplotlib.pyplot as plt

uploaded = files.upload()
last_uploaded = list(uploaded.keys())[-1]
im = Image.open(BytesIO(uploaded[last_uploaded]))

im = im.resize(size=(224,224))
img = np.array(im)
img = img / 255.0
prediction1 = model.predict(img[None,:,:])
print(prediction1)

上面的代码返回这个数组:

[6.1504150e-05 4.8508531e-11 5.1813848e-15 2.1887154e-12 9.9993849e-01
  8.4171114e-13 1.4638757e-08 3.4268971e-14 7.5719299e-15 1.0649443e-16]]

之后,我尝试使用以下代码在 Javascript 中进行预测:

async function predict(image) {
    var model = await tf.loadLayersModel('./TFJs/model.json');
    let predictions = model.predict(preprocessImage(image)).dataSync(); 
    console.log(predictions);

    return results;
}

function preprocessImage(image) {
    let tensor = tf.browser.fromPixels(image);
    const resizedImage = tensor.resizeNearestNeighbor([224,224]);
    const batchedImage = resizedImage.expandDims(0);
    return batchedImage.toFloat().div(tf.scalar(255)).sub(tf.scalar(1));
}

document.querySelector('input[type="file"]').addEventListener("change", async function () {
        if (this.files && this.files[0]) {
            img = document.getElementById("uploaded-img");
            img.onload = () => {
                URL.revokeObjectURL(img.src); // no longer needed, free memory
            };
            img.src = URL.createObjectURL(this.files[0]);
            predictionResult = await predict(model, img);
            displayResult(predictionResult);
        }
    });

但是,使用与我在 Python 上进行预测时使用的图像相同的图像,它会返回此结果,并且无论我更改图像,它永远不会改变

Float32Array(10) [0.9489052295684814, 0.0036257198080420494, 0.000009185552698909305,
0.000029705168344662525, 0.04141413792967796, 1.4301890782775217e-9, 0.006003820803016424,
2.8357267645162665e-9, 0.000011812648153863847, 4.0659190858605143e-7]

那么如何解决这个问题呢?我还应该做什么?提前感谢您的回答和建议!

【问题讨论】:

  • 呸,这是个烦人的问题。对于相同的图像,您确定预处理是相同的吗?
  • 我认为它已经相同了,我检查了预处理的形状结果,它与 JS 中的 ([1,224,224,3]) 完全相同,同时在 python 中它是 [None, 224, 224, 3].
  • 是的,形状有效。但也许图像每次都是一样的,或者是一些奇怪的行为。图像张量本身是否相同?
  • 谢谢。我发现我的网络应用收到的图片全是 0,所以这就是它行为错误的原因。
  • 哈哈,知道了,我自己也做过同样的事情。没问题,祝你好运。

标签: tensorflow tensorflow.js transfer-learning tensorflowjs-converter


【解决方案1】:

在调试了一些可能的原因后,我意识到问题出在这段代码中:

document.querySelector('input[type="file"]').addEventListener("change", async function () {
        if (this.files && this.files[0]) {
            img = document.getElementById("uploaded-img");
            img.onload = () => {
                URL.revokeObjectURL(img.src); // no longer needed, free memory
            };
            img.src = URL.createObjectURL(this.files[0]);
            predictionResult = await predict(model, img);
            displayResult(predictionResult);
        }
    });

首先,我想让它自动化,这样它就可以立即显示选择的图像并在管道中进行预测。但这无法完成,因为imgsrc 属性仍将与整个块执行前的值相同。

在我的例子中,它执行了整个块,直到预测和结果,然后上传的和错误的预测结果完全出现。所以我最后做了一个改变,比如添加一个仅用于预测的按钮,从该块中取出预测线并将它们放入另一个函数中。最后效果很好。

document.querySelector('input[type="file"]').addEventListener("change", async function () {
        if (this.files && this.files[0]) {
            img = document.getElementById("uploaded-img");
            img.onload = () => {
                URL.revokeObjectURL(img.src); // no longer needed, free memory
            };
            img.src = URL.createObjectURL(this.files[0]);
        }
    });

document.querySelector('#predict-btn').addEventListener("click", async function ()  {
    img = document.getElementById("uploaded-img");
    predictionResult = await predict(model, img);
    displayResult(predictionResult);
});

好吧,我仍然很好奇我是否可以将这些功能放入管道流程中,这样就只有一个上传按钮,其余工作由系统完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2020-10-31
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多