[英]Saving a Keras/Sklearn in python and loading the saved model in tensorflow.js
I have a trained sklearn SVM model in .pkl format and a Keras .h5 model.我有一个经过训练的 .pkl 格式的 sklearn SVM 模型和一个 Keras .h5 模型。 Can I load these models using tensorflow.js on a browser?我可以在浏览器上使用tensorflow.js加载这些模型吗? I do most of my coding in python and not sure how to work with tensorflow.js My model saving code looks like this我在 python 中完成大部分编码,但不确定如何使用 tensorflow.js 我的模型保存代码如下所示
from sklearn.externals import joblib
joblib.dump(svc,'model.pkl')
model = joblib.load('model.pkl')
prediction = model.predict(X_test)
#------------------------------------------------------------------
from keras.models import load_model
model.save('model.h5')
model = load_model('my_model.h5')
In order to deploy your model with tensorflow-js, you need to use the tensorflowjs_converter
, so you also need to install the tensorflowjs
dependency.为了使用 tensorflow-js 部署您的模型,您需要使用tensorflowjs_converter
,因此您还需要安装tensorflowjs
依赖项。
You can do that in python via pip install tensorflowjs
.你可以通过pip install tensorflowjs
在 python 中做到这pip install tensorflowjs
。
Next, you convert your trained model via this operation, according to your custom names: tensorflowjs_converter --input_format=keras /tmp/model.h5 /tmp/tfjs_model
, where the last path is the output path of the conversion result.接下来,根据您的自定义名称,通过此操作转换训练tensorflowjs_converter --input_format=keras /tmp/model.h5 /tmp/tfjs_model
: tensorflowjs_converter --input_format=keras /tmp/model.h5 /tmp/tfjs_model
,其中最后一个路径是转换结果的输出路径。
Note that, after the conversion you will get a model.json
(architecture of your model) and a list of N shards (weights split in N shards).请注意,转换后您将获得一个model.json
(模型的架构)和 N 个分片的列表(权重拆分为 N 个分片)。
Then, in JavaScript, you need to us the function tf.loadLayersModel(MODEL_URL)
, where MODEL_URL is the url pointing to your model.json.然后,在 JavaScript 中,您需要使用tf.loadLayersModel(MODEL_URL)
函数,其中 MODEL_URL 是指向您的 model.json 的 url。 Ensure that, at the same location with the model.json, the shards are also located.确保分片也位于与 model.json 相同的位置。
Since this is an asynchronous operation(you do not want your web-page to get blocked while your model is loading), you need to use the JavaScript await
keyword;由于这是一个异步操作(您不希望您的网页在您的模型加载时被阻止),您需要使用 JavaScript 的await
关键字; hence await tf.loadLayersModel(MODEL_URL)
因此await tf.loadLayersModel(MODEL_URL)
Please have a look at the following link to see an example: https://www.tensorflow.org/js/guide/conversion请查看以下链接以查看示例: https : //www.tensorflow.org/js/guide/conversion
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.