ML之lightgbm.sklearn:LGBMClassifier函数的简介、具体案例、调参技巧之详细攻略
ML之lightgbm.sklearn:LGBMClassifier函數的簡介、具體案例、調參技巧之詳細攻略
?
?
?
?
目錄
LGBMClassifier函數的簡介、具體案例、調參技巧
LGBMClassifier函數的調參技巧
1、lightGBM適合較大數據集的樣本
2、建議使用更小的learning_rate和更大的num_iteration
3、樣本不平衡調參技巧
4、調參時,可將參數字典分為兩大類
LGBMClassifier函數簡介
1、所有弱學習器的參數
2、具體函數解釋
?
?
?
LGBMClassifier函數的簡介、具體案例、調參技巧
LGBMClassifier函數的調參技巧
1、lightGBM適合較大數據集的樣本
而對于較小的數據集(<10000條記錄),lightGBM可能不是最佳選擇。所以,如果進行調優lightgbm參數,這可能沒有幫助。
?
2、建議使用更小的learning_rate和更大的num_iteration
此外,如果您想要更高的num_iteration,那么您應該使用early_stopping_rounds,以便在無法學習任何有用的內容時停止訓練。
?
3、樣本不平衡調參技巧
lightgbm中,可以設置兩個參數is_unbalance和scale_pos_weight。
is_unbalace:當其為True時,算法將嘗試自動平衡占主導地位的標簽的權重(使用列集中的pos/neg分數)
scale_pos_weight:默認1,即假設正負標簽都是相等的。在不平衡數據集的情況下,建議使用以下公式:
sample_pos_weight = number of negative samples / number of positive samples
?
4、調參時,可將參數字典分為兩大類
https://sites.google.com/view/lauraepp/parameters
| 調優參數 | search_params = {'learning_rate': 0.4, ?????????????????'max_depth': 15, ?????????????????'num_leaves': 20, ?????????????????'feature_fraction': 0.8, ?????????????????'subsample': 0.2} |
| 固定參數 | fixed_params={'objective': 'binary', ??????????????'metric': 'auc', ??????????????'is_unbalance':True, ??????????????'boosting':'gbdt', ??????????????'num_boost_round':300, ??????????????'early_stopping_rounds':30} |
?
?
LGBMClassifier函數簡介
LightGBM原論文:https://papers.nips.cc/paper/6907-lightgbm-a-highly-efficient-gradient-boosting-decision-tree
1、所有弱學習器的參數
| 參數及其默認 | 參數解釋及調參技巧 |
| boosting_type='gbdt' | 提升樹的類型,常用的梯度提升方法包括gbdt、dart、goss、rf。可以嘗試運行不同類型的漸變增強提升方法。 (1)、gbdt:這是傳統的梯度提升決策樹,也是基于XGBoost和pGBRT等優秀庫背后的算法。gbdt精度高、效率高、穩定性好,目前已得到廣泛的應用。但是,它的主要缺點是,在每個樹節點中找到最佳分割點非常耗時,而且會消耗內存。下邊其它的提升方法試圖解決這個問題。 (2)、dart:即Dropouts meet Multiple Additive Regression Trees,dart利用dropout技巧(源自深度神經網絡)解決過擬合的Regression Trees,改進模型正則化。gbdt存在過度專門化(over-specialization)的問題,這意味著在以后的迭代中添加的樹往往只會影響對少數實例的預測,而對其余實例的貢獻則可以忽略不計。添加dropout會使樹在以后的迭代中更加難以專門化那些少數的示例,從而提高性能。 它的原理是隨機丟棄生成的決策樹,然后再從剩下的決策樹集中迭代優化提升樹。它的特點是
dart與gbdt的不同點:計算下一棵樹要擬合的梯度的時,僅僅隨機從已經生成的樹中選取一部分。 注意dart添加一棵樹時需要先歸一化。 (3)、goss :基于梯度的單邊采樣,該方法命名為lightgbm的最重要原因就是其使用了基于Goss方法。goss的基本思想是首先對訓練集數據根據梯度排序,預設一個比例劃分梯度大小,保留在所有樣本中梯度大的數據樣本;再設置一個采樣比例,從梯度小的樣本中按比例抽取樣本。為了彌補對樣本分布造成的影響,goss算法在計算信息增益時,會對較小梯度的數據集乘以一個系數,用來放大。這樣,在計算信息增益時,算法可以更加關注“未被充分訓練”的樣本數據。 ????????goss通過對較小的樣本數據集估算增益,大大的減少了計算量。而且通過證明,goss算法不會過多的降低訓練的精度。 標準的gbdt是可靠的,但在大型數據集上速度不夠快。因此goss提出了一種基于梯度的采樣方法來避免搜索整個搜索空間。其實,對于每個數據實例,當梯度很小時,這意味著不用擔心數據是經過良好訓練的,而當梯度很大時,應該重新訓練。數據實例有大的和小的漸變。因此,goss以一個大的梯度保存所有數據,并對一個小梯度的數據進行隨機抽樣(這就是為什么它被稱為單邊抽樣)。這使得搜索空間更小,goss的收斂速度更快。 (4)、rf?:隨機森林。切記,如果將增強設置為rf,那么lightgbm算法表現為隨機森林而不是增強樹。根據文檔可知,要使用rf,必須使用bagging_fraction和feature_fraction小于1。 |
| objective ='binary' | 目標,"regression"、"binary" |
| metric='binary_logloss' | 模型度量標準,"rmse"、"auc"、'binary_logloss' |
| learning_rate=0.1 | 學習率 |
| n_estimators=10 | 擬合的樹的棵樹,可以理解為訓練的輪數。 弱學習器的個數,其中gbdt原理是利用通過梯度不斷擬合新的弱學習器,直到達到設定的弱學習器的數量。 |
| max_depth=-1 | 最大樹的深度。每個弱學習器也就是決策樹的最大深度。 其中,-1表示不限制。 |
| num_leavel=32 | 樹的最大葉子數,控制模型復雜性的最重要參數之一。對比在xgboost中,一般為2^(max_depth) 因LightGBM使用的是leaf-wise的算法,因此在調節樹的復雜程度時,使用的是num_leaves而不是max_depth。它們之間大致換算關系:num_leaves = 2^(max_depth)。即它的值的設置應該小于2^(max_depth),否則會進行警告,可能會導致過擬合。 |
| bagging_freq=15 | 控制過擬合。 |
| bagging_fraction= 0.8 | 子樣例,來控制過擬合。 可以指定每個樹構建迭代使用的行數百分比。這意味著將隨機選擇一些行來匹配每個學習者(樹)。這不僅提高了泛化能力,也提高了訓練速度。 |
| feature_fraction=0.8 | 子特征處理列采樣,來控制過擬合。 它將在每次迭代(樹)上隨機選擇特征子集。例如,如果將其設置為0.8,它將在訓練每棵樹之前選擇60%的特性。它常用來加速訓練和處理過擬合。 |
| subsample=1.0 | 訓練樣本采樣率,行 |
| colsample_bytree=1.0? | 訓練特征采樣率,列 |
| subsample_freq=1 | 子樣本頻率 |
| reg_alpha=0.5 | L1正則化系數 |
| reg_lambda=0.5 | L2正則化系數 |
| min_split_gain=0.0 | 最小分割增益 |
| min_child_weight=0.001? | 分支結點的最小權重 |
| min_child_samples=20 | ? |
| random_state=None | 隨機種子數 |
| n_jobs=-1 | 并行運行多線程核心數 |
| silent=True | 訓練過程是否打印日志信息 |
| verbose=-1 | ? |
?
2、具體函數解釋
| class LGBMClassifier?Found at: lightgbm.sklearn ? class LGBMClassifier(LGBMModel, _LGBMClassifierBase): ????"""LightGBM classifier.""" ????def fit(self, X, y, ????????sample_weight=None, init_score=None, ????????eval_set=None, eval_names=None, eval_sample_weight=None, ????????eval_class_weight=None, eval_init_score=None, eval_metric=None, ????????early_stopping_rounds=None, verbose=True, ????????feature_name='auto', categorical_feature='auto', callbacks=None): ????????"""Docstring is inherited from the LGBMModel.""" ????????_LGBMAssertAllFinite(y) ????????_LGBMCheckClassificationTargets(y) ????????self._le = _LGBMLabelEncoder().fit(y) ????????_y = self._le.transform(y) ????????self._classes = self._le.classes_ ????????self._n_classes = len(self._classes) ????????if self._n_classes > 2: ????????# Switch to using a multiclass objective in the underlying LGBM ?????????instance ????????????ova_aliases = "multiclassova", "multiclass_ova", "ova", "ovr" ????????????if self._objective not in ova_aliases and not callable(self. ?????????????_objective): ????????????????self._objective = "multiclass" ????????????if eval_metric in ('logloss', 'binary_logloss'): ????????????????eval_metric = "multi_logloss" ????????????elif eval_metric in ('error', 'binary_error'): ????????????????eval_metric = "multi_error" ????????elif eval_metric in ('logloss', 'multi_logloss'): ????????????eval_metric = 'binary_logloss' ????????elif eval_metric in ('error', 'multi_error'): ????????????eval_metric = 'binary_error' ????????if eval_set is not None: ????????????if isinstance(eval_set, tuple): ????????????????eval_set = [eval_set] ????????????for i, (valid_x, valid_y) in enumerate(eval_set): ????????????????if valid_x is X and valid_y is y: ????????????????????eval_set[i] = valid_x, _y ????????????????else: ????????????????????eval_set[i] = valid_x, self._le.transform(valid_y) ???????? ????????super(LGBMClassifier, self).fit(X, _y, sample_weight=sample_weight, ?????????init_score=init_score, eval_set=eval_set, eval_names=eval_names, ?????????eval_sample_weight=eval_sample_weight, ?????????eval_class_weight=eval_class_weight, eval_init_score=eval_init_score, ?????????eval_metric=eval_metric, ?????????early_stopping_rounds=early_stopping_rounds, verbose=verbose, ?????????feature_name=feature_name, categorical_feature=categorical_feature, ?????????callbacks=callbacks) ????????return self ???? ????fit.__doc__ = LGBMModel.fit.__doc__ ????def predict(self, X, raw_score=False, num_iteration=None, ????????pred_leaf=False, pred_contrib=False, **kwargs): ????????"""Docstring is inherited from the LGBMModel.""" ????????result = self.predict_proba(X, raw_score, num_iteration, ????????????pred_leaf, pred_contrib, **kwargs) ????????if raw_score or pred_leaf or pred_contrib: ????????????return result ????????else: ????????????class_index = np.argmax(result, axis=1) ????????????return self._le.inverse_transform(class_index) ???? ????predict.__doc__ = LGBMModel.predict.__doc__ ????def predict_proba(self, X, raw_score=False, num_iteration=None, ????????pred_leaf=False, pred_contrib=False, **kwargs): ????????"""Return the predicted probability for each class for each sample.?返回每個類和每個樣本的預測概率。 | ? |
| ????????Parameters ????????---------- ????????X?: array-like or sparse matrix of shape = [n_samples, n_features]?Input features matrix. ????????raw_score?: bool, optional?(default=False). Whether to predict raw scores. ????????num_iteration?: int or None, optional (default=None). Limit number of iterations in the prediction.?If None, if the best iteration exists, it is used; otherwise, all trees are used.??If <= 0, all trees are used (no limits). ????????pred_leaf?: bool, optional (default=False). Whether to predict leaf index. ????????pred_contrib?: bool, optional (default=False). Whether to predict feature contributions. ????????????Note ????????????---- ????????????If you want to get more explanation for your model's predictions using SHAP values?like SHAP interaction values,?you can install shap package (https://github.com/slundberg/shap). ? ????????**kwargs ????????????Other parameters for the prediction. ????????Returns ????????------- ????????predicted_probability?: array-like of shape = [n_samples, n_classes]. The predicted probability for each class for each sample. ????????X_leaves?: array-like of shape = [n_samples, n_trees * n_classes]. If ``pred_leaf=True``, the predicted leaf every tree for each sample. ????????X_SHAP_values?: array-like of shape = [n_samples, (n_features + 1) *n_classes]. If ``pred_contrib=True``, the each feature contributions for each sample. ????????""" ????????result = super(LGBMClassifier, self).predict(X, raw_score, num_iteration,?pred_leaf, pred_contrib, **kwargs). if self._n_classes > 2 or pred_leaf or pred_contrib: ????????????return result ????????else: ????????????return np.vstack((1. - result, result)).transpose() | 參數 ---------- X:?類數組形狀或稀疏矩陣= [n_samples, n_features]輸入特征矩陣。 raw_score?: bool,可選(默認=False)。是否預測原始分數。 num_iteration:??int或None,可選(默認=None)。預測中的極限迭代次數。如果沒有,如果存在最好的迭代,就使用它;否則,使用所有樹。如果<= 0,則使用所有樹(沒有限制)。 pred_leaf: ?bool,可選(默認=False)。是否預測葉指數。 pred_contrib: ?bool,可選(默認=False)。是否預測特性貢獻。 請注意 ---- 如果您想使用SHAP值(如SHAP交互值)對模型的預測進行更多的解釋,您可以安裝SHAP包(https://github.com/slundberg/shap)。 ? * * kwargs 用于預測的其他參數。 返回 ------- predicted_probability?: 類數組形狀= [n_samples, n_classes]。每個類,每個樣本的預測概率。 X_leaves:?類數組的形狀= [n_samples, n_trees * n_classes]。如果' ' pred_leaf=True ' ',則為每個樣本的每棵樹預測的葉。 X_SHAP_values:?類數組形狀= [n_samples, (n_features + 1) *n_classes]。如果' ' pred_contrib=True ' ',則每個特性為每個示例貢獻。 ? """ ????????result = super(LGBMClassifier, self).predict(X, raw_score, num_iteration,?pred_leaf, pred_contrib, **kwargs). if self._n_classes > 2 or pred_leaf or pred_contrib: ????????????return result ????????else: ????????????return np.vstack((1. - result, result)).transpose() |
| ???????@property ????def classes_(self): ????????"""Get the class label array.""" ????????if self._classes is None: ????????????raise LGBMNotFittedError('No classes found. Need to call fit ?????????????beforehand.') ????????return self._classes ???? ????@property ????def n_classes_(self): ????????"""Get the number of classes.""" ????????if self._n_classes is None: ????????????raise LGBMNotFittedError('No classes found. Need to call fit ?????????????beforehand.') ????????return self._n_classes | ? |
?
?
?
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的ML之lightgbm.sklearn:LGBMClassifier函数的简介、具体案例、调参技巧之详细攻略的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在Controll 获取数据库数据
- 下一篇: CSRF(Cross-site requ