machine-learning - 如何公平地比较基线和 GridSearchCV 结果?

标签 machine-learning scikit-learn cross-validation gridsearchcv baseline

我对比较最佳 GridSearchCV 模型和基线有点困惑。
例如,我们有分类问题。
作为基线,我们将使用默认设置拟合模型(让它成为逻辑回归):

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
baseline = LogisticRegression()
baseline.fit(X_train, y_train)
pred = baseline.predict(X_train)
print(accuracy_score(y_train, pred))

因此,基线为我们提供了使用整个训练样本的准确性。
接下来,GridSearchCV:

from sklearn.model_selection import cross_val_score, GridSearchCV, StratifiedKFold
X_val, X_test_val,y_val,y_test_val = train_test_split(X_train, y_train, test_size=0.3, random_state=42)
cv = StratifiedKFold(n_splits=5, random_state=0, shuffle=True)
parameters = [ ... ]
best_model = GridSearchCV(LogisticRegression(parameters,scoring='accuracy' ,cv=cv))
best_model.fit(X_val, y_val)
print(best_model.best_score_)

在这里,我们有基于验证样本的准确性。

我的问题是:

  1. 这些准确度得分是否具有可比性?一般来说,在没有任何交叉验证的情况下比较 GridSearchCV 和模型是否公平?
  2. 对于基线,也使用验证样本(而不是整个训练样本)不是更好吗?

最佳答案

不,它们没有可比性。

您的基线模型使用 X_train 来拟合模型。然后,您将使用拟合模型对 X_train 样本进行评分。这就像作弊,因为模型已经表现最佳,因为您是根据它已经看到的数据对其进行评估。

网格搜索模型处于劣势,因为:

  1. 由于您拆分了 X_train 样本,它使用的数据较少。
  2. 再加上由于 5 次折叠,它使用更少的数据进行训练(每次折叠仅使用 4/5 的 X_val 进行训练)。

所以你的网格搜索分数会比你的基线差。

现在您可能会问,“那么 best_model.best_score_ 的意义何在?好吧,该分数用于比较在您的搜索空间中搜索最佳超参数时使用的所有模型,但在不应使用任何方式与在网格搜索上下文之外训练的模型进行比较。

那么应该如何进行公平比较呢?

  1. 拆分两个模型的训练数据。
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
  1. 使用 X_train 拟合您的模型。
# fit baseline
baseline.fit(X_train, y_train)

# fit using grid search
best_model.fit(X_train, y_train)
  1. 根据 X_test 评估模型。
# baseline
baseline_pred = baseline.predict(X_test)
print(accuracy_score(y_test,  baseline_pred))

# grid search
grid_pred = best_model.predict(X_test)
print(accuracy_score(y_test, grid_pred))

关于machine-learning - 如何公平地比较基线和 GridSearchCV 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69844028/

相关文章:

machine-learning - 值错误 : Input 0 is incompatible with layer conv2_1: expected ndim=4, 发现 ndim=3

python - 在 tensorflow 中查找检测到的设备数量

deep-learning - 深度学习,Loss不减

python - 在Python中使用sklearn计算变量n-grams的TF-IDF

matlab - Matlab 中的交叉验证和 perfcurv

r - XGboost 模型始终获得 100% 的准确率?

Python 小批量字典学习

matlab - 使用 PCA 投影到 Octave 中的低维空间

python - 确定为什么特征在决策树模型中很重要

python-3.x - 使用 cross_val_score 的系数