Creating a sklearn.linear_model.LogisticRegression instance from existing coefficients

纵然是瞬间 提交于 2019-12-04 06:36:50

Yes, it works okay:

import numpy as np
from scipy.stats import norm
from sklearn.linear_model import LogisticRegression
import json
x = np.arange(10)[:, np.newaxis]
y = np.array([0,0,0,1,0,0,1,1,1,1])
# training one logistic regression
model1 = LogisticRegression(C=10, penalty='l1').fit(x, y)
# serialize coefficients (imitate loading from storage)
encoded = json.dumps((model1.coef_.tolist(), model1.intercept_.tolist(), model1.penalty, model1.C))
print(encoded)
decoded = json.loads(encoded)
# using coefficients in another regression
model2 = LogisticRegression()
model2.coef_ = np.array(decoded[0])
model2.intercept_ = np.array(decoded[1])
model2.penalty = decoded[2]
model2.C = decoded[3]
# resulting predictions are identical
print(model1.predict_proba(x) == model2.predict_proba(x))

Output:

[[[0.7558780101653273]], [-3.322083150375962], "l1", 10]
[[ True  True]
 [ True  True]
 [ True  True]
 [ True  True]
 [ True  True]
 [ True  True]
 [ True  True]
 [ True  True]
 [ True  True]
 [ True  True]]

So predictions of original and re-created models are indeed identical.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!