
XGBoost - 自舉法
自舉法可以與可替換抽樣相結合,對資料進行重取樣並生成許多訓練集。因此,XGBoost 中的自舉策略可以定義為一種方法,在這種方法中,我們在資料的許多隨機子集上訓練模型以改進它。
它是如何工作的?
為每個重取樣集訓練一個 XGBoost 模型,並對測試資料點生成預測。這些預測的分佈提供了對預測不確定性的粗略估計。
因此,XGBoost 中的自舉策略指的是透過在資料的許多隨機子集上訓練模型來改進模型的一種方法。
XGBoost 生成大量的小模型,每個模型都在可用資料的一部分上進行訓練。這種隨機抽樣稱為“自舉”。XGBoost 組合這些小模型的輸出,並在資料的各種子集上進行訓練,以生成單個強大的預測。
透過使用不同的隨機樣本,此策略試圖減少錯誤並提高模型準確性。它還有助於 XGBoost 模型避免過擬合,過擬合是指模型在訓練資料上表現良好但在新資料上表現不佳的情況。
這類似於人們透過獲得新經驗來學習的方式。
將自舉法應用於模型
正如我們在自舉法中所看到的,使用訓練資料的重取樣版本訓練多個模型,並將其預測結果結合起來。基本思想是隨機選擇資料,自舉多個模型,然後對以前從未見過的測試資料進行預測。透過平均預測並計算其可變性,我們可以生成置信區間,顯示預測中不確定性的程度。
因此,讓我們看看將自舉法應用於 XGBoost 模型的步驟 -
1. 匯入必要的庫並生成合成資料
首先,我們將載入 XGBoost、NumPy 和 Matplotlib 等庫來訓練和分析模型。接下來,我們生成合成資料來訓練模型。
# Importing libraries here import xgboost as xgb import numpy as np import matplotlib.pyplot as plt # Generate random training and testing data np.random.seed(123) X_train_data = np.random.rand(150, 8) y_train_target = np.random.rand(150) # Generate 30 samples with 8 features for testing X_test_data = np.random.rand(30, 8)
2. 自舉
現在,我們將使用上述自舉法建立多個模型。每次我們隨機對訓練集進行重取樣,將 XGBoost 模型擬合到它,然後對測試集進行預測。當我們試圖獲取從多個自舉資料集收集的預測集合時,此方法將重複多次。
# Number of bootstrapped models n_iterations = 120 # List to store predictions from each model all_preds = [] for iteration in range(n_iterations): # Create a bootstrapped dataset sampled_indices = np.random.choice(len(X_train_data), len(X_train_data), replace=True) X_resampled_data, y_resampled_target = X_train_data[sampled_indices], y_train_target[sampled_indices] # Initialize and train an XGBoost regression model xgboost_model = xgb.XGBRegressor() xgboost_model.fit(X_resampled_data, y_resampled_target) # Make predictions on the test data test_predictions = xgboost_model.predict(X_test_data) all_preds.append(test_predictions) # Convert the list of predictions to a NumPy array all_preds = np.array(all_preds) # Calculate the mean and standard deviation avg_preds = np.mean(all_preds, axis=0) std_dev_preds = np.std(all_preds, axis=0) # Calculate 95% confidence intervals lower_confidence_bound = avg_preds - 1.96 * std_dev_preds upper_confidence_bound = avg_preds + 1.96 * std_dev_preds
視覺化結果
透過取所有預測的平均值(均值)及其標準差,我們可以建立一個預測區間。這將幫助我們瞭解實際資料可能落入的範圍,並提供預測不確定性的度量。我們可以透過繪製平均預測並突出顯示其周圍的置信區間來檢視結果。
# Visualization of the predictions with confidence intervals # Set the figure size plt.figure(figsize=(10, 6)) # Plot the mean predictions plt.plot(avg_preds, label='Average Prediction', color='red') # Fill the area between the lower and upper confidence bounds plt.fill_between(range(len(avg_preds)), lower_confidence_bound, upper_confidence_bound, color='lightblue', alpha=0.5, label='95% Confidence Interval') # Add title and labels to the plot plt.title('Bootstrapping Prediction Interval') plt.xlabel('Test Data Points') plt.ylabel('Predicted Values') # Add a legend to describe the plot lines plt.legend() # Display the plot plt.show()
輸出
這將產生以下結果 -
