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?
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With