如何正确地为多个分类手动重新创建sklearn(python)逻辑回归predict_proba结果

时间:2017-06-03 14:56:05

标签: python-3.x scikit-learn logistic-regression

如果我使用4个类运行基本逻辑回归,我可以得到predict_proba数组。

如何使用系数和截距手动计算概率?获得predict_proba生成的相同答案的确切步骤是什么?

网上似乎存在多个问题以及一些不完整或无法匹配的建议。

例如,我无法从我的sklearn模型中复制此过程,因此缺少什么?

https://stats.idre.ucla.edu/stata/code/manually-generate-predicted-probabilities-from-a-multinomial-logistic-regression-in-stata/

谢谢,

2 个答案:

答案 0 :(得分:2)

复制sklearn calcs(在不同的帖子上看到这个):

V = X_train.values.dot(model.coef_.transpose())
U = V + model.intercept_
A = np.exp(U)
P=A/(1+A)
P /= P.sum(axis=1).reshape((-1, 1))

似乎与softmax计算或UCLA统计示例略有不同,但它有效。

答案 1 :(得分:0)

因为我有相同的问题,但是找不到给出相同结果的答案,所以我查看了sklearn GitHub repository来找到答案。使用他们自己的程序包中的函数,我可以创建与predict_proba()相同的结果。

似乎sklearn使用了特殊的softmax()函数,该函数不同于其代码中通常的softmax函数。

假设您建立的模型是这样的:

from sklearn.linear_model import LogisticRegression

X = ...
Y = ...
model = LogisticRegression(multi_class="multinomial", solver="saga")
model.fit(X, Y)

然后,您可以使用model.predict(X)来计算概率,或者使用上面提到的sklearn函数来像这样手动计算它们。

from sklearn.utils.extmath import softmax, 
import numpy as np

scores = np.dot(X, model.coef_.T) + model.intercept_
softmax(scores)  # Sklearn implementation

在自己的softmax()函数的文档中,他们指出了

softmax函数的计算公式为

np.exp(X)/ np.sum(np.exp(X),轴= 1)

对大数值求幂时将导致溢出。因此 每行的最大值从每个数据点减去 防止这种情况。

相关问题