너무 길어서 두 개로 나눠서 포스팅

랜덤포레스트와 다르게 무작위성이 x
매개변수조정이 중요하며 훈련시간이 길다
데이터의 스케일에 구애받지 x
고차원의 희소한 데이터에는 잘 작동하지 x
주요파라미터
loss : 최적화 시킬 손실 함수(squared_error, absolute_error, huber, quantile), default=squared_error
💡 회귀 평가지표로 absolute loss보다 squared loss를 더 많이 사용하는 이유는 무엇일까요?
squared loss에서는 점진적으로 loss가 줄어들 때 기울기가 0에 가까워지는 것을 확인할 수 있지만,
absolute loss에서는 기울기의 부호가 바뀌기 전까지 loss의 변화를 감지할 수 없습니다.
주요 매개변수
최상의 분할을 찾을 때 고려해야 할 기능의 수

GBT의 단점을 개선하고 보완한 것이 아래의 XGBoost, lightgbm, catboost

XGBoost Algorithm: Long May She Reign! | by Vishal Morde | Towards Data Science

주요 매개변수
과적합 방지를 위한 파라미터 조정 방법
plot_importance, plot_tree
xgb.plot_importance(model_xgb)
# from matplotlib.pylab import rcParams
# rcRarams["figure.figsize"]=15,15
# xgb.plot_tree(model_xgb, num_trees=2)
xgb.plot_tree(model_xgb, num_trees=2)
fig=plt.gcf()
fig.set_size_inches(150,100)


max_depth : 나무의 깊이. 단일 결정나무에서는 충분히 데이터를 고려하기 위해 depth를 적당한 깊이로 만들지만, 보정되기 때문에 부스팅에서는 깊이 하나짜리도 만드는 등, 깊이가 짧은것이 크리티컬하지 않음
min_data_in_leaf : 잎이 가질 수 있는 최소 레코드 수, 기본값은 20, 과적합을 다루기 위해 사용
feature_fraction : 부스팅 대상 모델이 랜덤포레스트일때, 랜덤포레스트는 feature의 일부만을 선택하여 훈련하는데, 이를 통제하기 위한 파라미터, 0.8이라면 LightGBM이 각 반복에서 80%의 파라미터를 무작위로 선택하여 트리를 생성
bagging_fraction : 데이터의 일부만을 사용하는 bagging의 비율
예를들어 오버피팅을 방지하기 위해 데이터의 일부만을 가져와서 훈련시키는데, 이는 오버피팅을 방지하며 약한예측기를 모두 합칠경우는 오히려 예측성능이 좋아질 수 있음
훈련 속도를 높이고 과적합을 방지하는 데 사용
early_stopping_round : 더이상 validation데이터에서 정확도가 좋아지지 않으면 멈춰버림 훈련데이터는 거의 에러율이 0에 가깝게 좋아지기 마련인데, validation데이터는 훈련에 사용되지 않기때문에 일정이상 좋아지지 않기 때문
lambda : 정규화에 사용되는 파라미터, 일반적인 값의 범위는 0 ~ 1
min_gain_to_split : 분기가 되는 최소 정보이득, 트리에서 유용한 분할 수를 제어하는 데 사용
max_cat_group : 범주형 변수가 많으면, 하나로 퉁쳐서 처리하게끔 만드는 최소단위
objective : lightgbm은 regression, binary, multiclass 모두 가능
boosting: gbdt(gradient boosting decision tree), rf(random forest), dart(dropouts meet multiple additive regression trees), goss(Gradient-based One-Side Sampling)
num_leaves: 결정나무에 있을 수 있는 최대 잎사귀 수. 기본값은 0.31
learning_rate : 각 예측기마다의 학습률 learning_rate은 아래의 num_boost_round와도 맞춰주어야 함
num_boost_round : boosting을 얼마나 돌릴지 지정한다. 보통 100정도면 너무 빠르게 끝나며, 시험용이 아니면 1000정도 설정하며, early_stopping_round가 지정되어있으면 더이상 진전이 없을 경우 알아서 멈춤
device : gpu, cpu
metric: loss를 측정하기 위한 기준. mae (mean absolute error), mse (mean squared error), 등
max_bin : 최대 bin
categorical_feature : 범주형 변수 지정
ignore_column : 컬럼을 무시한다. 무시하지 않을경우 모두 training에 넣는데, 뭔가 남겨놓아야할 컬럼이 있으면 설정
save_binary: True 메모리 절약
```python
lgbm.plot_importance(model_lgbm)
lgbm.plot_tree(model_lgbm, figsize=(20,20), tree_index=0,
show_info=['split_gain', 'internal_value', 'internal_count', 'leaf_count'])
```
What makes LightGBM lightning fast? | by Abhishek Sharma | Towards Data Science
Features — LightGBM 3.3.2.99 documentation

import catboost
model_cat = catboost.CatBoostRegressor(eval_metric="R2", verbose=False)
from scipy.stats import randint
from sklearn.utils.fixes import loguniform
# SymmetricTree - 대칭트리
# Lossguide - 리프별
# Depthwise - 깊이별
param_grid = {
'n_estimators': randint(100, 300),
'depth': randint(4, 10),
'learning_rate': loguniform(1e-3, 0.1),
'min_child_samples': randint(10, 40),
'grow_policy': ['SymmetricTree', 'Lossguide', 'Depthwise']
}
result = model_cat.randomized_search(param_grid, X_train, y_train, cv=3, n_iter=10)
df_result = pd.DataFrame(result)
df_result = df_result.loc[["train-R2-mean", "test-R2-mean"], "cv_results"]
pd.DataFrame({"train-R2-mean" : df_result.loc["train-R2-mean"],
"test-R2-mean" : df_result.loc["test-R2-mean"] }).plot()

[ML] Unbiased boosting : CatBoost (tistory.com)
# category type 변경
cat_col = train.select_dtypes(include="object").columns
cat_col
for col in cat_col:
train[col] = train[col].astype("category")
test[col] = test[col].astype("category")
train.dtypes
X_train, X_valid, y_train, y_valid = train_test_split(train.drop(columns="y"), train["y"],
train_size = 0.9, random_state=0)

model_lgbm = lgbm.LGBMRegressor(random_state=42)
model_lgbm.fit(X_train, y_train)
model_cat = catboost.CatBoostRegressor(eval_metric='R2', verbose=False,
cat_features=cat_col.tolist())
model_cat.fit(X_train, y_train)

# 점수 산출하는 과정을 함수화합니다.
def scoreModel(model, X_train, X_valid, y_train, y_valid):
'''
머신러닝 모델과 X_train, X_valid, y_train, y_valid 변수를 받아서
모델명, 학습용 세트 정확도(R2 score), 테스트 세트 정확도(R2 score)를 출력하는 함수
'''
print("모델 : {}".format(model))
print("학습용 세트 정확도: {:.3f}".format(model.score(X_train, y_train)))
valid_score = model.score(X_valid, y_valid)
print("검증 세트 정확도: {:.3f}".format(valid_score))
return valid_score