load model.json for tensorflowjs in reactjs not working

心已入冬 提交于 2020-06-15 10:29:06

问题


I'm trying to load a model.json file with it's weights.bin from the root directory in my react app.

When I call an example I found online from storage.googleapis.com it works but loading from my root doesn't.

The contents of App.js in my react app...

import React from "react";
import "./styles.css";

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

// example model - working
async function predict() {
  const model = await tf.loadGraphModel(
    "https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json"
  );
  console.log(typeof model);
}

// my model - not working
async function predictAlt() {
  const myModel = await tf.loadLayersModel("file://my-model.json");
  console.log(typeof model);
}

export default function App() {
  return (
    <div className="App">
      <button onClick={predict} style={{ fontSize: "20px" }}>
        example model
      </button>
      <br />
      <br />
      <button onClick={predictAlt} style={{ fontSize: "20px" }}>
        my model
      </button>
    </div>
  );
}

回答1:


The file URI scheme file://url is only for loading model server side. To load the model in the browser, the user can be prompted to select the model topology(model.json) and weight files. The doc contains an exemple of how to load a model by prompting the user using file input elements.

If the user is not to be requested to select the model files, then the model needs to be served by a server. The model.json and the weights can for instance be in the assets folder of the application deployed. Then the url would just need to be pointing to the model.json without file:// as follows:

const myModel = await tf.loadLayersModel("assets/my-model.json");

If there are some errors in loading the model, looking at the network tab in the developer console would help to see if the file is found or not



来源:https://stackoverflow.com/questions/61825870/load-model-json-for-tensorflowjs-in-reactjs-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!