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.9%。
我觉得javascript的图像预处理方法有问题,因为我不是javascript的专家,或者我在javascript部分遗漏了什么?
发布于 2020-01-07 00:39:46
它与用于预测的图像有关。在预测之前,图像需要完全加载。
imEl.onload = function (){
const pred =
model.predict(preprocessing_img(imgEl)).dataSync()
const class_index = tf.argMax(pred);
}
https://stackoverflow.com/questions/56617528
复制相似问题