【问题标题】:What is the reason for major difference between predictions for Tensorflow in Python and for Tensorflow JS in browser?Python 中的 Tensorflow 预测与浏览器中的 Tensorflow JS 预测之间存在重大差异的原因是什么?
【发布时间】:2021-07-28 22:10:38
【问题描述】:

我在 Python Tensorflow 中创建了一个对象检测模型,然后在 Tensorflow JS 中对其进行了转换,以便在浏览器中使用。该模型在 python 中完美运行。现在,当我向浏览器提供输入图像时,python 和 TensorFlow JS 中的预测结果之间存在重大差异。我正在分享python和JS的预测结果。

Python 的结果:

JS 的结果:

我为 python 和 JS 提供了相同的图像作为输入,但对于 Scores 仍然存在很大差异,其中 python 预测为 99%,而 JS 预测仅为 16%。

这可能是什么原因?我在转换为 Tensorflow JS 时是否无意中犯了一些错误,还是有其他原因?

我浏览了this 和互联网上的其他资源,但找不到任何导致结果差异的具体原因。

任何帮助将不胜感激。非常感谢。

更新 1

这是我的 Python 代码:

def load_image_into_numpy_array(image_path):
     return np.array(Image.open(image_path))

image_path = random.choice(TEST_IMAGE_PATHS)
image_np = load_image_into_numpy_array(image_path)
input_tensor = tf.convert_to_tensor(
    np.expand_dims(image_np, 0), dtype=tf.float32)
detections, predictions_dict, shapes = detect_fn(input_tensor)

label_id_offset = 1
image_np_with_detections = image_np.copy()

viz_utils.visualize_boxes_and_labels_on_image_array(
      image_np_with_detections,
      detections['detection_boxes'][0].numpy(),
      (detections['detection_classes'][0].numpy() + label_id_offset).astype(int),
      detections['detection_scores'][0].numpy(),
      category_index,
      use_normalized_coordinates=True,
      max_boxes_to_draw=200,
      #Set min_score_thresh accordingly to display the boxes
      min_score_thresh=.5, 
      agnostic_mode=False
)

plt.figure(figsize=(12,25))
plt.imshow(image_np_with_detections)
plt.show()

这是 JS 中的模型调用:

async function run() {

    //Loading the Model : 
    model = await tf.loadGraphModel(MODEL_URL);
    console.log("SUCCESS");

    let img = document.getElementById("myimg");

    console.log("Predicting....");

    //Image PreProcessing 
    var example = tf.browser.fromPixels(img);
    example = example.expandDims(0);

    //model call
    const output = await model.executeAsync(example);
    console.log(output);

    const boxes = output[4].arraySync();
    const scores = output[5].arraySync();
    const classes = output[1].arraySync();

    console.log(boxes);
    console.log(scores);
    console.log(classes);

}

更新 2:

import pathlib

filenames = list(pathlib.Path('/content/train/').glob('*.index'))

filenames.sort()
print(filenames)

#recover our saved model
pipeline_config = pipeline_file
#generally you want to put the last ckpt from training in here
model_dir = str(filenames[-1]).replace('.index','')
configs = config_util.get_configs_from_pipeline_file(pipeline_config)
model_config = configs['model']
detection_model = model_builder.build(
      model_config=model_config, is_training=False)

# Restore checkpoint
ckpt = tf.compat.v2.train.Checkpoint(
      model=detection_model)
ckpt.restore(os.path.join(str(filenames[-1]).replace('.index','')))


def get_model_detection_function(model):
  """Get a tf.function for detection."""

  @tf.function
  def detect_fn(image):
    """Detect objects in image."""

    image, shapes = model.preprocess(image)
    prediction_dict = model.predict(image, shapes)
    detections = model.postprocess(prediction_dict, shapes)

    return detections, prediction_dict, tf.reshape(shapes, [-1])

  return detect_fn

detect_fn = get_model_detection_function(detection_model)

【问题讨论】:

  • 最有可能进行图像预处理。但是您的问题中没有足够的信息来回答。我们需要您在 Python 中的训练管道,在 JS 中的模型调用。
  • @Lescurel 我已按照建议添加了更多信息。
  • 首先想到的是您使用了不同的权重。您确定要在 Javascript 中加载经过训练的权重吗?因为 16% 的准确度听起来像是一个随机初始化的网络。
  • 能分享一下python代码中detect_fn的定义吗?
  • @mmiron 不,我没有使用不同的权重。 MODEL_URL 指向 .json 文件。

标签: python tensorflow tensorflow.js tensorflowjs-converter


【解决方案1】:

您缺少预处理。导出模型时,您正在导出默认的 serve 标签,因此您在 JS 中调用 model.executeAsync 相当于在 python 中调用 model.predict。但是,在您的 python 代码中,您还通过调用 model.preprocess 来预处理输入。

您应该在 JS 中复制 python 预处理。

【讨论】:

  • 注明。将按照建议在 JS 中的预处理方面工作并将更新。还想知道除了“服务”标签之外是否还有更多标签用于导出模型。感谢您的帮助。
  • 在 JS 中尝试预处理后,我仍然无法获得与 Python 中相同的精度。因此,我现在正在使用 TensorflowServing。有趣的是,我没有做任何我在训练时做的处理,但我仍然得到了与 TensorflowServing 中的 Python 相同的结果。
猜你喜欢
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 2021-03-24
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2014-04-02
  • 2018-10-10
相关资源
最近更新 更多