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

霸气de小男生 提交于 2020-06-16 04:47:10

问题


Keras model performs as expected in python but after converting the model the results are different on the same data.

I tried updating the keras and tensorflow-js version but still the same issue.

Python code for testing:


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

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

These results are correct.

Javascript Code:

tfjs version:

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

preprocessing_img method and prediction in js:

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

In this case the results are not same and the last index in the pred array is 1 90% of the time.

I think there is something wrong with the preprocessing method of image in javascript since i am not an expert in javascript or am i missing something in javascript part?


回答1:


It has to do with the image used for the prediction. The image needs to have completely loaded before the prediction.

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


来源:https://stackoverflow.com/questions/56617528/keras-model-doest-not-provide-same-results-after-converting-into-tensorflow-js-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!