从 K-Fold CV 中寻找逻辑回归权重

Finding Logistic Regression weights from K-Fold CV

我有一个包含 36 个特征的数据集,我将所有这些特征用于 Fold 交叉验证中的逻辑回归算法。我的 K 值为 10。有什么方法可以在 CV 的第 10 次折叠结束时找到专用于我的所有 36 个特征的权重?这是我的代码:

    labels = df.columns[2:36]

    X = df[labels]
    y = df['target']

    # use train/test split with different random_state values
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=4)

    logreg = LogisticRegression()
    classifier_pre = cross_val_score(logreg, X, y, cv=20, scoring='precision')
    print("Precision:" ,classifier_pre.mean())

首先,python中的索引是从0开始的,所以写成labels = df.columns[2:36]是假设你的目标列有索引1,用人类语言来说就是从左数第二个(遍历这些值,第 36 列将 return 作为第 0 列)。如果您的目标列是从数据框左侧开始的第一列,您应该写 labels = df.columns[1:35]

某些函数(包括逻辑回归)已经在 sklearn.linear_model 中实现了 CV 架构。我建议你看看 here 在那里你可以看到如何调整和使用它。

您可以尝试类似的方法:

from sklearn.linear_model import LogisticRegressionCV

labels = df.columns[1:35] #if indeed your very first column is your target !!

logistic = LogisticRegressionCV(Cs=4, fit_intercept=True, cv=10, verbose =1, random_state=42)
logistic.fit(X, y)
print(logistic.coef_) #weights of each feature
print(logistic.intercept_) #value of intercept

最后一个建议:使用 train_test_split 生成的测试集是个好主意,但不要在其上训练模型。仅将其用于最后的评估。这意味着在这里你应该用 X_trainy_train 拟合你的算法并在 X_testy_test 上评估它,而不是复制我写的一小段代码,其中拟合部分是在 Xy 上完成的,如果在 Xy...

上评估您的模型,这将导致您对准确性的衡量过于乐观

我明白了。我们可以这样实现它:

labels = df.columns[2:35]

X = df[labels]
y = df['target']

kf = KFold(n_splits=10, shuffle=True, random_state=42)
logistic = LogisticRegressionCV(Cs=2, fit_intercept=True, cv=kf, verbose =1, random_state=42)
logistic.fit(X_train, y_train)
print("Train Coefficient:" , logistic.coef_) #weights of each feature
print("Train Intercept:" , logistic.intercept_) #value of intercept

这将给出 KFOLD 和 LR 中 CV=10 的给定模型的系数和截距。