Scikit Learn Logistic 回归中的逆预测是正确的

Inverse of prediction is correct in Scikit Learn Logistic Legression

在以下最小可重现数据集中,我将数据集拆分为训练数据集和测试数据集,使用 scikit 学习将逻辑回归拟合到训练数据集,并根据 x_test.

预测 y

然而,y_pred 或 y 预测只有在逆向计算(例如 0 = 1,1 = 0)时才正确:1 - y_pred。 为什么会这样?我无法弄清楚它是否与 x 的缩放有关(我尝试过使用和不使用 StandardScaler),是否与逻辑回归或准确度分数计算有关。

在我更大的数据集中,即使使用不同的种子作为随机状态也是如此。我也试过 this Logistic Regression 结果相同。

EDIT 正如@Nester 所指出的,对于这个最小数据集,它在没有标准缩放器的情况下工作。更大的数据集可用 herestandardScaler 对这个更大的数据集没有任何作用,我将保留 OP 较小的数据集,因为它可能有助于解释问题。

# imports
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler

# small dataset
Y = [1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0]
X =[[0.38373581],[0.56824121],[0.39078066],[0.41532221],[0.3996311 ]
    ,[0.3455455 ],[0.55867358],[0.51977073],[0.51937625],[0.48718916]
    ,[0.37019272],[0.49478954],[0.37277804],[0.6108499 ],[0.39718093]
    ,[0.33776591],[0.36384773],[0.50663667],[0.3247984 ]]


x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.15, random_state=42, stratify=Y)
clf = make_pipeline(StandardScaler(), LogisticRegression())
clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)

y_pred = 1 - y_pred #          <- why?

accuracy_score(y_test,y_pred)
1.0

更大的数据集准确性:

accuracy_score(y_test,y_pred)
0.7  # if inversed

感谢阅读

您是否尝试过 运行 没有 StandardScaler() 的模型?您的数据看起来不需要重新缩放。

X和Y根本没有任何关系。因此,该模型表现不佳。有理由说 1-pred 表现更好。如果你有两个以上的类,那么情况会更糟。

%matplotlib inline 
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.15,  stratify=Y)
clf = make_pipeline(StandardScaler(), LogisticRegression())
clf.fit(x_train, y_train)
import matplotlib.pyplot as plt
plt.scatter(clf.named_steps['standardscaler'].transform(x_train),y_train)
plt.scatter(clf.named_steps['standardscaler'].transform(x_test),y_test)
print(clf.score(x_test,y_test))

对于更大的数据集,这种关系也是相同的。

尝试识别其他特征,这可以帮助您预测 Y。