簡體   English   中英

Keras 模型在轉換為 tensorflow-js 模型后沒有提供相同的結果

[英]Keras model doest not provide same results after converting into tensorflow-js model

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 數組中的最后一個索引在 90% 的情況下是 1。

我認為 javascript 中圖像的預處理方法有問題,因為我不是 javascript 專家,或者我在 javascript 部分遺漏了什么?

它與用於預測的圖像有關。 圖像需要在預測之前完全加載。

imEl.onload = function (){
 const pred = 
 model.predict(preprocessing_img(imgEl)).dataSync()
 const class_index = tf.argMax(pred);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM