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

时间:2018-10-06 22:04:27

标签: javascript python tensorflow keras tensorflowjs-converter

我按照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

的“替代:使用Python API直接导出为TF.js图层格式”部分,以适合tensorflowjs的格式保存模型。

但是,当我尝试使用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>
      // 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]);
          })
        });
      })
    </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,此问题已得到解决。

2 个答案:

答案 0 :(得分:1)

升级到最新版本的tfjs(当前为0.13.3)可以解决此问题。 可以在herethere

处查看该问题的更多背景信息
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.13.3"></script>

答案 1 :(得分:0)

在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位)。