无法使用反应将 tflite 自定义模型加载到网络中

Can't load tflite custom model into web using react

我有 2 个 tflite 模型在 aws 上托管为 s3 objects。在我的 react-typescript 应用程序中,如果在移动设备上打开浏览器,我会尝试加载这些模型。否则,网络应用程序将使用其他更高效的模型。

Models界面如下:

我已经配置了 s3 存储桶,因此我可以通过更改 CORS 配置从这个网络应用程序访问它。这样可行。如果我转到网络选项卡,我会看到模型的提取:

使用Chrome,我可以从移动显示更改为桌面显示。桌面显示不会产生任何错误。但是,手机给我的错误我不明白。

忽略 GET 错误和 date_created console.log。它们来自我的代码的另一部分,与此无关。

我搜索了各种资源来将 tflite 部署到网络应用程序,但没有找到任何有用的东西。

--------------------编辑---------------- ---

我试过使用this github post中讨论的方法

但只得到如下错误(可以忽略GET错误和isMobileconsole.log):

在幕后,Tensorflow TFLite API 使用 WASM (WebAssembly)。默认情况下,它将尝试从捆绑的 JS 文件所在的目录加载相关的 WASM 文件。此错误表明找不到文件,因此找不到 WASM 模块。为了解决这个问题,在尝试加载模型之前,需要使用 tflite.setWasmPath 配置 WASM 文件所在的路径:

tflite.setWasmPath(
   'https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-tflite@0.0.1-alpha.8/dist/'
);

或者,如果您想从自己的服务器提供 WASM 文件,可以将它们复制到项目中的 public 目录:

mkdir -p public/tflite_wasm
cp -rf node_modules/@tensorflow/tfjs-tflite/dist/tflite_web* public/tflite_wasm

然后相应地设置路径:

tflite.setWasmPath('tflite_wasm/');

更新

关于添加 setWasmPath 后出现的错误,如 Github issue and my initial response, based on the message "Failed to create TFLiteWebModelRunner: INVALID ARGUMENT" and looking at the source 中所述,该错误与参数 model 有关,即模型(s3 路径) 正在供应。

根据您提供的显示网络 activity 的图像,似乎 R_converted_model.tflite 下载成功,但 L_converted_model.tflite 不在该列表中。在无法访问模型文件以完全重现问题的情况下,我会说首先验证 L_converted_model.tflite 文件是否存在于 S3 中的该路径中。通过将模型路径修改为 non-existent 文件,我能够重现您在 this codepen demo 中看到的错误:

如果文件确实存在于该位置,我会通过在本地下载模型文件并尝试使用 Tensorflow API 加载它来评估模型文件本身,以确定文件是否存在问题。

解决办法是s3对象上传不正确。创建 tflite 模型的脚本没有完全创建 tflite 模型。它只创建了一个空文件。我修复了脚本。这是有效的代码:

import tensorflow as tf

model = tf.keras.models.load_model('model/R_keypoint_classifier_final.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
r_file = open("tflite_models/R_converted_model.tflite", "wb")
r_file.write(tflite_model)

model = tf.keras.models.load_model('model/L_keypoint_classifier_final.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
l_file = open("tflite_models/L_converted_model.tflite", "wb")
l_file.write(tflite_model)

在那之后,我只是将文件添加到 s3 存储桶中,并将代码与 setWasmPath 函数一起使用。