Load Tensorflow js model from local file system in javascript

前端 未结 7 1230
一个人的身影
一个人的身影 2020-11-30 10:31

I have converted a keras model to tensorflow json format and saved it locally in my computer. I am trying to load that json model in a javascript code using the below comman

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 11:30

    LoadModel uses fetch under the hood. And fetch cannot access the local files directly. It is meant to be used to get files served by a server. More on this here. To load a local file with the browser, there is two approaches, asking the user to upload the file with

    
    

    Or serving the file by a server.

    In these two scenarios, tf.js provides way to load the model.

    1. Load the model by asking the user to upload the file

    html

    
    
    

    js

    const uploadJSONInput = document.getElementById('upload-json');
    const uploadWeightsInput = document.getElementById('upload-weights');
    const model = await tfl.loadModel(tf.io.browserFiles(
     [uploadJSONInput.files[0], uploadWeightsInput.files[0]]));
    
    1. Serving the local files using a server

    To do so, one can use the following npm module http-server to serve the directory containing both the weight and the model. It can be installed with the following command:

     npm install http-server -g
    

    Inside the directory, one can run the following command to launch the server:

    http-server -c1 --cors .
    

    Now the model can be loaded:

     // load model in js script
     (async () => {
       ...
       const model = await tf.loadFrozenModel('http://localhost:8080/model.pb', 'http://localhost:8080/weights.json')
     })()
    

提交回复
热议问题