要進一步降低您LSTM模型的損失(loss),可以採取多種方法來優化模型的性能。以下將逐步說明幾種常見且有效的方法,並提供相應的代碼示例,以幫助您提升模型的預測準確性。
1. 調整模型架構和超參數
1.1 增加LSTM層數和單元數
增加模型的複雜度,通過增加LSTM層數和每層的單元數,可以使模型學習更複雜的模式。
# 修改LSTM模型架構
model = Sequential([
LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], x_train.shape[2])),
LSTM(50, return_sequences=True),
LSTM(50),
Dense(1)
])
model.compile(optimizer=Adam(learning_rate=0.001), loss='mean_squared_error')
1.2 添加Dropout層以防止過擬合
Dropout層可以隨機丟棄部分神經元,幫助模型泛化能力,減少過擬合。
from tensorflow.keras.layers import Dropout
# 修改LSTM模型架構,加入Dropout層
model = Sequential([
LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], x_train.shape[2])),
Dropout(0.2),
LSTM(50, return_sequences=True),
Dropout(0.2),
LSTM(50),
Dropout(0.2),
Dense(1)
])
model.compile(optimizer=Adam(learning_rate=0.001), loss='mean_squared_error')
1.3 調整學習率
使用不同的學習率進行試驗,可以找到最適合模型收斂的學習率。
# 使用更小的學習率
model.compile(optimizer=Adam(learning_rate=0.0005), loss='mean_squared_error')
2. 使用不同的優化器
嘗試使用其他優化器,如RMSprop或Nadam,有時能帶來更好的結果。
from tensorflow.keras.optimizers import RMSprop, Nadam
# 使用RMSprop優化器
model.compile(optimizer=RMSprop(learning_rate=0.001), loss='mean_squared_error')
# 或者使用Nadam優化器
model.compile(optimizer=Nadam(learning_rate=0.001), loss='mean_squared_error')
3. 調整批量大小和訓練輪數
嘗試不同的批量大小和訓練輪數,可能會改善模型的收斂速度和最終性能。
# 調整批量大小和增加最大輪數
history = model.fit(
x_train, y_train,
validation_data=(x_test, y_test),
epochs=200, # 增加訓練輪數
batch_size=64, # 增加批量大小
callbacks=[early_stop],
verbose=1
)
4. 增加更多特徵(Feature Engineering)
除了基本的開盤價、最高價、最低價和收盤價,還可以添加技術指標如移動平均線(MA)、相對強弱指數(RSI)等,幫助模型更好地理解數據。
4.1 計算移動平均線(MA)
# 計算20天和50天的移動平均線
df['MA20'] = df['Closing Price'].rolling(window=20).mean()
df['MA50'] = df['Closing Price'].rolling(window=50).mean()
# 更新特徵
features = ['Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price', 'MA20', 'MA50']
# 處理NA值
df = df.dropna()
# 重新進行縮放
scaled_data = scaler.fit_transform(df[features])
4.2 計算相對強弱指數(RSI)
# 計算RSI指標
def compute_RSI(data, window=14):
delta = data.diff()
gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()
RS = gain / loss
RSI = 100 - (100 / (1 + RS))
return RSI
df['RSI'] = compute_RSI(df['Closing Price'])
df = df.dropna()
# 更新特徵
features = ['Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price', 'MA20', 'MA50', 'RSI']
scaled_data = scaler.fit_transform(df[features])
5. 使用更長的序列長度
增加序列的長度(例如從40天增加到60天),可以讓模型捕捉更長期的趨勢。
# 增加序列長度
seq_length = 60
x, y = create_sequences(scaled_data, seq_length)
# 重新劃分訓練集和測試集
train_size = int(0.8 * len(x))
x_train, x_test = x[:train_size], x[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
6. 使用序列正則化(Regularization)
除了Dropout,還可以使用L2正則化來約束權重,防止過擬合。
from tensorflow.keras.regularizers import l2
# 使用L2正則化
model = Sequential([
LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], x_train.shape[2]),
kernel_regularizer=l2(0.001)),
Dropout(0.2),
LSTM(50, return_sequences=True, kernel_regularizer=l2(0.001)),
Dropout(0.2),
LSTM(50, kernel_regularizer=l2(0.001)),
Dropout(0.2),
Dense(1)
])
model.compile(optimizer=Adam(learning_rate=0.001), loss='mean_squared_error')
7. 早停監控不同的指標
除了監控val_loss,有時監控val_mape等指標也有助於更好地停止訓練。
# 自定義回調以監控MAPE
from tensorflow.keras.callbacks import Callback
class EarlyStoppingByMAPE(Callback):
def __init__(self, monitor='val_mean_absolute_percentage_error', patience=5):
super(EarlyStoppingByMAPE, self).__init__()
self.monitor = monitor
self.patience = patience
self.best = np.Inf
self.wait = 0
def on_epoch_end(self, epoch, logs=None):
current = logs.get(self.monitor)
if current is None:
return
if current < self.best:
self.best = current
self.wait = 0
else:
self.wait += 1
if self.wait >= self.patience:
self.model.stop_training = True
# 編譯模型時加入MAPE作為指標
model.compile(optimizer=Adam(learning_rate=0.001),
loss='mean_squared_error',
metrics=['mean_absolute_percentage_error'])
# 使用自定義的早停回調
early_stop_mape = EarlyStoppingByMAPE(monitor='val_mean_absolute_percentage_error', patience=10)
history = model.fit(
x_train, y_train,
validation_data=(x_test, y_test),
epochs=200,
batch_size=64,
callbacks=[early_stop, early_stop_mape],
verbose=1
)
8. 模型保存與載入
在訓練過程中保存最佳模型,防止後期過擬合影響最終模型。
from tensorflow.keras.callbacks import ModelCheckpoint
# 定義模型檢查點
checkpoint = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True, verbose=1)
# 訓練模型時加入檢查點
history = model.fit(
x_train, y_train,
validation_data=(x_test, y_test),
epochs=200,
batch_size=64,
callbacks=[early_stop, checkpoint],
verbose=1
)
# 載入最佳模型
from tensorflow.keras.models import load_model
best_model = load_model('best_model.h5')
9. 使用更高級的模型架構
考慮使用更複雜的模型架構,如雙向LSTM(Bidirectional LSTM)或加入注意力機制(Attention Mechanism),以提升模型的性能。
9.1 使用雙向LSTM
from tensorflow.keras.layers import Bidirectional
model = Sequential([
Bidirectional(LSTM(50, return_sequences=True), input_shape=(x_train.shape[1], x_train.shape[2])),
Dropout(0.2),
Bidirectional(LSTM(50, return_sequences=True)),
Dropout(0.2),
Bidirectional(LSTM(50)),
Dropout(0.2),
Dense(1)
])
model.compile(optimizer=Adam(learning_rate=0.001), loss='mean_squared_error')
9.2 加入注意力機制
實現注意力機制較為複雜,以下是一個簡單的實現示例:
from tensorflow.keras.layers import Layer, Input, LSTM, Dense, Concatenate
from tensorflow.keras.models import Model
import tensorflow as tf
class Attention(Layer):
def __init__(self, **kwargs):
super(Attention, self).__init__(**kwargs)
def build(self, input_shape):
self.W = self.add_weight(name='att_weight', shape=(input_shape[-1], 1),
initializer='random_normal', trainable=True)
self.b = self.add_weight(name='att_bias', shape=(input_shape[1], 1),
initializer='zeros', trainable=True)
super(Attention, self).build(input_shape)
def call(self, inputs):
e = tf.keras.backend.tanh(tf.keras.backend.dot(inputs, self.W) + self.b)
a = tf.keras.backend.softmax(e, axis=1)
output = inputs * a
output = tf.keras.backend.sum(output, axis=1)
return output
# 定義模型
inputs = Input(shape=(x_train.shape[1], x_train.shape[2]))
lstm_out = LSTM(50, return_sequences=True)(inputs)
attention = Attention()(lstm_out)
dense_out = Dense(1)(attention)
model = Model(inputs=inputs, outputs=dense_out)
model.compile(optimizer=Adam(learning_rate=0.001), loss='mean_squared_error')
10. 數據增強與擴充
雖然時間序列數據增強不像圖像數據那樣直觀,但可以使用滑動窗口、添加噪聲等方法來擴充數據集。
10.1 添加隨機噪聲
# 添加隨機噪聲到訓練數據
noise_factor = 0.01
x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)
x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)
# 訓練模型使用帶噪聲的數據
history = model.fit(
x_train_noisy, y_train,
validation_data=(x_test_noisy, y_test),
epochs=200,
batch_size=64,
callbacks=[early_stop, checkpoint],
verbose=1
)
綜合應用
結合上述多種方法,下面是一個綜合優化後的完整代碼示例:
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_absolute_percentage_error, mean_squared_error
from tensorflow.keras.models import Sequential, load_model, Model
from tensorflow.keras.layers import LSTM, Dense, Dropout, Bidirectional, Input, Concatenate
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, Callback
from tensorflow.keras.optimizers import Adam, RMSprop, Nadam
import matplotlib.pyplot as plt
# File path and data settings
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\stock price.csv"
features = ['Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price']
target = 'Closing Price'
# Read and preprocess the CSV file
df = pd.read_csv(file_path, parse_dates=['Date'])
df = df.sort_values('Date')
# Feature Engineering: Adding MA and RSI
df['MA20'] = df['Closing Price'].rolling(window=20).mean()
df['MA50'] = df['Closing Price'].rolling(window=50).mean()
# Function to compute RSI
def compute_RSI(data, window=14):
delta = data.diff()
gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()
RS = gain / loss
RSI = 100 - (100 / (1 + RS))
return RSI
df['RSI'] = compute_RSI(df['Closing Price'])
# Drop NA values
df = df.dropna()
# Update features
features = ['Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price', 'MA20', 'MA50', 'RSI']
# Scale data
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(df[features])
# Convert the data into sequences for LSTM input
def create_sequences(data, seq_length):
x, y = [], []
for i in range(len(data) - seq_length):
x.append(data[i:i+seq_length])
y.append(data[i+seq_length, features.index(target)])
return np.array(x), np.array(y)
# Define sequence length
seq_length = 60
x, y = create_sequences(scaled_data, seq_length)
# Split data into training and testing sets
train_size = int(0.8 * len(x))
x_train, x_test = x[:train_size], x[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
# Define custom EarlyStopping by MAPE
class EarlyStoppingByMAPE(Callback):
def __init__(self, monitor='val_mean_absolute_percentage_error', patience=10):
super(EarlyStoppingByMAPE, self).__init__()
self.monitor = monitor
self.patience = patience
self.best = np.Inf
self.wait = 0
def on_epoch_end(self, epoch, logs=None):
current = logs.get(self.monitor)
if current is None:
return
if current < self.best:
self.best = current
self.wait = 0
else:
self.wait += 1
if self.wait >= self.patience:
self.model.stop_training = True
# Build the optimized LSTM model with Bidirectional layers and Dropout
model = Sequential([
Bidirectional(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], x_train.shape[2]))),
Dropout(0.2),
Bidirectional(LSTM(50, return_sequences=True)),
Dropout(0.2),
Bidirectional(LSTM(50)),
Dropout(0.2),
Dense(1)
])
# Compile the model with Nadam optimizer
model.compile(optimizer=Nadam(learning_rate=0.001), loss='mean_squared_error', metrics=['mean_absolute_percentage_error'])
# Define callbacks
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
checkpoint = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True, verbose=1)
early_stop_mape = EarlyStoppingByMAPE(monitor='val_mean_absolute_percentage_error', patience=15)
# Train the model
history = model.fit(
x_train, y_train,
validation_data=(x_test, y_test),
epochs=200,
batch_size=64,
callbacks=[early_stop, checkpoint, early_stop_mape],
verbose=1
)
# Load the best model
best_model = load_model('best_model.h5')
# Predict and inverse scale the predictions
predicted = best_model.predict(x_test)
# To inverse scale, concatenate with other features
scaled_pred = np.copy(scaled_data[-len(predicted):])
scaled_pred[:, features.index(target)] = predicted[:, 0]
predicted_prices = scaler.inverse_transform(scaled_pred)[:, features.index(target)]
# Actual prices
actual_scaled = scaled_data[-len(predicted):]
actual_prices = scaler.inverse_transform(actual_scaled)[:, features.index(target)]
# Calculate Metrics
mape = mean_absolute_percentage_error(actual_prices, predicted_prices) * 100
rmse = np.sqrt(mean_squared_error(actual_prices, predicted_prices))
# Extract the last loss and val_loss
training_loss = history.history['loss'][-1]
validation_loss = history.history['val_loss'][-1]
# Print Metrics
print(f"Training Loss: {training_loss:.6f}")
print(f"Validation Loss: {validation_loss:.6f}")
print(f"MAPE: {mape:.2f}%")
print(f"RMSE: {rmse:.4f}")
# Display results
plt.figure(figsize=(14,5))
plt.plot(actual_prices, color='red', label='Actual Stock Price')
plt.plot(predicted_prices, color='blue', label='Predicted Stock Price')
plt.title('Stock Price Prediction')
plt.xlabel('Time')
plt.ylabel('Stock Price')
plt.legend()
plt.show()
總結
通過以上步驟,您可以從多方面優化您的LSTM模型,包括調整模型結構、添加正則化、進行特徵工程、選用不同的優化器以及應用更高級的模型架構等。每一步的改進都有助於提升模型的預測性能,進而降低損失。您可以根據數據的具體情況,選擇合適的方法進行嘗試和調整。
如有任何問題或需要進一步的幫助,請隨時告知!