XGBoost原理

XGBoost 是一個基于梯度提升樹(Gradient Boosting Decision Tree,GBDT)的模型。它通過集成多棵弱學習器(通常是決策樹)來提高整體預測能力。具體來說,XGBoost在訓練過程中通過每一步的預測誤差來修正前一輪的誤差,并逐步逼近真實的值。

梯度提升的基本思想

梯度提升的基本思想是:通過將多個弱學習器(如淺決策樹)逐步組合起來形成一個強大的預測模型。在每一步的訓練過程中,梯度提升算法會嘗試去最小化當前模型的損失函數(shù),即通過擬合上一輪的殘差來調整模型的參數(shù),從而達到提升模型預測精度的目的。

XGBoost的損失函數(shù)

在XGBoost中,損失函數(shù)由兩部分組成:訓練誤差和正則化項。

損失函數(shù)的形式為:

其中:

樹的結構

數(shù)據(jù)集介紹

我們將使用Kaggle中的stock_prices.csv數(shù)據(jù)集。該數(shù)據(jù)集包含了不同公司的股票價格信息,字段包括:

我們將使用這些數(shù)據(jù)來訓練XGBoost模型,以預測未來幾天的收盤價。

數(shù)據(jù)預處理

在開始建模之前,我們需要對數(shù)據(jù)進行預處理。步驟包括:

  1. 數(shù)據(jù)清洗:處理缺失值和異常值。
  2. 特征工程:創(chuàng)建有助于預測的新特征,比如股票的波動率、成交量變化率等。
  3. 標簽生成:生成預測目標,即未來某天的收盤價。

數(shù)據(jù)清洗

import pandas as pd
import numpy as np

# 讀取數(shù)據(jù)
df = pd.read_csv('stock_prices.csv')

# 將日期轉換為datetime類型,并設置為索引
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)

# 查看缺失值
print(df.isnull().sum())

# 刪除含有缺失值的行
df.dropna(inplace=True)

特征工程

我們可以從原始數(shù)據(jù)中構造更多有意義的特征,比如價格變化、移動平均線、波動率等。

# 創(chuàng)建一些技術指標
df['Price Change'] = df['Close'] - df['Open']
df['SMA_5'] = df['Close'].rolling(window=5).mean() # 5日簡單移動平均線
df['SMA_20'] = df['Close'].rolling(window=20).mean() # 20日簡單移動平均線
df['Volatility'] = (df['High'] - df['Low']) / df['Low'] # 波動率

# 刪除前20天無效數(shù)據(jù)
df = df.dropna()

# 特征和目標
X = df[['Open', 'High', 'Low', 'Volume', 'Price Change', 'SMA_5', 'SMA_20', 'Volatility']]
y = df['Close']

模型訓練

數(shù)據(jù)集劃分

為了避免模型的過擬合,我們將數(shù)據(jù)劃分為訓練集和測試集。

from sklearn.model_selection import train_test_split

# 劃分訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)

XGBoost模型構建與訓練

import xgboost as xgb
from sklearn.metrics import mean_squared_error

# 構建DMatrix
train_dmatrix = xgb.DMatrix(X_train, label=y_train)
test_dmatrix = xgb.DMatrix(X_test, label=y_test)

# 設置參數(shù)
params = {
'objective': 'reg:squarederror', # 預測目標是回歸
'max_depth': 5,
'learning_rate': 0.1,
'n_estimators': 100
}

# 訓練模型
xg_reg = xgb.train(params, train_dmatrix, num_boost_round=100)

# 測試模型
preds = xg_reg.predict(test_dmatrix)

# 計算均方誤差
mse = mean_squared_error(y_test, preds)
print(f"Mean Squared Error: {mse}")

數(shù)據(jù)可視化

為了更好地理解模型的表現(xiàn)和股票數(shù)據(jù)的特征,我們可以使用Matplotlib和Seaborn繪制相關圖形。

股票收盤價變化趨勢

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Close'], label='Close Price')
plt.title('Stock Closing Price Over Time')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()

這張圖顯示了股票的收盤價隨時間的變化,幫助我們直觀了解價格的波動情況。

真實值與預測值對比

plt.figure(figsize=(10, 6))
plt.plot(y_test.index, y_test, label='Actual Price')
plt.plot(y_test.index, preds, label='Predicted Price')
plt.title('Actual vs Predicted Closing Price')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()

這張圖展示了模型的預測結果與真實值之間的差異,幫助評估模型的預測能力。

移動平均線對比

plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Close'], label='Close Price')
plt.plot(df.index, df['SMA_5'], label='5-Day SMA')
plt.plot(df.index, df['SMA_20'], label='20-Day SMA')
plt.title('Stock Price with Moving Averages')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()

移動平均線是常見的技術分析工具,這張圖展示了股票價格與短期(5日)和長期(20日)移動平均線的對比。

波動率分析

plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Volatility'], label='Volatility')
plt.title('Stock Price Volatility Over Time')
plt.xlabel('Date')
plt.ylabel('Volatility')
plt.legend()
plt.show()

這張圖顯示了股票的波動率隨時間的變化,有助于理解價格劇烈變動的時期。

模型優(yōu)化與調參

為了提升模型的預測能力,我們可以通過調參來優(yōu)化XGBoost模型。調參過程主要包括以下幾個步驟:

網(wǎng)格搜索(Grid Search)

我們可以通過網(wǎng)格搜索來尋找最優(yōu)的參數(shù)組合。需要調整的參數(shù)包括:

from sklearn.model_selection import GridSearchCV

# 參數(shù)范圍
param_grid = {
'max_depth': [3, 5, 7],
'learning_rate': [0.01, 0.1, 0.2],
'n_estimators': [100, 200, 300]
}

# 網(wǎng)格搜索
xgb_model = xgb.XGBRegressor(objective='reg:squarederror')
grid_search = GridSearchCV(estimator=xgb_model, param_grid=param_grid, cv=3, scoring='neg_mean_squared_error', verbose=1)
grid_search.fit(X_train, y_train)

# 輸出最佳參數(shù)
print("Best Parameters:", grid_search.best_params_)

正則化

XGBoost中提供了L1和L2正則化,可以有效防止模型過擬合。通過增加正則化項的權重,模型能夠更好地應對噪聲數(shù)據(jù)。

params = {
'objective': 'reg:squarederror',
'max_depth': 5,
'learning_rate': 0.1,
'n_estimators': 100,
'alpha': 0.1, # L1正則化項權重
'lambda': 0.1 # L2正則化項權重
}

全文通過XGBoost模型對股票市場的趨勢進行了預測,詳細介紹了從數(shù)據(jù)預處理、特征工程、模型訓練到調參優(yōu)化的整個過程。

最后通過繪制股票價格變化趨勢、真實值與預測值對比、移動平均線和波動率分析的圖形,我們能夠直觀地理解股票市場的變化規(guī)律。調參和正則化進一步提升了模型的性能。

文章轉自微信公眾號@深夜努力寫Python

上一篇:

突破最強回歸算法模型,SVR !!

下一篇:

GBDT、XGBoost、LightGBM,樹模型全面對比 ??!
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數(shù)據(jù)驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費