tensorflow - 我转换后的 tensorflow 迁移学习模型总是在 Tensorflow JS 中返回相同的结果

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

我创建了一个模型,该模型将 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]

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

最佳答案

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

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 属性仍然是整个 block 执行之前的值。

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

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

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

关于tensorflow - 我转换后的 tensorflow 迁移学习模型总是在 Tensorflow JS 中返回相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68574893/

相关文章:

python - Tensorflow 中的预定采样

machine-learning - keras.fit() 重新初始化权重

tensorflow - 无法在 GPU 上训练 Keras 卷积网络

statistics - Tensorflow.js 找到张量的中位数

javascript - 为什么我的神经网络训练方法没有被调用? (ML5.JS)

c++ - 关闭 session 后 Tensorflow 1.8 内存仍保留在 GPU 上

javascript - Tensorflow JS - 将张量转换为 JSON,然后再转换回张量

deep-learning - 使用某些卡住模块训练模型时是否应该停用 Dropout?

deep-learning - 如何选择用于我的模型的预训练权重?