转换为tensorflow-js模型后,Keras模型无法提供相同的结果 [英] Keras model doest not provide same results after converting into tensorflow-js model
问题描述
Keras模型的执行效果与python预期的一样,但在转换模型后,相同数据上的结果却不同.
Keras model performs as expected in python but after converting the model the results are different on the same data.
我尝试更新keras和tensorflow-js版本,但仍然存在相同的问题.
I tried updating the keras and tensorflow-js version but still the same issue.
用于测试的Python代码:
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))
结果:[[1.9591815e-16 1.0000000e + 00 3.8602989e-18 3.2472009e-19 5.8910814e-11]]1
Results: [[1.9591815e-16 1.0000000e+00 3.8602989e-18 3.2472009e-19 5.8910814e-11]] 1
这些结果是正确的.
JavaScript代码:
Javascript Code:
tfjs版本:
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.13.5">
</script>
js中的preprocessing_img方法和预测:
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);
在这种情况下,结果并不相同,并且pred数组中的最后一个索引是1 90%的时间.
In this case the results are not same and the last index in the pred array is 1 90% of the time.
我认为javascript中图像的预处理方法有问题,因为我不是javascript方面的专家,或者我在javascript部分中缺少某些内容?
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?
推荐答案
它与用于预测的图像有关.图像需要在预测之前完全加载.
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);
}
这篇关于转换为tensorflow-js模型后,Keras模型无法提供相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!