【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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM