
XGBoost - Python 實現
本章將使用 XGBoost Python 模組在泰坦尼克號資料上訓練一個 XGBoost 模型。我們構建此模型的主要目標是透過考慮年齡、性別和等級等變數來預測乘客是否倖存。此外,我們還將修改模型的超引數。
先決條件
在您可以使用 Python 構建 XGBoost 模型之前,必須滿足以下條件:
Python 環境: 需要 Python 3.6 或更高版本。您可以使用 PyCharm、Visual Studio Code 或 Jupyter Notebook 等庫來編寫和執行 Python 程式碼。
庫: 需要安裝用於資料處理、視覺化和機器學習的 Python 庫。我們將在模型中使用的庫包括 scikit-learn、xgboost、matplotlib、pandas、numpy 和 seaborn。
資料集: 一個有效的資料集,其中包含用於二元或多類分類的特徵和因變數。資料集需要採用 pandas 可以快速載入的格式,例如 CSV。
擁有必要的工具、庫、資料集和基本知識將有助於您使用 Python 構建 XGBoost 模型。
XGBoost 實現
以下是您需要遵循的步驟:
步驟 1:安裝所需的庫
此實現需要一些庫,如果您尚未安裝,請使用以下命令安裝:
# Install necessary libraries pip install matplotlib pip install numpy pip install pandas pip install scikit-learn pip install seaborn pip install xgboost
步驟 2:匯入所需的庫
現在您需要匯入庫:
# Here are the imports import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import xgboost as xgb from sklearn.metrics import accuracy_score, confusion_matrix, ConfusionMatrixDisplay from sklearn.model_selection import GridSearchCV, train_test_split
步驟 3:載入泰坦尼克號資料集
本課程將使用泰坦尼克號資料集,該資料集可以從 Kaggle 和其他網站下載。因此,下載 titanic.csv 獲取泰坦尼克號資料集。您需要將 CSV 檔案上傳到您的 Jupyter Notebook。此時,將資料讀取到 pandas DataFrame 中:
# Load the dataset titanic_df = pd.read_csv('/Python/Datasets/titanic.csv') # Display the first few rows of the dataset print(titanic_df.head())
輸出
這將產生以下結果:
PassengerId Survived Pclass \ 0 1 0 3 1 2 1 1 2 3 1 3 3 4 1 1 4 5 0 3 Name Gender Age SibSp \ 0 Braund, Mr. Owen Harris male 22.0 1 1 Cumings, Mrs. John Bradley Florence Briggs Th... female 38.0 1 2 Heikkinen, Miss. Laina female 26.0 0 3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 4 Allen, Mr. William Henry male 35.0 0 Parch Ticket Fare Cabin Embarked 0 0 A/5 21171 7.2500 NaN S 1 0 PC 17599 71.2833 C85 C 2 0 STON/O2. 3101282 7.9250 NaN S 3 0 113803 53.1000 C123 S 4 0 373450 8.0500 NaN S
步驟 4:資料預處理
在訓練模型之前,需要對資料進行預處理。此步驟包括處理缺失資料、編碼分類變數和選擇特徵。查詢任何缺失的值:
# Check for missing values print(titanic_df.isnull().sum())
輸出
這將生成以下結果:
PassengerId 0 Survived 0 Pclass 0 Name 0 Gender 0 Age 177 SibSp 0 Parch 0 Ticket 0 Fare 0 Cabin 687 Embarked 2 dtype: int64
填寫空白或刪除它們:
# Drop rows with missing values titanic_df = titanic_df.dropna()
現在我們將選擇必要的特徵並編碼分類變數
# Select features and target variable X = titanic_df[['Pclass', 'Gender', 'Age', 'SibSp', 'Parch', 'Fare']] y = titanic_df['Survived'] # Encode categorical variable 'Gender' X.loc[:, 'Gender'] = X['Gender'].map({'male': 0, 'female': 1})
步驟 5:訓練和評估模型
將資料分成訓練集和測試集後,我們將訓練模型並評估其有效性。這裡將資料分成如下:
# Split data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
接下來,我們需要將資料轉換為 XGBoost 模型的 DMatrix 格式:
# Convert 'Gender' column to numeric in both training and test sets X_train['Gender'] = X_train['Gender'].map({'male': 0, 'female': 1}) X_test['Gender'] = X_test['Gender'].map({'male': 0, 'female': 1}) # Ensure there are no missing values and data types are numeric X_train = X_train.astype(float) X_test = X_test.astype(float) # Now convert to DMatrix format dmatrix_train = xgb.DMatrix(data=X_train, label=y_train) dmatrix_test = xgb.DMatrix(data=X_test, label=y_test)
然後我們將訓練模型:
# Set learning objective learning_objective = {'objective': 'binary:logistic'} # Train the model model = xgb.train(params=learning_objective, dtrain=dmatrix_train)
之後,我們需要評估模型:
# Make predictions test_predictions = model.predict(dmatrix_test) round_test_predictions = [round(p) for p in test_predictions] # Calculate accuracy accuracy = accuracy_score(y_test, round_test_predictions) print(f'Accuracy: {accuracy:.2f}')
輸出
這將建立以下結果:
Accuracy: 0.80
步驟 6:超引數調優
我們現在將使用 GridSearchCV 實現超引數調優,以找到 XGBoost 模型的理想引數。因此,設定引數網格:
# Define the parameter grid params_grid = { 'learning_rate': [0.01, 0.05], 'gamma': [0, 0.01], 'max_depth': [6, 7], 'min_child_weight': [1, 2, 3], 'subsample': [0.6, 0.7], 'n_estimators': [400, 600, 800], 'colsample_bytree': [0.7, 0.8], }
定義並設定 XGBoost 分類器和 GridSearchCV:
# Define the XGBoost classifier classifier = xgb.XGBClassifier() # Set up GridSearchCV grid_classifier = GridSearchCV(classifier, params_grid, scoring='accuracy', cv=5) grid_classifier.fit(X_train, y_train)
確定最合適的引數後,我們將評估模型
# Get best parameters best_parameters = grid_classifier.best_params_ print("Best parameters:", best_parameters) # Make predictions with the best model grid_test_preds = grid_classifier.predict(X_test) # Calculate accuracy grid_test_accuracy = accuracy_score(y_test, grid_test_preds) print(f'GridSearchCV Accuracy: {grid_test_accuracy:.2f}')
輸出
這將導致以下結果:
Best parameters: {'colsample_bytree': 0.7, 'gamma': 0, 'learning_rate': 0.01, 'max_depth': 7, 'min_child_weight': 1, 'n_estimators': 600, 'subsample': 0.7} GridSearchCV Accuracy: 0.78
在這裡,我們將繪製混淆矩陣。
# Plot confusion matrix cm = confusion_matrix(y_test, grid_test_preds) disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=grid_classifier.classes_) disp.plot() plt.show()
輸出
這將導致以下結果:

總結
本章使用泰坦尼克號資料集解釋瞭如何在 Python 中實現 XGBoost 模型。為了提高模型的效能,您可以研究其他資料集。