Different results for tensorflowjs and keras on same model and tensor
我按照https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html的示例训练了一些图像上的CNN模型。我的模型代码是相同的,我只是在另一个图像数据集上对其进行了训练:也用于两个类之间的分类。
结果是您在训练集上所期望的:图像正确分类为0或1。
我按照https://js.tensorflow.org/tutorials/import- keras.html
但是,当我尝试使用javascript访问html页面中的结果时,几乎每张图像(或接近它)都会得到1:即使图像在Keras中给出了0。
我什至在JSON中将图像保存为张量,在Keras中得到0,在TensorflowJS中得到1。这是错误还是我在某个地方犯了错误?
这是我在TensorflowJS中访问json的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <html> <head> <!-- Load TensorFlow.js --> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"> // https://stackoverflow.com/a/18324384/2730032 function callAjax(url, callback){ var xmlhttp; // compatible with IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200){ callback(xmlhttp.responseText); } } xmlhttp.open("GET", url, true); xmlhttp.send(); } tf.loadModel('/model.json').then(model => { callAjax('/tensor.json', res => { arr = JSON.parse(res); const example = tf.tensor(arr).reshape([1, 150, 150, 3]); const prediction = model.predict(example); prediction.data().then(res => { console.log('PREDICTION JS', res[0]); }) }); }) </head> <body> </body> </html> |
这是我的相同的python代码:
1 2 3 4 5 6 7 8 9 10 | import json import numpy as np import tensorflowjs as tfjs model = tfjs.converters.load_keras_model('model.json') with open('tensor.json', 'r') as f: r = json.load(f) arr = np.array([np.array([np.array(v) for v in l]) for l in r]) print('PREDICTION PYTHON', model.predict(arr[np.newaxis,...])[0][0]) |
对于完全相同的数据和相同的模型,我得到了PREDICTION JS 1和PREDICTION PYTHON 0.0:有人在我的代码中看到任何问题吗?
EDIT1:我使用的是Xubuntu 18.04.1 LTS,并使用以下软件版本:
1 2 3 4 5 | Python 3.6.6 Keras 2.2.4 tensorflow 1.11.0 tensorflowjs 0.6.2 numpy 1.15.2 |
EDIT2:我打开了以下问题https://github.com/tensorflow/tfjs/issues/776,此问题已得到修复。
升级到最新版本的tfjs(当前为0.13.3)可以解决此问题。
可以在这里和那里查看有关该问题的更多上下文
1 |
在Mac 10.15,TF 2.3,Python 3.8,纯JavaScript TFJS 2.6.0,网络服务器上存在类似问题:python3 -m http.server
在大型,深的CNN RNN Keras网络上的所有单元上,推理结果始终保持在0.5左右。
解决方案:
不要将tensorflowjs_converter用于.h5到TFJS的转换
tensorflowjs_wizard允许您关闭数值压缩,从而提供与Python TF2.3几乎相同的结果(在我的情况下,最后一层的数字最多为6位)。