簡體   English   中英

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。

我在tensorflowjs友好的格式保存的模型下面的“替代方案:使用Python API出口直接TF.js層格式”的部分https://js.tensorflow.org/tutorials/import-keras.html

但是,當我嘗試使用 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 ,此后已修復。

升級到最新版本的 tfjs(當前為 0.13.3)解決了這個問題。 可以在這里那里查看問題的更多背景

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM