【问题标题】:Why is my model giving different results in tensorflow.js and in Python Tensorflow?为什么我的模型在 tensorflow.js 和 Python Tensorflow 中给出不同的结果?
【发布时间】:2021-12-26 13:00:45
【问题描述】:

我正在尝试使笔记本“Predict Artist from Artworks”适应我自己的数据集。 Keras 模型已生成并转换为 Tensorflow 模型(使用 tensorflowjs_converter --input_format keras us.keras tfjs_model/us),我现在尝试将其与 tensorflow.js 一起使用,但使用 tensorflow.js 时预测结果不同(且错误)。

这是给出正确结果的预测 Python 代码:

from keras.preprocessing import image
from tensorflow import keras
import numpy as np

artists = ['CB', 'AT', 'TS', 'FG', 'DR']

model = keras.models.load_model('us.keras')

image_file = 'datasets/full/thumbnails3/fr/gb/fr_gb_0004p_001.jpg'
test_image = image.load_img(image_file, target_size=(224, 224))

# Predict artist
test_image = image.img_to_array(test_image)
test_image /= 255.
test_image = np.expand_dims(test_image, axis=0)

prediction = model.predict(test_image)
prediction_probability = np.amax(prediction)
prediction_idx = np.argmax(prediction)

print("Predicted artist = {}, probability of {:.2f} %"
      .format(artists[prediction_idx],  prediction_probability * 100))

结果是:

预测艺术家 = CB,概率为 22.62 %

但是,当使用 tensorflow.js 时,结果完全不同:

const tf = require("@tensorflow/tfjs");
const tfn = require("@tensorflow/tfjs-node");
const sharp = require('sharp');

const modelFile = tfn.io.fileSystem("tfjs_model/us/model.json");

const artists = ['CB', 'AT', 'TS', 'FG', 'DR']

tf.loadLayersModel(modelFile).then(model => {
    sharp('datasets/full/thumbnails3/fr/gb/fr_gb_0004p_001.jpg')
        .rotate()
        .resize(224, 224)
        .toBuffer().then(
            data => {
                let image = tfn.node.decodeImage(data, 0)
                image = tf.expandDims(image, 0);
                image = tf.cast(image, 'float32').div(255)
                const prediction = model.predict(image);
                prediction.array().then(([predictionArray]) => {
                    const predictionProbability = Math.max(...predictionArray);
                    const predictionIndex = predictionArray.indexOf(predictionProbability);
                    console.log(`Predicted artist = ${artists[predictionIndex]}, probability of ${predictionProbability * 100}%`)
                })
            }
        )
})

结果:

预测艺术家 = DR,概率为 37.461987137794495%

我的假设是我在 JS 代码中对尺寸或图像处理所做的事情是错误的,但我不知道是什么。

【问题讨论】:

  • 这肯定与预测前图像的处理方式有关。在 js 中,您在预测之前旋转图像。你似乎没有在 python 中做同样的事情

标签: tensorflow tensorflow.js


【解决方案1】:

这肯定与预测前处理图像的方式有关。在 js 中,您在预测之前旋转图像。你似乎没有在 python 中做同样的事情。

此外,您不需要额外的库 sharp 来加载您的图像

const buf = fs.readFileSync('path/to/image');
const tensor = tfnode.node.decodeImage(buf, 3);
let resized = tensor.resizeBilinear([224, 224]).div(tf.scalar(255));
// ... the rest

以上只是改进代码的一种方式,并不是说sharp是导致预测不匹配的原因

【讨论】:

  • 谢谢你的回答,我试试看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
  • 2020-08-08
  • 2019-07-29
  • 2021-09-02
相关资源
最近更新 更多