zoukankan      html  css  js  c++  java
  • 【ML-6-4-2】xgboost的python参数说明

    目录

    1. 核心数据结构
    2. 学习API
    3. Scikit-Learn API
    4. 绘图API
    5. 回调API
    6. Dask API

         

    一、核心数据结构

    class xgboost.DMatrix(data, label=None, weight=None, base_margin=None, missing=None, silent=False, feature_names=None, feature_types=None, nthread=None, enable_categorical=False)

    XGBoost中使用的数据矩阵。

    DMatrix是XGBoost使用的内部数据结构,它针对内存效率和训练速度进行了优化。您可以从多个不同的数据源构造DMatrix。

    Parameters

    data (os.PathLike/string/numpy.array/scipy.sparse/pd.DataFrame/) – dt.Frame/cudf.DataFrame/cupy.array/dlpack Data source of DMatrix. When data is string or os.PathLike type, it represents the path libsvm format txt file, csv file (by specifying uri parameter 'path_to_csv?format=csv'), or binary file that xgboost can read from.

       

    label (list, numpy 1-D array or cudf.DataFrame, optional) – Label of the training data.

       

    missing (float, optional) – Value in the input data which needs to be present as a missing value. If None, defaults to np.nan.

       

    weight (list, numpy 1-D array or cudf.DataFrame , optional) –

    Weight for each instance.

       

    silent (boolean, optional) – Whether print messages during construction

       

    feature_names (list, optional) – Set names for features.

       

    feature_types (list, optional) – Set types for features.

       

    nthread (integer, optional) – Number of threads to use for loading data when parallelization is applicable. If -1, uses maximum threads available on the system.

       

    enable_categorical (boolean, optional) –

    save_binaryfnamesilent = True

    将DMatrix保存到XGBoost缓冲区。保存的二进制文件可以稍后通过提供路径xgboost.DMatrix()作为输入来加载。

    参量

    fname(字符串或os.PathLike)–输出缓冲区文件的名称。

    静音(bool(可选;默认:True ))–如果设置,则抑制输出。

       

    二、学习API

    xgboost.train(params, dtrain, num_boost_round=10, evals=(), obj=None, feval=None, maximize=None, early_stopping_rounds=None, evals_result=None, verbose_eval=True, xgb_model=None, callbacks=None)

    参量Parameters

    参量

    params(dict)-booster参数。

    dtrain(DMatrix)–要训练的数据。

    num_boost_round(int)–提升迭代的次数。

    early_stopping_rounds(int)–激活提前停止。验证指标需要在每个Early_stopping_rounds回合中至少改善一次,以继续训练。至少需要eval个项目。该方法从上次迭代(不是最佳迭代)返回模

    • evals_result (dict) –
      This dictionary stores the evaluation results of all the items in watchlist.
      Example: with a watchlist containing [(dtest,'eval'), (dtrain,'train')] and a parameter containing ('eval_metric': 'logloss'), the evals_result returns
      {'train': {'logloss': ['0.48253', '0.35953']},
       'eval': {'logloss': ['0.480385', '0.357756']}}
    • verbose_eval (bool or int) – Requires at least one item in evals. If verbose_eval is True then the evaluation metric on the validation set is printed at each boosting stage. If verbose_eval is an integer then the evaluation metric on the validation set is printed at every given verbose_evalboosting stage. The last boosting stage / the boosting stage found by using early_stopping_rounds is also printed. Example: with verbose_eval=4 and at least one item in evals, an evaluation metric is printed every 4 boosting stages, instead of every boosting stage.
    • xgb_model (file name of stored xgb model or 'Booster' instance) – Xgb model to be loaded before training (allows training continuation).(存储的xgb模型或“ Booster”实例的文件名)–训练之前要加载的Xgb模型(允许继续训练)。
    • callbacks (list of callback functions) –
      List of callback functions that are applied at end of each iteration. It is possible to use predefined callbacks by using Callback API. Example:
      [xgb.callback.reset_learning_rate(custom_rates)]

    Returns

    Booster

    Return type

    a trained booster model

    其它参数看官网。

    xgboost.cv(params, dtrain, num_boost_round=10, nfold=3, stratified=False, folds=None, metrics=(), obj=None, feval=None, maximize=None, early_stopping_rounds=None, fpreproc=None, as_pandas=True, verbose_eval=None, show_stdv=True, seed=0, callbacks=None, shuffle=True)

    Cross-validation with given parameters.

    参数Parameters

    params (dict) – Booster params.

    dtrain (DMatrix) – Data to be trained.

    num_boost_round (int) – Number of boosting iterations.

    nfold (int) – Number of folds in CV.

    early_stopping_rounds(int)–激活提前停止。交叉验证度量标准(通过CV折叠计算得出的验证度量标准的平均值)需要在每一轮Early_stopping_rounds中至少提高一次,以继续进行训练。评估历史记录中的最后一个条目将代表最佳迭代。如果在params中给定的eval_metric参数中 有多个度量标准,则最后一个度量标准将用于提前停止。

       

    三、Scikit-Learn API

    类:class xgboost.XGBRegressor(objective='reg:squarederror', **kwargs)

    参量

    n_estimators(int)–梯度增强树的数量。相当于轮数。

    max_depth(int)–基础学习者的最大树深度。

    learning_rate(float)–提高学习率(xgb的" eta")

    verbosity(int)–详细程度。有效值为0(静默)-3(调试)。

    目标(字符串或可调用的)–指定学习任务和要使用的相应学习目标或自定义目标函数(请参见下面的注释)。

    booster(string)–指定要使用的助推器:gbtree,gblinear或dart。

    tree_method(字符串)–指定要使用的树方法。默认为自动。如果将此参数设置为默认值,则XGBoost将选择最保守的选项。建议从参数文档中研究此选项,也可以上一篇文章查找。

    n_jobs(int)–用于运行xgboost的并行线程数。与网格搜索等其他Scikit-Learn算法结合使用时,您可以选择哪种算法可以并行化和平衡线程。创建线程争用将显着减慢两种算法的使用速度。

    gamma(float)–在树的叶子节点上进行进一步分区所需的最小损失减少。

    min_child_weight(float)–子实例所需实例重量(hessian)的最小总和。

    max_delta_step(int)–我们允许每棵树的权重估计为最大增量步长。

    subsample (float) –训练实例的子样本比率。

    colsample_bytree(float)–构造每棵树时列的子采样率。

    colsample_bylevel(float)–每个级别的列的子采样率。

    colsample_bynode(float)–每个拆分列的子采样率。

    reg_alpha(float(xgb's alpha ))–权重的L1正则化项

    reg_lambda(float(xgb的lambda ))–权重的L2正则化项

    scale_pos_weight(float)–正负负平衡。

    base_score –所有实例的初始预测分数,全局偏差。

    random_state(int)–随机数种子。

    missing (float, default np.nan) –数据中需要以缺失值形式显示的值。

    num_parallel_tree(int)–用于增强随机森林。

    monotone_constraints(str)–可变单调性的约束。有关更多信息,请参见教程。

    interact_constraints(str)–表示允许的交互的交互约束。约束必须以嵌套列表的形式指定,例如[[0,1],[2、3、4]],其中每个内部列表都是一组允许相互交互的要素索引。有关更多信息,请参见教程

    Important_type(字符串,默认为" gain")– feature_importances_属性的特征重要性类型:" gain"," weight"," cover"," total_gain"或" total_cover"。

    ** kwargs(字典,可选)–

    类的方法:applyXntree_limit = 0

    返回每个样本的每棵树的预测叶。

    参量

    X(array_like ,shape = [ n_samples ,n_features ])–输入要素矩阵。

    ntree_limit(int)–预测中限制树的数量;默认为0(使用所有树)。

    Returns

    X_leaves – For each datapoint x in X and for each tree, return the index of the leaf x ends up in. Leaves are numbered within [0; 2**(self.max_depth+1)), possibly with gaps in the numbering.

    Return type

    array_like, shape=[n_samples, n_trees]

    类方法evals_result()

    返回评估结果。

    如果将eval_set传递给fit函数,则可以调用 evals_result()以获取所有传递的eval_sets的评估结果。当eval_metric也传递给fit函数时, evals_result将包含传递给fit函数的eval_metrics。

    返回类型:字典

    property feature_importances_

    Feature importances property

    fit(X, y, sample_weight=None, base_margin=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True, xgb_model=None, sample_weight_eval_set=None, feature_weights=None, callbacks=None)

    参量

    X(array_like)–特征矩阵

    y(array_like)–标签

    sample_weight(array_like)–实例权重

    base_margin(array_like)–每个实例的全局偏差。

    eval_set(list,optional)–用作验证集的(X,y)元组对的列表,将为其计算指标。验证指标将帮助我们跟踪模型的性能。

    eval_metric(str,str列表或callable ,可选)–如果为str,则应作为内置评估指标使用。请参阅doc / parameter.rst。如果为str的列表,则应为要使用的多个内置评估指标的列表。如果可以调用,则为自定义评估指标。呼叫签名是这里将是一个DMatrix对象,这样你可能需要调用的 方法。它必须返回一个str值对,其中str是求值的名称,value是求值函数的值。可调用的自定义目标总是最小化。func(y_predicted, y_true)y_trueget_label

    early_stopping_rounds(int)–激活提前停止。验证指标需要在每个Early_stopping_rounds回合中至少改善一次,以继续训练。在eval_set中至少需要一项。该方法从上次迭代(不是最佳迭代)返回模型。如果eval_set中有多个项目,则最后一个条目将用于提前停止。如果eval_metric中有多个指标,则最后一个指标将用于提前停止。如果发生提早终止,该模型将有三个附加字段: clf.best_score,clf.best_iteration和clf.best_ntree_limit。

    verbose(bool)–如果使用冗长和评估集,则将在验证集上测得的评估指标写入stderr。

    xgb_model(str)–file name of stored XGBoost model or 'Booster' instance XGBoost model to be loaded before training (allows training continuation).----在训练之前要加载的已存储XGBoost模型或" Booster"实例XGBoost模型的文件名(允许继续训练)。

    sample_weight_eval_set(列表,可选)–形式为[L_1,L_2,…,L_n]的列表,其中每个L_i是第i个验证集上的实例权重的列表。

    feature_weights(array_like)–每个要素的权重,定义使用colsample时每个要素被选中的概率。所有值必须大于0,否则将引发ValueError。

    回调(回调函数列表)–

    在每次迭代结束时应用的回调函数列表。通过使用Callback API可以使用预定义的回调。例:

    [xgb.callback.reset_learning_rate(custom_rates)]

    get_booster()

    Get the underlying xgboost Booster of this model.

    This will raise an exception when fit was not called

    Returns

    booster

    Return type

    a xgboost booster of underlying model

    get_num_boosting_rounds()

    获取xgboost提升回合的数量。

    get_paramsdeep = True

    获取参数。

    get_xgb_params()

    获取特定于xgboost的参数。

    load_modelfname

    从文件加载模型。

    该模型是从XGBoost内部格式加载的,该格式在各种XGBoost接口中通用。Python Booster对象的辅助属性(例如功能名称)将不会加载。

    参量

    fname(字符串)–输入文件名。

    predict(数据,output_margin = Falsentree_limit = Nonevalidate_features = Truebase_margin = None

    用数据预测

    参量

    数据(numpy.array / scipy.sparse)–要进行预测的数据

    output_margin(bool)–是否输出未转换的原始余量值。

    ntree_limit(int)–预测中限制树的数量;如果定义,则默认为best_ntree_limit(即已经过提早停止训练),否则为0(使用所有树)。

    validate_features(bool)–为True时,请验证Booster和数据的feature_name是相同的。否则,假定feature_names相同。

    返回类型

    numpy数组

    save_modelfname str

    将模型保存到文件。

    模型以XGBoost内部格式保存,该格式在各种XGBoost接口中通用。Python Booster对象的辅助属性(例如功能名称)将不会保存。

    参量

    fname(字符串)–输出文件名

       

    class xgboost.XGBClassifier(objective='binary:logistic', **kwargs)

    Bases: xgboost.sklearn.XGBModel, object

    Implementation of the scikit-learn API for XGBoost classification.

    和上面的类:class xgboost.XGBRegressor(objective='reg:squarederror', **kwargs)参数和方法基本相同。下面介绍不同部分:

       

    class xgboost.XGBRanker(objective='rank:pairwise', **kwargs)

    Bases: xgboost.sklearn.XGBModel

    Implementation of the Scikit-Learn API for XGBoost Ranking.

    和上面的类:class xgboost.XGBRegressor(objective='reg:squarederror', **kwargs)参数和方法基本相同。下面介绍不同部分

       

    class xgboost.XGBRFRegressor(learning_rate=1, subsample=0.8, colsample_bynode=0.8, reg_lambda=1e-05, **kwargs)

    Bases: xgboost.sklearn.XGBRegressor

    scikit-learn API for XGBoost random forest regression.

    和上面的类:class xgboost.XGBRegressor(objective='reg:squarederror', **kwargs)参数和方法基本相同。下面介绍不同部分

       

    class xgboost.XGBRFClassifier(learning_rate=1, subsample=0.8, colsample_bynode=0.8, reg_lambda=1e-05, **kwargs)

    Bases: xgboost.sklearn.XGBClassifier

    scikit-learn API for XGBoost random forest classification.

    和上面的类:class xgboost.XGBRegressor(objective='reg:squarederror', **kwargs)参数和方法基本相同。下面介绍不同部分

    四、绘图API-Plotting API

    xgboost.plot_importance(booster, ax=None, height=0.2, xlim=None, ylim=None, title='Feature importance', xlabel='F score', ylabel='Features', fmap='', importance_type='weight', max_num_features=None, grid=True, show_values=True, **kwargs)

    Plot importance based on fitted trees. 根据拟合的树绘制重要性。

       

    xgboost.plot_tree(booster, fmap='', num_trees=0, rankdir=None, ax=None, **kwargs)

    Plot specified tree.

    将指定的树转换为graphviz实例。IPython可以自动绘制返回的graphiz实例。否则,您应该调用返回的graphiz实例的.render()方法。

       

    五、回调API --Callback API

    xgboost.callback.print_evaluation(period=1show_stdv=True)

    Create a callback that print evaluation result.

    We print the evaluation results every period iterations and on the first and the last iterations.

    Parameters

    • period (int) – The period to log the evaluation results
    • show_stdv (bool, optional) – Whether show stdv if provided

    Returns

    callback – A callback that print evaluation every period iterations.

    Return type

    function

    xgboost.callback.record_evaluation(eval_result)

    Create a call back that records the evaluation history into eval_result.

    Parameters

    eval_result (dict) – A dictionary to store the evaluation results.

    Returns

    callback – The requested callback function.

    Return type

    function

    xgboost.callback.reset_learning_rate(learning_rates)

    Reset learning rate after iteration 1

    NOTE: the initial learning rate will still take in-effect on first iteration.

    xgboost.callback.early_stop(stopping_roundsmaximize=Falseverbose=True)

    Create a callback that activates early stoppping.

    Validation error needs to decrease at least every stopping_rounds round(s) to continue training. Requires at least one item in evals. If there's more than one, will use the last. Returns the model from the last iteration (not the best one). If early stopping occurs, the model will have three additional fields:bst.best_scorebst.best_iteration and bst.best_ntree_limit. (Use bst.best_ntree_limit to get the correct value if num_parallel_tree and/or num_class appears in the parameters)

    来自 <https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.training>

       

    六、Dask API

    分布式扩展的Dask扩展。有关简单的教程,请参见 https://xgboost.readthedocs.io/en/latest/tutorials/dask.html。还有一些示例的xgboost / demo / dask。

       

    此模块中有两套API,一类是功能性API,包括 train和predict方法。另一个是从单节点Scikit-Learn接口继承的有状态Scikit-Learner包装器。

       

    该实现受到dask_xgboost的严重影响:https : //github.com/dask/dask-xgboost

       

    更多信息,强烈推荐:

    https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.training

  • 相关阅读:
    [RxJS] Filtering operators: throttle and throttleTime
    [RxJS] Transformation operators: debounce and debounceTime
    [AngularJS] Default Child state and nav between child state
    [RxJS] Transformation operator: bufferToggle, bufferWhen
    [RxJS] Transformation operators: delay and delayWhen
    [RxJS] Transformation operator: buffer, bufferCount, bufferTime
    [RxJS] Transformation operator: scan
    [置顶] 利用Global.asax的Application_Error实现错误记录,错误日志
    Java方法重写与方法重载
    Inside GDALAllRegister之一: 五大部分
  • 原文地址:https://www.cnblogs.com/yifanrensheng/p/13859333.html
Copyright © 2011-2022 走看看