如何将保存在sklearn中的模型转换为TensorFlow/Lite

13

如果我想使用sklearn库实现分类器,有没有一种方法可以保存模型或将文件转换为保存的tensorflow文件,以便稍后将其转换为tensorflow lite


1
目前还没有一种百分之百可靠的转换器可以将sklearn转换为tf。您可以尝试使用keras scikit api包装器https://www.tensorflow.org/api_docs/python/tf/keras/wrappers/scikit_learn。一旦这样做,您就可以使用标准的TF到TF Lite转换过程。 - aselle
谢谢您的回复。但是,据我所知,这个包装器帮助在sklearn框架中使用keras模型。例如,您训练了顺序NN,然后想要从sklearn进行交叉验证,这就是这个包装器有用的地方。 - Mee
2个回答

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))

太好了!还有哪些模型/分类器可以转换?我也注意到现在TF可以使用决策树... - jtlz2

1

在tensorflow中复制scikit模型并不总是容易的。例如,scitik有很多即时插补库,这些库在tensorflow中实现会有一些棘手。


这不是一个“答案”,根据SO的定义,最多只能作为OP问题下的评论。请访问帮助中心了解更多关于什么样的回答可以被认可。帮助中心链接位于每个页面的顶部。 - SherylHohman
这并没有回答问题。一旦您拥有足够的声望,您将能够评论任何帖子;相反,提供不需要询问者澄清的答案。- 来自审核 - SherylHohman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接