當然,我可以幫助你優化並重寫這段股票價格預測的LSTM模型程式碼。以下是優化後的版本,包含改進的結構、模組化的函數以及更清晰的註解,讓程式碼更易讀、更易維護。
優化重點
- 模組化:將不同的步驟封裝成函數,提高代碼的可重用性和可讀性。
- 參數化:使用參數來控制模型的超參數,使得調整變得更方便。
- 錯誤處理:添加基本的錯誤處理來提高代碼的健壯性。
- 清晰的註解:添加詳細的註解,方便理解每一步的目的。
- 路徑處理:使用
os 模組來處理文件路徑,增強跨平台兼容性。
以下是優化重寫後的完整程式碼:
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from keras.callbacks import EarlyStopping, ReduceLROnPlateau
# 設定繪圖風格
plt.style.use('seaborn-darkgrid')
def load_data(file_path, date_column='Date'):
"""
加載並預處理數據。
Parameters:
- file_path: str, CSV文件的路徑
- date_column: str, 日期列名稱
Returns:
- df: pandas DataFrame, 已排序並設定日期為索引
"""
try:
df = pd.read_csv(file_path, parse_dates=[date_column])
df.sort_values(date_column, inplace=True)
df.set_index(date_column, inplace=True)
print("數據加載成功。")
return df
except FileNotFoundError:
print(f"文件未找到: {file_path}")
raise
except Exception as e:
print(f"加載數據時發生錯誤: {e}")
raise
def preprocess_data(df, features, target, method='drop'):
"""
處理缺失值和特徵縮放。
Parameters:
- df: pandas DataFrame, 原始數據
- features: list of str, 特徵列名稱
- target: str, 目標列名稱
- method: str, 缺失值處理方法 'drop' 或 'ffill'
Returns:
- X_scaled: np.ndarray, 縮放後的特徵
- y_scaled: np.ndarray, 縮放後的目標
- scaler_X: MinMaxScaler, 特徵縮放器
- scaler_y: MinMaxScaler, 目標縮放器
"""
print("處理缺失值之前:")
print(df.isnull().sum())
if method == 'drop':
df_clean = df.dropna()
elif method == 'ffill':
df_clean = df.fillna(method='ffill')
else:
raise ValueError("method參數必須是 'drop' 或 'ffill'")
print("處理缺失值之後:")
print(df_clean.isnull().sum())
X = df_clean[features]
y = df_clean[target]
scaler_X = MinMaxScaler(feature_range=(0, 1))
X_scaled = scaler_X.fit_transform(X)
scaler_y = MinMaxScaler(feature_range=(0, 1))
y_scaled = scaler_y.fit_transform(y.values.reshape(-1, 1))
return X_scaled, y_scaled, scaler_X, scaler_y
def train_test_split_time_series(X, y, train_ratio=0.8):
"""
按時間順序劃分訓練集和測試集。
Parameters:
- X: np.ndarray, 特徵數據
- y: np.ndarray, 目標數據
- train_ratio: float, 訓練集比例
Returns:
- X_train, X_test, y_train, y_test: np.ndarray, 劃分後的數據
"""
train_size = int(len(X) * train_ratio)
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
print(f"訓練樣本數量: {X_train.shape[0]}")
print(f"測試樣本數量: {X_test.shape[0]}")
return X_train, X_test, y_train, y_test
def create_sequences(X, y, time_steps=10):
"""
創建LSTM所需的序列數據。
Parameters:
- X: np.ndarray, 特徵數據
- y: np.ndarray, 目標數據
- time_steps: int, 時間步長
Returns:
- Xs, ys: np.ndarray, 序列特徵和目標
"""
Xs, ys = [], []
for i in range(len(X) - time_steps):
Xs.append(X[i:(i + time_steps)])
ys.append(y[i + time_steps])
return np.array(Xs), np.array(ys)
def build_lstm_model(input_shape, units=50, dropout_rate=0.2):
"""
構建LSTM神經網絡模型。
Parameters:
- input_shape: tuple, 輸入數據形狀 (time_steps, num_features)
- units: int, LSTM單元數
- dropout_rate: float, Dropout比率
Returns:
- model: keras Sequential模型
"""
model = Sequential()
model.add(LSTM(
units=units,
return_sequences=True,
input_shape=input_shape,
dropout=dropout_rate,
recurrent_dropout=dropout_rate
))
model.add(Dropout(dropout_rate))
model.add(LSTM(
units=units,
return_sequences=False,
dropout=dropout_rate,
recurrent_dropout=dropout_rate
))
model.add(Dropout(dropout_rate))
model.add(Dense(units=25))
model.add(Dropout(dropout_rate))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
model.summary()
return model
def plot_loss(history):
"""
繪製訓練和驗證的損失曲線。
Parameters:
- history: keras History對象
"""
plt.figure(figsize=(12, 6))
plt.plot(history.history['loss'], label='訓練損失')
plt.plot(history.history['val_loss'], label='驗證損失')
plt.title('損失函數隨訓練輪數的變化')
plt.xlabel('訓練輪數')
plt.ylabel('均方誤差')
plt.legend()
plt.show()
def plot_predictions(dates, actual, predicted, title='實際 vs 預測收盤價', xlabel='日期', ylabel='收盤價'):
"""
繪製實際值與預測值的比較圖。
Parameters:
- dates: pandas DatetimeIndex, 日期
- actual: np.ndarray, 實際值
- predicted: np.ndarray, 預測值
- title: str, 圖表標題
- xlabel: str, x軸標籤
- ylabel: str, y軸標籤
"""
plt.figure(figsize=(14,7))
plt.plot(dates, actual, label='實際收盤價', color='blue')
plt.plot(dates, predicted, label='預測收盤價', color='red')
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend()
plt.show()
def calculate_performance_metrics(actual, predicted):
"""
計算並打印性能指標。
Parameters:
- actual: np.ndarray, 實際值
- predicted: np.ndarray, 預測值
"""
mse = mean_squared_error(actual, predicted)
mae = mean_absolute_error(actual, predicted)
mape = np.mean(np.abs((actual - predicted) / actual)) * 100
r2 = r2_score(actual, predicted)
print(f"均方誤差 (MSE): {mse:.4f}")
print(f"平均絕對誤差 (MAE): {mae:.4f}")
print(f"平均絕對百分比誤差 (MAPE): {mape:.2f}%")
print(f"決定係數 (R²): {r2:.4f}")
def forecast_future(model, last_sequence, scaler_y, n_steps=20):
"""
進行遞歸未來步數的預測。
Parameters:
- model: 訓練好的LSTM模型
- last_sequence: np.ndarray, 最後的輸入序列 (time_steps, num_features)
- scaler_y: MinMaxScaler, 目標值的縮放器
- n_steps: int, 預測的步數
Returns:
- predictions: np.ndarray, 未來預測值 (原始尺度)
"""
predictions = []
X_current = last_sequence.copy()
for _ in range(n_steps):
pred_scaled = model.predict(X_current.reshape(1, X_current.shape[0], X_current.shape[1]))
predictions.append(pred_scaled[0, 0])
# 更新序列: 移除第一個時間步,添加新的預測值
new_feature = X_current[-1].copy()
new_feature[-1] = pred_scaled # 更新'Closing Price'為預測值
X_current = np.append(X_current[1:], [new_feature], axis=0)
# 反縮放
predictions = scaler_y.inverse_transform(np.array(predictions).reshape(-1, 1)).flatten()
return predictions
def main():
# 1. 配置參數
file_path = os.path.join("C:\\", "Users", "jack8", "OneDrive", "stock cow ai", "data", "stock price.csv")
features = ['Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price']
target = 'Closing Price'
time_steps = 10
train_ratio = 0.8
epochs = 300
batch_size = 32
dropout_rate = 0.2
n_future_steps = 20
# 2. 加載數據
df = load_data(file_path, date_column='Date')
# 3. 預處理數據
X_scaled, y_scaled, scaler_X, scaler_y = preprocess_data(df, features, target, method='drop')
# 4. 時間序列劃分
X_train_raw, X_test_raw, y_train_raw, y_test_raw = train_test_split_time_series(X_scaled, y_scaled, train_ratio)
# 5. 創建序列
X_train, y_train = create_sequences(X_train_raw, y_train_raw, time_steps)
X_test, y_test = create_sequences(X_test_raw, y_test_raw, time_steps)
print(f"X_train shape: {X_train.shape}")
print(f"y_train shape: {y_train.shape}")
print(f"X_test shape: {X_test.shape}")
print(f"y_test shape: {y_test.shape}")
# 6. 提取對應的日期
dates = df.index[time_steps:]
train_dates = dates[:int(len(dates) * train_ratio) - time_steps]
test_dates = dates[int(len(dates) * train_ratio):]
# 7. 構建模型
model = build_lstm_model(input_shape=(X_train.shape[1], X_train.shape[2]),
units=50,
dropout_rate=dropout_rate)
# 8. 訓練模型
early_stop = EarlyStopping(monitor='val_loss', patience=20, restore_best_weights=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=10, min_lr=1e-6)
history = model.fit(
X_train, y_train,
epochs=epochs,
batch_size=batch_size,
validation_data=(X_test, y_test),
callbacks=[early_stop, reduce_lr],
verbose=1
)
# 9. 繪製損失曲線
plot_loss(history)
# 10. 預測
y_pred_scaled = model.predict(X_test)
y_pred = scaler_y.inverse_transform(y_pred_scaled)
y_test_actual = scaler_y.inverse_transform(y_test)
# 11. 繪製實際值與預測值
plot_predictions(test_dates, y_test_actual.flatten(), y_pred.flatten())
# 12. 計算性能指標
calculate_performance_metrics(y_test_actual, y_pred)
# 13. 未來預測
last_sequence = X_test[-1]
future_predictions = forecast_future(model, last_sequence, scaler_y, n_steps=n_future_steps)
# 14. 生成未來日期
last_date = test_dates[-1]
future_dates = pd.bdate_range(start=last_date + pd.Timedelta(days=1), periods=n_future_steps)
# 15. 繪製未來預測
plot_predictions(future_dates, future_predictions,
title='未來收盤價預測',
xlabel='日期',
ylabel='收盤價')
if __name__ == "__main__":
main()
優化說明
-
模組化函數:
load_data:負責加載和初步處理數據,包括排序和設置索引。
preprocess_data:處理缺失值、選擇特徵和目標,並進行縮放。
train_test_split_time_series:根據時間順序劃分訓練集和測試集。
create_sequences:創建LSTM所需的時間序列數據。
build_lstm_model:構建並編譯LSTM模型。
plot_loss 和 plot_predictions:負責繪製訓練過程中的損失和預測結果的可視化。
calculate_performance_metrics:計算並打印模型的性能指標。
forecast_future:進行未來步數的預測。
-
參數化設計:
- 將模型的超參數(如
units、dropout_rate)、訓練參數(如epochs、batch_size)以及其他可調參數設置為函數參數,便於調整和實驗。
-
錯誤處理:
- 在數據加載函數中加入了對文件未找到和其他異常的處理,避免程式在遇到問題時無法提供有用的錯誤信息。
-
路徑處理:
- 使用
os.path.join 來構建文件路徑,增強了跨平台的兼容性(如在不同操作系統下的路徑分隔符問題)。
-
繪圖美化:
- 設定了繪圖風格為
seaborn-darkgrid,使圖表更具可讀性。
- 調整了圖表的標題、標籤和圖例,使其更具描述性。
-
模型訓練改進:
- 先前你有進行雙重的
model.fit,優化後僅保留一個訓練過程,並加入了 EarlyStopping 和 ReduceLROnPlateau 回調來防止過擬合並自動調整學習率。
-
性能指標:
- 除了 MSE 和 MAE,增添了 MAPE 和 R²,更全面地評估模型的預測效果。
-
未來預測:
- 優化了未來預測函數,使其更清晰且易於理解,並且在生成未來日期時,使用
pd.bdate_range 保證只考慮工作日。
額外建議
- 超參數調整:可以考慮使用超參數調整工具(如 Grid Search 或 Random Search)來尋找最佳的模型參數。
- 模型保存與加載:訓練完成後,可以將模型保存到文件,方便後續加載和使用。
- 更多特徵工程:根據需要,可以引入更多技術性指標(如移動平均線、相對強弱指數 RSI 等)來提升模型性能。
- 異常值處理:在處理缺失值之外,還可以考慮處理數據中的異常值,提升模型的穩健性。
希望這樣的優化重寫能夠滿足你的需求,並提升你的模型效果和程式碼質量。如果有進一步的問題或需求,隨時告訴我!