简体   繁体   English

在本地将 keras model 加载到 tensorflow.js 中

[英]Loading keras model into tensorflow.js locally

I want to load keras model which has been converted into tensorflow.js compatible format to perform inference.我想加载已转换为tensorflow.js兼容格式的keras model 进行推理。 My code looks like this我的代码看起来像这样

import * as tf from '@tensorflow/tfjs';
import "regenerator-runtime/runtime.js";
import 'bootstrap/dist/css/bootstrap.css';

const model_path = '/home/user/Desktop/Github/tfjs_model/tfjs/tfjs_model/model.json'; 

async function loadModel(path){
  console.log("Model loading in progress from ".concat(path));
  const model =  await tf.loadLayersModel(path);
  console.log("Model Loaded Successfully");
  return model;
};

const model = loadModel(model_path);

const input = tf.tensor1d([1], [13]);
console.log(model.predict(input));

I am getting this error Error: Failed to parse model JSON of response from /home/user/Desktop/Github/tfjs_model/tfjs/tfjs_model/model.json'. Please make sure the server is serving valid JSON for this request.我收到此错误Error: Failed to parse model JSON of response from /home/user/Desktop/Github/tfjs_model/tfjs/tfjs_model/model.json'. Please make sure the server is serving valid JSON for this request. Error: Failed to parse model JSON of response from /home/user/Desktop/Github/tfjs_model/tfjs/tfjs_model/model.json'. Please make sure the server is serving valid JSON for this request. I've looked in a lot of placed (Github issues, Stack overflow) but can't seem to find a fix.我查看了很多地方(Github 问题,堆栈溢出),但似乎找不到解决方法。 How can this be resolved?如何解决? ` `

I had this problem too.我也有这个问题。

Using const model = await tf.loadLayersModel('directory/model.json');使用const model = await tf.loadLayersModel('directory/model.json'); generated the same error you had.产生了与您相同的错误。 I tried changing the import to find file model2.json , which didn't exist yet gave the same error (I notice there's an outstanding issue with TensorFlow.js to give a more meaningful error).我尝试更改导入以查找文件model2.json ,该文件尚不存在但给出了相同的错误(我注意到 TensorFlow.js 存在一个突出问题以给出更有意义的错误)。

Looking at my Parcel setup, I realised that the model.json and .bin files were being copied into the root of the dist folder.查看我的 Parcel 设置,我意识到model.json.bin文件被复制到dist文件夹的根目录中。 So I removed the directory from the import and now it works with:所以我从导入中删除了目录,现在它可以使用:

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

Note that my files are still in <content_root>/directory/ .请注意,我的文件仍在<content_root>/directory/中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM