tensorflowjs 和 keras 在同一模型和张量上的不同结果

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

的 "Alternative: Use the Python API to export directly to TF.js Layers format" 部分以 te​​nsorflowjs 友好的格式保存了模型

然而,当我尝试使用 javascript 访问 html 页面中的结果时,我几乎每张图片(或接近它)都得到 1:即使图片在 Keras 中给出 0 .

我什至在 JSON 中将图像保存为张量,我在 Keras 中得到 0,在 TensorflowJS 中得到 1。这是一个错误还是我在某处犯了错误?

这是我在 TensorflowJS 中访问 json:

的代码
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.13.0"></script>

    <script>
      // 
      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]);
          })
        });
      })
    </script>
  </head>
  <body>
  </body>
</html>

这是我的 python 代码:

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 上并使用以下软件版本:

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)解决了这个问题。 可以查看问题的更多上下文 here and there

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.13.3"></script>

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 位数字)层)。