2

Keras 模型在 python 中按预期执行,但在转换模型后,相同数据的结果不同。

我尝试更新 keras 和 tensorflow-js 版本,但仍然是同样的问题。

用于测试的 Python 代码:


import keras
import cv2
model = keras.models.load_model("keras_model.h5")
img = cv2.imread("test_image.jpg")

def preprocessing_img(img):
    img = cv2.resize(img, (50,50))
    x = np.array(img)
    image = np.expand_dims(x, axis=0)
    return image/255

prediction_array= model.predict(preprocessing_img(img))
print(prediction_array)
print(np.argmax(prediction_array))

结果:[[1.9591815e-16 1.0000000e+00 3.8602989e-18 3.2472009e-19 5.8910814e-11]] 1

这些结果是正确的。

Javascript代码:

tfjs 版本:

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.13.5">
</script>

js中的preprocessing_img方法和预测:

function preprocessing_img(img)
  {
    let tensor = tf.fromPixels(img)
    const resized = tf.image.resizeBilinear(tensor, [50, 50]).toFloat()
    const offset = tf.scalar(255.0);
    const normalized = tf.scalar(1.0).sub(resized.div(offset));
    const batched = normalized.expandDims(0)

    return batched

  }

const pred = model.predict(preprocessing_img(imgEl)).dataSync()
const class_index = tf.argMax(pred);

在这种情况下,结果不一样,pred 数组中的最后一个索引是 1 90% 的时间。

我认为javascript中图像的预处理方法有问题,因为我不是javascript专家,还是我在javascript部分遗漏了什么?

4

1 回答 1

1

它与用于预测的图像有关。图像需要在预测之前完全加载。

imEl.onload = function (){
 const pred = 
 model.predict(preprocessing_img(imgEl)).dataSync()
 const class_index = tf.argMax(pred);
}
于 2020-01-06T16:39:46.270 回答