Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert saved model from sklearn into tensorflow/lite

If I want to implement a classifier using the sklearn library. Is there a way to save the model or convert the file into a saved tensorflow file in order to convert it to tensorflow lite later?

like image 321
Mee Avatar asked Jan 13 '20 20:01

Mee


People also ask

How do you convert a Sklearn model to TFLite?

There is not a converter that is 100% foolproof to go from sklearn to tf. You might try the keras scikit api wrapper tensorflow.org/api_docs/python/tf/keras/wrappers/scikit_learn . Once you do that you can use the standard TF to TF Lite conversion process.

What is saved model in TensorFlow?

A SavedModel contains a complete TensorFlow program, including trained parameters (i.e, tf. Variable s) and computation. It does not require the original model building code to run, which makes it useful for sharing or deploying with TFLite, TensorFlow. js, TensorFlow Serving, or TensorFlow Hub.

What is a TFLite file?

Jul 13, 2022. 1 min read. TensorFlow Lite, often referred to as TFLite, is an open source library developed by Google for deploying machine learning models to edge devices. Examples of edge deployments would be mobile (iOS/Android), embedded, and on-device.


1 Answers

If you replicate the architecture in TensorFlow, which will be pretty easy given that scikit-learn models are usually rather simple, you can explicitly assign the parameters from the learned scikit-learn models to TensorFlow layers.

Here is an example with logistic regression turned into a single dense layer:

import tensorflow as tf
import numpy as np
from sklearn.linear_model import LogisticRegression

# some random data to train and test on
x = np.random.normal(size=(60, 21))
y = np.random.uniform(size=(60,)) > 0.5

# fit the sklearn model on the data
sklearn_model = LogisticRegression().fit(x, y)

# create a TF model with the same architecture
tf_model = tf.keras.models.Sequential()
tf_model.add(tf.keras.Input(shape=(21,)))
tf_model.add(tf.keras.layers.Dense(1))

# assign the parameters from sklearn to the TF model
tf_model.layers[0].weights[0].assign(sklearn_model.coef_.transpose())
tf_model.layers[0].bias.assign(sklearn_model.intercept_)

# verify the models do the same prediction
assert np.all((tf_model(x) > 0)[:, 0].numpy() == sklearn_model.predict(x))
like image 182
Jindřich Avatar answered Sep 22 '22 22:09

Jindřich