如何使用 Node.js 将转换后的预训练 keras 模型加载到 Tensorflow.js?

How to load a converted pre-trained keras model to Tensorflow.js using Node.js?

我有预训练的 keras 模型,我已经使用 TensorflowJs Converter 进行了转换。我正在尝试在以下脚本中加载它们

(index.js)

const tf = require('@tensorflow/tfjs');

require('@tensorflow/tfjs-node');
global.fetch = require('node-fetch')

const model = tf.loadLayersModel(
     'model/model.json');

我在执行 node index.js

时遇到以下错误
(node:28543) UnhandledPromiseRejectionWarning: Error: Request for model/decoder-model/model.json failed due to error: TypeError: Only absolute URLs are supported

(node:28543) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
(node:28543) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这个我也试过

const model = tf.loadLayersModel(
     'https://storage.googleapis.com/tfjs-models/tfjs/iris_v1/model.json');

但是我得到了

(node:28772) UnhandledPromiseRejectionWarning: Error: Found more than one (2) load handlers for URL 'https://storage.googleapis.com/tfjs-models/tfjs/iris_v1/model.json'

系统信息

节点 v10.15.3 和 TensorflowJs v1.0.1

第一个错误很明显,它想要一个绝对的 URL ('/model/model.json'),但你给它一个相对的 ('model/model.json')。

第二个错误也比较清楚,错误告诉你前一个抛出的错误没有被捕获(因此Unhandled)。

最后一个,请看 https://github.com/tensorflow/tfjs/issues/779https://github.com/tensorflow/tfjs/issues/622

我认为这是因为混合了 CUDA 和非 CUDA 的东西。先检查你的packages.json

替换

const tf = require('@tensorflow/tfjs'); 

const tf = require('@tensorflow/tfjs-node');

并删除行

require('@tensorflow/tfjs-node');

然后,如果您要从本地文件系统加载模型,请将 'file://' 添加到您提供给 loadLayersModel() 的参数的开头。

它应该可以工作