我正在嘗試使用系數手動預測邏輯回歸模型并截取 scikit-learn 模型的輸出。但是,我無法將我的概率預測與predict_proba分類器中的方法相匹配。
我試過了:
from sklearn.datasets import load_iris
from scipy.special import expit
import numpy as np
X, y = load_iris(return_X_y=True)
clf = LogisticRegression(random_state=0).fit(X, y)
# use sklearn's predict_proba function
sk_probas = clf.predict_proba(X[:1, :])
# and attempting manually (using scipy's inverse logit)
manual_probas = expit(np.dot(X[:1], clf.coef_.T) clf.intercept_)
# with a completely manual inverse logit
full_manual_probas = 1/(1 np.exp(-(np.dot(iris_test, iris_coef.T) clf.intercept_)))
輸出:
>>> sk_probas
array([[9.81815067e-01, 1.81849190e-02, 1.44120963e-08]])
>>> manual_probas
array([[9.99352591e-01, 9.66205386e-01, 2.26583306e-05]])
>>> full_manual_probas
array([[9.99352591e-01, 9.66205386e-01, 2.26583306e-05]])
我似乎確實讓類匹配(使用np.argmax),但概率不同。我錯過了什么?
我已經看過這個和這個,但還沒有弄清楚。
uj5u.com熱心網友回復:
該檔案指出
對于 multi_class 問題,如果 multi_class 設定為“多項式”,則使用 softmax 函式查找每個類的預測概率
也就是說,為了獲得與 sklearn 相同的值,您必須使用 softmax 進行歸一化,如下所示:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
import numpy as np
X, y = load_iris(return_X_y=True)
clf = LogisticRegression(random_state=0, max_iter=1000).fit(X, y)
decision = np.dot(X[:1], clf.coef_.T) clf.intercept_
print(clf.predict_proba(X[:1]))
print(np.exp(decision) / np.exp(decision).sum())
要改用 sigmoid,您可以這樣做:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
import numpy as np
X, y = load_iris(return_X_y=True)
clf = LogisticRegression(random_state=0, max_iter=1000, multi_class='ovr').fit(X, y) # Notice the extra argument
full_manual_probas = 1/(1 np.exp(-(np.dot(X[:1], clf.coef_.T) clf.intercept_)))
print(clf.predict_proba(X[:1]))
print(full_manual_probas / full_manual_probas.sum())
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470219.html
