如果我想使用sklearn
库实现分类器,有没有一种方法可以保存模型或将文件转换为保存的tensorflow
文件,以便稍后将其转换为tensorflow lite
?
如果我想使用sklearn
库实现分类器,有没有一种方法可以保存模型或将文件转换为保存的tensorflow
文件,以便稍后将其转换为tensorflow lite
?
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))
在tensorflow中复制scikit模型并不总是容易的。例如,scitik有很多即时插补库,这些库在tensorflow中实现会有一些棘手。