【发布时间】:2018-09-08 18:20:42
【问题描述】:
我试图了解如何在逻辑回归交叉验证中计算最佳系数,其中“refit”参数为 True。 如果我正确理解了docs,则最佳系数是首先确定最佳正则化参数“C”的结果,即在所有折叠中平均得分最高的 C 值。然后,最好的系数就是在最佳 C 得分最高的折叠上计算的系数。我假设如果通过多次折叠达到最高分数,则这些折叠的系数将被平均以给出最好的系数(我在文档中没有看到关于如何处理这种情况的任何内容)。
为了测试我的理解,我以两种不同的方式确定了最佳系数:
- 直接来自拟合模型的 coef_ 属性,并且
- 来自 coefs_paths 属性,该属性包含在交叉验证过程中获得的系数的路径,该路径跨越每个折叠,然后跨越每个 C。
我从 1. 和 2. 得到的结果相似但不完全相同,所以我希望有人能指出我在这里做错了什么。 谢谢!
演示问题的示例:
from sklearn.datasets import load_breast_cancer
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegressionCV
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# Set parameters
n_folds = 10
C_values = [0.001, 0.01, 0.05, 0.1, 1., 100.]
# Load and preprocess data
cancer = load_breast_cancer()
X, y = cancer.data, cancer.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
X_train_scaled = StandardScaler().fit_transform(X_train)
# Fit model
clf = LogisticRegressionCV(Cs=C_values, cv=n_folds, penalty='l1',
refit=True, scoring='roc_auc',
solver='liblinear', random_state=0,
fit_intercept=False)
clf.fit(X_train_scaled, y_train)
########################
# Get and plot coefficients using method 1
########################
coefs1 = clf.coef_
coefs1_series = pd.Series(coefs1.ravel(), index=cancer['feature_names'])
coefs1_series.sort_values().plot(kind="barh")
########################
# Get and plot coefficients using method 2
########################
# mean of scores of class "1"
scores = clf.scores_[1]
mean_scores = np.mean(scores, axis=0)
# Get index of the C that has the highest average score across all folds
best_C_idx = np.where(mean_scores==np.max(mean_scores))[0][0]
# Get index (here: indices) of the folds with highest scores for the
# best C
best_folds_idx = np.where(scores[:, best_C_idx]==np.max(scores[:, best_C_idx]))[0]
paths = clf.coefs_paths_[1] # has shape (n_folds, len(C_values), n_features)
coefs2 = np.squeeze(paths[best_folds_idx, best_C_idx, :])
coefs2 = np.mean(coefs2, axis=0)
coefs2_series = pd.Series(coefs2.ravel(), index=cancer['feature_names'])
coefs2_series.sort_values().plot(kind="barh")
【问题讨论】:
-
包含示例输入数据和输出会很有帮助,尤其是说明回归系数在不同折叠之间可能会有多大差异。
-
@rwp 你在想什么样的示例输入?我发布的示例使用 scikit-learn 的乳腺癌数据集作为输入。如果您运行该示例,您可以看到输出(coefs1 和 coefs2 的图),并且它们不相等(也可以使用 numpy.array_equal(coefs1, coefs2) 进行验证。我的问题基本上是如何计算/重现来自 coefs_paths_ 属性的最佳系数(由 clf.scores_ 给出),该属性包含 C 在每一折上的所有值的分数。
标签: scikit-learn logistic-regression cross-validation coefficients