Certainly! To improve your LSTM model's performance when adding more data, you can perform hyperparameter optimization using Random Search. Below is a step-by-step guide using Keras Tuner, which is a powerful library for hyperparameter tuning with TensorFlow/Keras models.
1. Install Required Libraries
First, ensure you have the necessary libraries installed. You can install them using pip:
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import keras_tuner as kt
3. Load and Preprocess Data
python
# Load the dataset
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\enhanced_stock_price_ma.csv"
data = pd.read_csv(file_path)
# Select features and target
features = ['Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price', 'MA_5', 'MA_20']
target = 'Closing Price'
X = data[features].values
y = data[target].values
# Normalize the features
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)
# Reshape for LSTM [samples, timesteps, features]
# Assuming you want to use previous 60 timesteps to predict the next value
timesteps = 60
def create_sequences(X, y, timesteps):
Xs, ys = [], []
for i in range(timesteps, len(X)):
Xs.append(X[i-timesteps:i])
ys.append(y[i])
return np.array(Xs), np.array(ys)
X_seq, y_seq = create_sequences(X_scaled, y, timesteps)
# Split into training and testing
X_train, X_test, y_train, y_test = train_test_split(X_seq, y_seq, test_size=0.2, random_state=42)
4. Define the Model-Building Function for Keras Tuner
python
def build_model(hp):
model = keras.Sequential()
# Tune the number of LSTM units
hp_units = hp.Int('units',
min_value=50,
max_value=200,
step=50)
model.add(layers.LSTM(units=hp_units, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(layers.Dropout(rate=hp.Float('dropout_1', min_value=0.0, max_value=0.5, step=0.1)))
model.add(layers.LSTM(units=hp_units))
model.add(layers.Dropout(rate=hp.Float('dropout_2', min_value=0.0, max_value=0.5, step=0.1)))
# Tune the learning rate for the optimizer
hp_learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])
model.add(layers.Dense(1))
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=hp_learning_rate),
loss='mean_squared_error',
metrics=['mae']
)
return model
5. Initialize the Random Search Tuner
python
tuner = kt.RandomSearch(
build_model,
objective='val_mae',
max_trials=20, # Number of different models to try
executions_per_trial=2, # How many models to build for each trial
directory='lstm_random_search',
project_name='stock_price_prediction'
)
6. Run the Hyperparameter Search
python
# Early stopping to prevent overfitting
early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)
tuner.search(
X_train,
y_train,
epochs=50,
batch_size=32,
validation_split=0.2,
callbacks=[early_stop]
)
7. Retrieve the Best Model and Evaluate
python
# Get the optimal hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print(f"""
The best number of units in the LSTM layers is {best_hps.get('units')} and the best learning rate for the optimizer is {best_hps.get('learning_rate')}.
""")
# Build the best model and train it
model = tuner.hypermodel.build(best_hps)
history = model.fit(
X_train,
y_train,
epochs=50,
batch_size=32,
validation_split=0.2,
callbacks=[early_stop]
)
# Evaluate on the test set
loss, mae = model.evaluate(X_test, y_test)
print(f"Test MAE: {mae}")
Feature Engineering: Ensure that your features are relevant and consider adding more technical indicators if applicable.
Sequence Length (timesteps): You can also make timesteps a hyperparameter to tune.
More Hyperparameters: Feel free to include more hyperparameters in the build_model function, such as the number of LSTM layers, different activation functions, etc.
Increase max_trials: Depending on computational resources, increasing the number of trials can potentially find better hyperparameters.
Regularization: Consider adding techniques like Batch Normalization or different Dropout rates to prevent overfitting.
10. Full Example Code
Here's the complete code integrating all the steps above:
python
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import keras_tuner as kt
# 1. Load the dataset
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\enhanced_stock_price_ma.csv"
data = pd.read_csv(file_path)
# 2. Select features and target
features = ['Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price', 'MA_5', 'MA_20']
target = 'Closing Price'
X = data[features].values
y = data[target].values
# 3. Normalize the features
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)
# 4. Create sequences for LSTM
timesteps = 60
def create_sequences(X, y, timesteps):
Xs, ys = [], []
for i in range(timesteps, len(X)):
Xs.append(X[i-timesteps:i])
ys.append(y[i])
return np.array(Xs), np.array(ys)
X_seq, y_seq = create_sequences(X_scaled, y, timesteps)
# 5. Split into training and testing
X_train, X_test, y_train, y_test = train_test_split(X_seq, y_seq, test_size=0.2, random_state=42)
# 6. Define the model-building function
def build_model(hp):
model = keras.Sequential()
hp_units = hp.Int('units', min_value=50, max_value=200, step=50)
model.add(layers.LSTM(units=hp_units, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(layers.Dropout(rate=hp.Float('dropout_1', min_value=0.0, max_value=0.5, step=0.1)))
model.add(layers.LSTM(units=hp_units))
model.add(layers.Dropout(rate=hp.Float('dropout_2', min_value=0.0, max_value=0.5, step=0.1)))
hp_learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])
model.add(layers.Dense(1))
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=hp_learning_rate),
loss='mean_squared_error',
metrics=['mae']
)
return model
# 7. Initialize the Random Search tuner
tuner = kt.RandomSearch(
build_model,
objective='val_mae',
max_trials=20,
executions_per_trial=2,
directory='lstm_random_search',
project_name='stock_price_prediction'
)
# 8. Run the search
early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)
tuner.search(
X_train,
y_train,
epochs=50,
batch_size=32,
validation_split=0.2,
callbacks=[early_stop]
)
# 9. Retrieve the best hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print(f"""
The best number of units in the LSTM layers is {best_hps.get('units')} and the best learning rate for the optimizer is {best_hps.get('learning_rate')}.
""")
# 10. Build and train the best model
model = tuner.hypermodel.build(best_hps)
history = model.fit(
X_train,
y_train,
epochs=50,
batch_size=32,
validation_split=0.2,
callbacks=[early_stop]
)
# 11. Evaluate the model
loss, mae = model.evaluate(X_test, y_test)
print(f"Test MAE: {mae}")
# 12. Make predictions
predictions = model.predict(X_test)
11. Understanding the Hyperparameters Tuned
units: Number of neurons in each LSTM layer. More units can capture more complex patterns but may lead to overfitting.
dropout_1 and dropout_2: Dropout rates after each LSTM layer to prevent overfitting.
learning_rate: Learning rate for the Adam optimizer, affecting how quickly the model learns.
12. Next Steps
Experiment with More Hyperparameters: Such as the number of LSTM layers, different activation functions, or different optimizers.
Cross-Validation: Implement cross-validation for a more robust evaluation.
Feature Selection: Analyze feature importance and consider reducing or engineering features for better performance.
Model Evaluation: Use additional metrics (e.g., RMSE, R²) to assess model performance comprehensively.
Visualize Results: Plot training/validation loss and predictions vs actual values to gain insights.
By implementing Random Search with Keras Tuner, you can efficiently explore various hyperparameter combinations to enhance your LSTM model's accuracy, especially when scaling up your dataset.