Keras Deploy for Tensorflow.js Usage

帅比萌擦擦* 提交于 2021-02-11 12:05:04

问题


I need to be able to deploy a keras model for Tensorflow.js prediction, but the Firebase docs only seem to support a TFLite object, which tf.js cannot accept. Tf.js appears to accept JSON files for loading (loadGraphModel() / loadLayersModel() ), but not a keras SavedModel (.pb + /assets + /variables).

How can I attain this goal?

Note for the Tensorflow.js portion: There are a lot of pointers to the tfjs_converter, but the closest API function offered to what I'm looking for is the loadFrozenModel() function, which requires both a .pb and a weights_manifest.json. It seem to me like I'd have to programmatically assemble this before before sending it up to GCloud as a keras SavedModel doesn't contain both (mine contains .pb + /assets + /variables).

This seems tedious for a straightforward deployment feature, and I'd imagine my question only hits upon common usage of each tool.

What I'm looking for is a simple pathway from Keras => Firebase/GCloud => Tensorflow.js.


回答1:


So I understand your confusion but you have half part ready. So your keras model has the following files and folders if I understand correctly:

saved_model.pb
/assests
/variables

This is enough to convert the keras model to tensorflow.js model. Use the converter script in the following manner. Make sure you have the latest version of tfjs. If you do not have the latest version, try creating a virtual environment and install latest tfjs otherwise it will disrupt your tensorflow version.

import tensorflowjs as tfjs
import tensorflow as tf

model=tf.keras.models.load_model('path/to/keras/model')

tfjs.converters.save_keras_model(model, 'path/where/you/will/like/to/have/js/model/converted')

Once you have converted the model you will receive following files for js model.

model.json
something.bin

You will have to host those files using a webserver and just make it available for loadLayersModel API something like this:

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

That is it and you have converted the model from Keras to Tensorflowjs and uploaded as well in js.

I hope my answer helps you.



来源:https://stackoverflow.com/questions/63136779/keras-deploy-for-tensorflow-js-usage

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