【问题标题】:how to convert saved model from sklearn into tensorflow/lite如何将保存的模型从 sklearn 转换为 tensorflow/lite
【发布时间】:2020-04-30 14:20:10
【问题描述】:

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

【问题讨论】:

  • 从 sklearn 到 tf. 没有 100% 万无一失的转换器。您可以尝试使用 keras scikit api 包装器 tensorflow.org/api_docs/python/tf/keras/wrappers/scikit_learn 。完成后,您可以使用标准 TF 到 TF Lite 的转换过程。
  • 感谢您的回复。但是,据我了解,这个包装器有助于在 sklearn 框架中使用 keras 模型。比如说你训练了顺序神经网络,然后你想从 sklearn 进行交叉验证,这是这个包装器有用的时候

标签: tensorflow machine-learning scikit-learn text-classification tensorflow-lite


【解决方案1】:

如果您在 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 可以使用决策树了...
猜你喜欢
  • 2019-04-14
  • 1970-01-01
  • 2019-12-18
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 2020-12-03
  • 2020-10-14
相关资源
最近更新 更多