如何将保存的模型从 sklearn 转换为 tensorflow/lite

Mee*_*Mee 9 machine-learning scikit-learn text-classification tensorflow tensorflow-lite

如果我想使用sklearn库实现分类器。有没有办法保存模型或将文件转换为已保存的tensorflow文件以便tensorflow lite以后将其转换?

Jin*_*ich 6

如果您在 TensorFlow 中复制该架构(考虑到 scikit-learn 模型通常相当简单),这将非常容易,您可以将学习到的 scikit-learn 模型中的参数显式分配给 TensorFlow 层。

这是一个逻辑回归变成单个密集层的示例:

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))
Run Code Online (Sandbox Code Playgroud)