TypeError: XGBModel.fit() got an unexpected keyword argument 'early_stopping_rounds'
时间: 2025-01-11 10:30:47 浏览: 915
### 解决方案
当遇到 `XGBoost` 的 `fit()` 方法中传递 `early_stopping_rounds` 参数时报错的情况,通常是因为参数设置不当或数据集不符合预期的要求。为了正确配置并使用该参数,可以遵循以下方法:
对于 `XGBModel` 或者其他基于 `scikit-learn` API 接口的封装类,在调用 `.fit()` 进行模型训练时确实支持直接指定 `early_stopping_rounds` 参数[^1]。
然而需要注意的是,要使此参数生效还需要满足两个条件:一是提供验证集用于监控性能;二是确保输入的数据格式正确无误。具体来说就是除了训练样本外还需额外给出评估使用的数据集作为关键字参数 `eval_set` 的值,并且这个元组列表中的每一对都应该由特征矩阵和目标向量组成[(X_val, y_val)](https://xgboost.readthedocs.io/en/stable/python/python_api.html#module-xgboost.sklearn)。
下面是一个简单的例子来展示如何正确地应用这些选项:
```python
import xgboost as xgb
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# 创建模拟数据集
X, y = make_classification(n_samples=1000, n_features=20,
n_informative=2, n_redundant=10,
random_state=7)
# 划分训练/测试集合
X_train, X_valid, y_train, y_valid = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
# 初始化分类器实例
clf = xgb.XGBClassifier(use_label_encoder=False, eval_metric='logloss')
# 训练模型的同时启用早停机制
clf.fit(X_train, y_train,
early_stopping_rounds=10,
eval_set=[(X_valid, y_valid)])
```
上述代码片段展示了怎样利用 `early_stopping_rounds` 和 `eval_set` 来防止过拟合以及提高效率。
阅读全文
相关推荐


















