
如何高效爬取全球新聞網站 – 整合Scrapy、Selenium與Mediastack API實現自動化新聞采集
XGBoost 是 GBDT 的優化版本,核心思想仍然是梯度提升,但它在計算效率、模型精度等方面進行了多種優化。它通過使用正則化控制模型復雜度,防止過擬合,并且支持分布式計算和多線程并行,提升了計算速度。
LightGBM 是一個高效的梯度提升框架,專為大數據集和高維數據集設計。LightGBM 使用基于直方圖(Histogram-based)的決策樹構建方法,并在算法設計上引入了多個優化,如葉節點按深度生長(Leaf-wise Growth)、GOSS(Gradient-based One-Side Sampling)等技術,來提升訓練速度和資源利用率。
LightGBM 仍然基于梯度提升的基本思想,但其改進在于:
模型 | 優點 | 缺點 | 適用場景 |
---|---|---|---|
GBDT | 穩定,適合小數據集;無需特征歸一化和特征工程 | 訓練時間較長,無法并行處理,調參復雜 | 小數據集的分類和回歸任務 |
XGBoost | 支持并行計算,加入正則化防止過擬合;訓練速度快 | 內存占用大,調參復雜 | 大規模數據集的分類、回歸、排序 |
LightGBM | 訓練速度快,適合大規模數據;內存占用少 | 對小數據集不如 XGBoost 穩定,模型解釋性較差 | 超大規模數據集,高維任務 |
總結來說:
最后,咱們舉一個全面的案例進行比較,大家也有一個更加深層次的理解~
案例標題:GBDT vs. XGBoost vs. LightGBM:集成學習模型的性能與適用性對比
在該案例中,我們希望解決一個典型的分類問題,即對虛擬數據集中的數據點進行準確分類。數據集將具有較大的維度和噪聲。我們比較三種算法模型(GBDT、XGBoost和LightGBM)在分類任務中的性能和適用性,包括訓練速度、模型性能(如AUC-ROC)、調參難度和模型的可擴展性。
我們將生成一個虛擬的二分類數據集,其中包含2個類別的樣本,并具有100個特征,部分特征具有噪聲。通過對比XGBoost、LightGBM和GBDT的分類效果、訓練速度和模型復雜性,得出適用性結論。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import roc_auc_score, accuracy_score, roc_curve
from sklearn.ensemble import GradientBoostingClassifier
from xgboost import XGBClassifier
import lightgbm as lgb
import time
# 數據集
X, y = make_classification(n_samples=10000, n_features=100, n_informative=10,
n_redundant=10, n_classes=2, random_state=42, flip_y=0.01)
# 劃分數據集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 訓練模型、性能指標的功能
def evaluate_model(model, X_train, y_train, X_test, y_test):
start_time = time.time()
model.fit(X_train, y_train)
train_time = time.time() - start_time
y_pred = model.predict(X_test)
y_pred_prob = model.predict_proba(X_test)[:, 1]
accuracy = accuracy_score(y_test, y_pred)
roc_auc = roc_auc_score(y_test, y_pred_prob)
return train_time, accuracy, roc_auc
# 1. GBDT model
gbdt = GradientBoostingClassifier()
gbdt_time, gbdt_accuracy, gbdt_auc = evaluate_model(gbdt, X_train, y_train, X_test, y_test)
# 2. XGBoost model
xgb = XGBClassifier(use_label_encoder=False, eval_metric='logloss')
xgb_time, xgb_accuracy, xgb_auc = evaluate_model(xgb, X_train, y_train, X_test, y_test)
# 3. LightGBM model
lgbm = lgb.LGBMClassifier()
lgbm_time, lgbm_accuracy, lgbm_auc = evaluate_model(lgbm, X_train, y_train, X_test, y_test)
# 比較結果
print(f"GBDT - Time: {gbdt_time:.2f}s, Accuracy: {gbdt_accuracy:.4f}, AUC: {gbdt_auc:.4f}")
print(f"XGBoost - Time: {xgb_time:.2f}s, Accuracy: {xgb_accuracy:.4f}, AUC: {xgb_auc:.4f}")
print(f"LightGBM - Time: {lgbm_time:.2f}s, Accuracy: {lgbm_accuracy:.4f}, AUC: {lgbm_auc:.4f}")
使用GridSearchCV進行XGBoost和LightGBM模型的超參數調優,并記錄調參前后的性能變化。
# XGBoost超參數調整
xgb_params = {
'n_estimators': [50, 100],
'learning_rate': [0.01, 0.1],
'max_depth': [3, 6, 9]
}
grid_xgb = GridSearchCV(XGBClassifier(use_label_encoder=False, eval_metric='logloss'), xgb_params, cv=3, scoring='roc_auc')
grid_xgb.fit(X_train, y_train)
print("Best XGBoost Parameters:", grid_xgb.best_params_)
xgb_best = grid_xgb.best_estimator_
# LightGBM超參數調整
lgb_params = {
'n_estimators': [50, 100],
'learning_rate': [0.01, 0.1],
'max_depth': [3, 6, 9]
}
grid_lgbm = GridSearchCV(lgb.LGBMClassifier(), lgb_params, cv=3, scoring='roc_auc')
grid_lgbm.fit(X_train, y_train)
print("Best LightGBM Parameters:", grid_lgbm.best_params_)
lgbm_best = grid_lgbm.best_estimator_
接下來,我們將通過繪制ROC曲線、訓練時間對比條形圖以及AUC-ROC對比圖來進行不同模型的性能對比。
# Plot ROC curves
def plot_roc_curve(models, X_test, y_test, title):
plt.figure(figsize=(10, 6))
for name, model in models.items():
y_pred_prob = model.predict_proba(X_test)[:, 1]
fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
plt.plot(fpr, tpr, label=f"{name} (AUC = {roc_auc_score(y_test, y_pred_prob):.4f})")
plt.plot([0, 1], [0, 1], 'k--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title(title)
plt.legend(loc="lower right")
plt.show()
# Model ROC Curves
models = {
"GBDT": gbdt,
"XGBoost": xgb_best,
"LightGBM": lgbm_best
}
plot_roc_curve(models, X_test, y_test, "ROC Curves for GBDT, XGBoost, and LightGBM")
# Plot training time comparison
def plot_training_time(times, title):
plt.figure(figsize=(8, 5))
model_names = ['GBDT', 'XGBoost', 'LightGBM']
plt.barh(model_names, times, color=['#FF6347', '#4682B4', '#32CD32'])
plt.xlabel('Training Time (seconds)')
plt.title(title)
plt.show()
train_times = [gbdt_time, xgb_time, lgbm_time]
plot_training_time(train_times, 'Training Time Comparison')
# Plot AUC comparison
def plot_auc_comparison(aucs, title):
plt.figure(figsize=(8, 5))
model_names = ['GBDT', 'XGBoost', 'LightGBM']
plt.barh(model_names, aucs, color=['#FF6347', '#4682B4', '#32CD32'])
plt.xlabel('AUC Score')
plt.title(title)
plt.show()
aucs = [gbdt_auc, xgb_auc, lgbm_auc]
plot_auc_comparison(aucs, 'AUC Score Comparison')
訓練時間:10000條數據訓練模型情況下,XGBoost表現出最快的訓練速度,緊隨其后的是LightGBM,而GBDT速度最慢。這表明XGBoost在比較大的數據場景中的計算效率優勢。如果在再大規模的數據集下,可能LightGBM要比XGBoost更快速。
GBDT - Time: 21.93s, Accuracy: 0.9100, AUC: 0.9694
XGBoost - Time: 0.86s, Accuracy: 0.9245, AUC: 0.9781
LightGBM - Time: 1.66s, Accuracy: 0.9305, AUC: 0.9793
AUC評分:XGBoost和LightGBM在AUC評分上略高于GBDT,說明它們在處理該分類問題時的性能更好。
調參復雜度:LightGBM和XGBoost都有較多可調節的超參數,但XGBoost由于其算法復雜度,調參更加繁瑣,而LightGBM相對容易。
通過對比不同的集成學習模型,我們發現XGBoost和LightGBM在分類任務上不僅表現優異,而且擁有更快的訓練速度和更好的擴展性。使用這些算法,我們提升了分類準確率和模型訓練速度。
這個是在10000數據量下的測試,在不同的數據量和不同情況下,表現還會不同。總的來說,XGBoost和LightGBM會更加的高效。