我对比较最佳 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_)
在这里,我们有基于验证样本的准确性。
我的问题是:
- 这些准确度得分是否具有可比性?一般来说,在没有任何交叉验证的情况下比较 GridSearchCV 和模型是否公平?
- 对于基线,也使用验证样本(而不是整个训练样本)不是更好吗?
最佳答案
不,它们没有可比性。
您的基线模型使用 X_train
来拟合模型。然后,您将使用拟合模型对 X_train
样本进行评分。这就像作弊,因为模型已经表现最佳,因为您是根据它已经看到的数据对其进行评估。
网格搜索模型处于劣势,因为:
- 由于您拆分了
X_train
样本,它使用的数据较少。 - 再加上由于 5 次折叠,它使用更少的数据进行训练(每次折叠仅使用 4/5 的
X_val
进行训练)。
所以你的网格搜索分数会比你的基线差。
现在您可能会问,“那么 best_model.best_score_
的意义何在?好吧,该分数用于比较在您的搜索空间中搜索最佳超参数时使用的所有模型,但在不应使用任何方式与在网格搜索上下文之外训练的模型进行比较。
那么应该如何进行公平比较呢?
- 拆分两个模型的训练数据。
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
- 使用
X_train
拟合您的模型。
# fit baseline
baseline.fit(X_train, y_train)
# fit using grid search
best_model.fit(X_train, y_train)
- 根据
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/