sklearn.linear_model.LogisticRegression每次都返回不同的系数,尽管设置了random_state

jon*_*ans 7 python scikit-learn logistic-regression

我正在拟合逻辑回归模型,并将随机状态设置为固定值.

每次我做一个"适合"我得到不同的系数,例如:

classifier_instance.fit(train_examples_features, train_examples_labels)
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
          intercept_scaling=1, penalty='l2', random_state=1, tol=0.0001)

>>> classifier_instance.raw_coef_
array([[ 0.071101940040772596  ,  0.05143724979709707323,  0.071101940040772596  , -0.04089477198935181912, -0.0407380696457252528 ,  0.03622160087086594843,  0.01055345545606742319,
         0.01071861708285645406, -0.36248634699444892693, -0.06159019047096317423,  0.02370064668025737009,  0.02370064668025737009, -0.03159781822495803805,  0.11221150783553821006,
         0.02728295348681779309,  0.071101940040772596  ,  0.071101940040772596  ,  0.                    ,  0.10882033432637286396,  0.64630314505709030026,  0.09617956519989406816,
         0.0604133873444507169 ,  0.                    ,  0.04111685986987245051,  0.                    ,  0.                    ,  0.18312324521915510078,  0.071101940040772596  ,
         0.071101940040772596  ,  0.                    , -0.59561802045324663268, -0.61490898457874587635,  1.07812569991461248975,  0.071101940040772596  ]])

classifier_instance.fit(train_examples_features, train_examples_labels)
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
          intercept_scaling=1, penalty='l2', random_state=1, tol=0.0001)

>>> classifier_instance.raw_coef_
array([[ 0.07110193825129411394,  0.05143724970282205489,  0.07110193825129411394, -0.04089477178162870957, -0.04073806899140903354,  0.03622160048165772028,  0.010553455400928528  ,
         0.01071860364222424096, -0.36248635488413910588, -0.06159021545062405567,  0.02370064608376460866,  0.02370064608376460866, -0.03159783710841745225,  0.11221149816037970237,
         0.02728295411479400578,  0.07110193825129411394,  0.07110193825129411394,  0.                    ,  0.10882033461822394893,  0.64630314701686075729,  0.09617956493834901865,
         0.06041338563697066372,  0.                    ,  0.04111676713793514099,  0.                    ,  0.                    ,  0.18312324401049043243,  0.07110193825129411394,
         0.07110193825129411394,  0.                    , -0.59561803345113684127, -0.61490899867901249731,  1.07812569539027203191,  0.07110193825129411394]])
Run Code Online (Sandbox Code Playgroud)

我使用的是版本0.14,文档指定"底层C实现使用随机数生成器在拟合模型时选择特征.因此,对于相同的输入数据,结果略有不同,这种情况并不少见.如果发生这种情况,请尝试使用较小的tol参数."

我认为设置随机状态会确保没有随机性,但显然情况并非如此.这是一个错误还是想要的行为?

Fre*_*Foo 3

这并不是真正想要的,但这是一个很难修复的已知问题。问题是LogisticRegression模型是用Liblinear训练的,它不允许以完全稳健的方式设置其随机种子。当您显式设置 时random_state,会尽力设置 Liblinear 的随机种子,但这可能会失败。

  • 如果必须具有完全相同的系数,您可以编写一个函数“get_logistic_regression_coef”来拟合模型并返回系数,然后使用“sklearn.externals.joblib.Memory”对其进行缓存。这样,它将针对给定输入将结果保存到磁盘,并在第二次调用时重新加载这些结果(如果输入没有更改)。 (2认同)