You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Hyperopt调优XGBRegressor参数时遇TypeError错误求助

解决Hyperopt优化XGBRegressor时的TypeError错误

错误原因

你碰到的TypeError: int() takes at most 2 arguments (3 given),核心问题是把min_child_weight、colsample_bytree等XGBoost模型参数错误嵌套进了int()函数的参数列表。int()仅用于将reg_alpha的浮点值转换为整数,最多只接受2个参数(待转换值+可选进制),多余的参数直接触发了报错。

修正后的完整代码

from hyperopt import hp, STATUS_OK  # 修正hp的导入路径,补充缺失的STATUS_OK
from sklearn.metrics import mean_squared_error
from xgboost import XGBRegressor

space={'max_depth': hp.quniform("max_depth", 3, 18, 1),
    'gamma': hp.uniform ('gamma', 1,9),
    'reg_alpha' : hp.quniform('reg_alpha', 40,180,1),
    'reg_lambda' : hp.uniform('reg_lambda', 0,1),
    'colsample_bytree' : hp.uniform('colsample_bytree', 0.5,1),
    'min_child_weight' : hp.quniform('min_child_weight', 0, 10, 1),
    'n_estimators': 180
}
def hyperparameter_tuning(space):
    model = XGBRegressor(
        n_estimators=space["n_estimators"],
        max_depth=int(space["max_depth"]),
        gamma=space["gamma"],
        reg_alpha=int(space["reg_alpha"]),  # 仅保留reg_alpha的类型转换
        reg_lambda=space["reg_lambda"],
        colsample_bytree=space["colsample_bytree"],  # 作为独立参数传入模型
        min_child_weight=int(space["min_child_weight"])  # 转为整数后独立传入
    )

    evaluation = [(X_train, y_train), (X_valid, y_valid)]

    model.fit(
        X_train,
        y_train,
        eval_set=evaluation,
        eval_metric="rmse",
        early_stopping_rounds=10,
        verbose=False,
    )

    pred = model.predict(X_valid)
    mse = mean_squared_error(y_valid, pred)
    print("SCORE:", mse)
    return {"loss": mse, "status": STATUS_OK, "model": model}

关键修正点

  • 导入修正:hp属于hyperopt库,而非scipy.constants;同时补充导入STATUS_OK(原代码中使用但未声明)
  • 参数位置修正:将min_child_weight、colsample_bytree、reg_lambda从int()中移出,作为XGBRegressor的独立参数传入
  • 类型转换修正:min_child_weight由hp.quniform生成浮点值,需转为整数类型才能匹配XGBoost的参数要求

内容的提问来源于stack exchange,提问作者nonamethoughtof

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 05:29:54