从现有系数创建sklearn.linear_model.LogisticRegression实例

13 投票
1 回答
4494 浏览
提问于 2025-04-18 11:14

有没有办法根据已经计算好的系数(比如在其他程序中算出来的,像是Java)来创建这样的实例呢?

我试着先创建一个实例,然后直接设置coef_和intercept_,看起来是可以的,但我不太确定这样做有没有什么坏处,或者会不会导致什么问题。

1 个回答

7

是的,这个方法可以正常工作:

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

输出结果:

[[[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]]

所以,原始模型和重新创建的模型的预测结果确实是一样的。

撰写回答