Xgboost模型评估

    # 4.1 模型评估

    """ 检查 XGBoost 模型是否正确,如不正确则抛出异常 """
    logger.info(' --- 检查 XGBoost 模型是否正确')

    if not xgboost_model:
        logger.error('XGBoost模型不存在,请检查!')
        raise ValueError("XGBoost模型不存在,请检查!")
    if not isinstance(xgboost_model, xgb.sklearn.XGBModel):
        logger.error('XGBoost模型不正确,请重新训练!')
        raise TypeError("XGBoost模型不正确,请重新训练!")
    predictions = xgboost_model.predict(x_test)
    mae = mean_absolute_error(y_test, predictions)
    rmse = np.sqrt(mean_squared_error(y_test, predictions))
    r_square_score = r2_score(y_test, predictions)
    evaluation_criteria = {
            'mae': mae,
            'rmse': rmse,
            'r2': r_square_score
        }
    logger.info('模型评估完成,请查看成员变量 evaluation_criteria')

    # 4.2 获取模型评估结果
    # evaluation_criteria = xgb_reg_helper.evaluation_criteria
    logger.info('模型评估效果: {}', evaluation_criteria)
    # 4.3 获取特征重要性
    #feature_importance = xgb_reg_helper.get_feature_importance()
    """ 返回特征重要性 """
    logger.info(' --- 返回特征重要性')
    #self._check_whether_xgb_model_correct()
    xgboost_model.feature_importances_
    logger.info('模型特征重要性: {}', xgboost_model.feature_importances_)
    # 4.4 绘制特征重要性图像
    # xgb_reg_helper.plot_feature_importance()

    xgb.plot_importance(xgboost_model).set_yticklabels(features_column_names)

    plt.show()


    # 5. 模型预测,预测各个输入回归值
    # (可提供 ndarray 形式入参;如不提供,则预测测试集)
    # predict_result = xgb_reg_helper.predict()
    # logger.info('预测测试集: {}', predict_result)

    """
            执行预测任务。对于分类器,预测结果为类别;对于回归器,预测结果为回归值
                可提供一维 np.ndarray 形式待预测数据,如不提供,则默认使用测试集数据进行预测

            Args:
                x_predict: 一维 np.ndarray 形式待预测数据
            """
    logger.info(' --- 执行预测任务。对于分类器,预测结果为类别;对于回归器,预测结果为回归值')

    # if x_predict:
    #     if not isinstance(x_predict, np.ndarray) or x_predict.ndim != 2:
    #         logger.error('请提供二维 np.ndarray 作为输出')
    #         raise TypeError("请提供二维 np.ndarray 作为输出")
    #     return self.xgboost_model.predict(x_predict)
    predict_result = xgboost_model.predict(x_test)
    logger.info('预测测试集: {}', predict_result)

### XGBoost 模型评估方法 为了有效评估XGBoost模型,通常采用多种技术和指标来衡量其性能。这些技术不仅帮助理解模型的表现,还指导进一步的优化方向。 #### 使用交叉验证提升可靠性 一种常用的技术是交叉验证,它通过将数据集划分为多个子集,在不同的划分上训练和测试模型,从而提供更可靠的性能估计[^1]。这有助于减少过拟合的风险并增强模型泛化能力。 #### 常见评价指标的选择与应用 对于分类任务而言,选择恰当的评价指标至关重要。以下是几种常用的评价指标: - **准确率 (Accuracy)**:表示预测正确的样本占总样本的比例。尽管简单直观,但在类别不平衡的情况下可能具有误导性。 - **精确度 (Precision)** 和 **召回率 (Recall)**:分别反映了正类被正确识别的能力以及所有实际为正类的实例中有多少被成功检测出来。F1分数则是这两者的调和平均数,适用于需要平衡两者的情况。 - **AUC-ROC曲线下的面积 (Area Under the Curve - Receiver Operating Characteristic)**:该值介于0到1之间,越接近1表明区分能力强;特别适合二元分类问题中的概率输出比较。 针对具体应用场景的特点,可以选择最适合当前需求的一个或几个组合起来作为最终评判标准[^2]。 ```python from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score def evaluate_model(y_true, y_pred_proba): # 将概率转换成标签 y_pred = [1 if proba >= 0.5 else 0 for proba in y_pred_proba] acc = accuracy_score(y_true, y_pred) prec = precision_score(y_true, y_pred) rec = recall_score(y_true, y_pred) f1 = f1_score(y_true, y_pred) auc_roc = roc_auc_score(y_true, y_pred_proba) metrics = { 'accuracy': acc, 'precision': prec, 'recall': rec, 'f1-score': f1, 'auc-roc': auc_roc } return metrics ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值