Sure! Below is a comprehensive Python script that accomplishes the following:
-
Data Loading and Preprocessing:
- Reads the CSV file.
- Scales the features using
MinMaxScaler.
- Creates sequences suitable for LSTM input.
-
Model Building:
- Defines a function to create LSTM models with hyperparameters that can be tuned.
-
Grid Search with Cross-Validation:
- Utilizes
GridSearchCV from scikit-learn to perform hyperparameter tuning.
- Incorporates
EarlyStopping to prevent overfitting.
- Uses
Mean Absolute Percentage Error (MAPE) as the evaluation metric.
-
Training and Evaluation:
- Trains the model with the best hyperparameters.
- Evaluates performance on the test set.
Make sure you have the necessary libraries installed. You can install any missing libraries using pip. For example:
pip install pandas numpy scikit-learn tensorflow keras
Now, here's the complete script:
import pandas as pd
import numpy as np
import os
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.metrics import make_scorer, mean_absolute_percentage_error
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from tensorflow.keras.callbacks import EarlyStopping
import tensorflow as tf
# 1. Load and preprocess the data
def load_data(file_path, features, target, sequence_length=60, test_size=0.2):
# Load data
df = pd.read_csv(file_path)
# Ensure the data is sorted by date or appropriate time index
# If there's a date column, uncomment and modify the following lines:
# df['Date'] = pd.to_datetime(df['Date'])
# df = df.sort_values('Date')
# Select relevant features
data = df[features + [target]].values
# Scale the data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# Create sequences
X, y = [], []
for i in range(sequence_length, len(scaled_data)):
X.append(scaled_data[i-sequence_length:i, :-1]) # all features except target
y.append(scaled_data[i, -1]) # target
X, y = np.array(X), np.array(y)
# Split into train and test sets
split = int(X.shape[0] * (1 - test_size))
X_train, X_test = X[:split], X[split:]
y_train, y_test = y[:split], y[split:]
return X_train, X_test, y_train, y_test, scaler
# 2. Define the LSTM model creation function for KerasRegressor
def create_model(units=50, dropout_rate=0.2, optimizer='adam'):
model = Sequential()
model.add(LSTM(units=units, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(dropout_rate))
model.add(LSTM(units=units))
model.add(Dropout(dropout_rate))
model.add(Dense(1))
model.compile(optimizer=optimizer, loss='mse', metrics=[tf.keras.metrics.MeanAbsolutePercentageError()])
return model
# 3. Load data
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\enhanced_stock_price_ma.csv"
features = ['Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price','MA_5','MA_20']
target = 'Closing Price'
# Load and preprocess data
X_train, X_test, y_train, y_test, scaler = load_data(file_path, features, target, sequence_length=60, test_size=0.2)
# 4. Wrap the model using KerasRegressor
model = KerasRegressor(build_fn=create_model, verbose=0)
# 5. Define the grid search parameters
param_grid = {
'units': [50, 100],
'dropout_rate': [0.2, 0.3],
'optimizer': ['adam', 'rmsprop'],
'batch_size': [32, 64],
'epochs': [50] # Using 50 epochs, but we'll use EarlyStopping
}
# 6. Define EarlyStopping callback
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
# 7. Define the custom scorer
mape_scorer = make_scorer(mean_absolute_percentage_error, greater_is_better=False)
# 8. Set up Time Series Cross-Validation
tscv = TimeSeriesSplit(n_splits=3)
# 9. Perform Grid Search
grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=tscv, scoring=mape_scorer, verbose=2, n_jobs=1)
# 10. Fit Grid Search
# Note: KerasRegressor does not support 'callbacks' directly in GridSearchCV, so we need to modify the create_model function to include callbacks or handle it differently.
# A workaround is to use a custom training loop or adjust the estimator. However, for simplicity, we'll include EarlyStopping in the model's fit method by modifying the KerasRegressor.
# To include callbacks, we need to create a custom KerasRegressor
from sklearn.base import BaseEstimator, RegressorMixin
class KerasRegressorWithCallbacks(BaseEstimator, RegressorMixin):
def __init__(self, build_fn, units=50, dropout_rate=0.2, optimizer='adam', batch_size=32, epochs=50, callbacks=None, verbose=0):
self.build_fn = build_fn
self.units = units
self.dropout_rate = dropout_rate
self.optimizer = optimizer
self.batch_size = batch_size
self.epochs = epochs
self.callbacks = callbacks
self.verbose = verbose
self.model_ = None
def fit(self, X, y):
self.model_ = self.build_fn(units=self.units, dropout_rate=self.dropout_rate, optimizer=self.optimizer)
self.model_.fit(X, y,
batch_size=self.batch_size,
epochs=self.epochs,
callbacks=self.callbacks,
validation_split=0.1,
verbose=self.verbose)
return self
def predict(self, X):
return self.model_.predict(X).flatten()
def score(self, X, y):
y_pred = self.predict(X)
return -mean_absolute_percentage_error(y, y_pred) # negative because GridSearchCV maximizes the score
# Create a new KerasRegressor with callbacks
model = KerasRegressorWithCallbacks(build_fn=create_model, callbacks=[early_stop], verbose=0)
# Update param_grid to exclude epochs if using EarlyStopping (optional)
# You can keep epochs if you want to limit the maximum number of epochs
# Here we'll keep it as is
# Perform Grid Search
grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=tscv, scoring=mape_scorer, verbose=2, n_jobs=1)
# Fit Grid Search
grid_result = grid.fit(X_train, y_train)
# 11. Summarize Results
print(f"Best MAPE: {-grid_result.best_score_} using {grid_result.best_params_}")
# 12. Evaluate on Test Set
best_model = grid_result.best_estimator_.model_
y_pred = best_model.predict(X_test).flatten()
# Inverse transform the predictions and actual values
# Since we scaled all features together, to invert the scaling we need to concatenate predictions with other features
# Here, we'll assume that the target was the last feature in the scaler
# Create an array with predictions and zeros for other features
inv_y_pred = np.zeros((len(y_pred), len(features) +1))
inv_y_pred[:, -1] = y_pred
inv_y = np.zeros((len(y_test), len(features) +1))
inv_y[:, -1] = y_test
# Inverse transform
inv_y_pred = scaler.inverse_transform(inv_y_pred)[:, -1]
inv_y = scaler.inverse_transform(inv_y)[:, -1]
# Calculate MAPE
test_mape = mean_absolute_percentage_error(inv_y, inv_y_pred)
print(f"Test MAPE: {test_mape}")
# 13. Optional: Plot Actual vs Predicted
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
plt.plot(inv_y, label='Actual Closing Price')
plt.plot(inv_y_pred, label='Predicted Closing Price')
plt.title('Actual vs Predicted Closing Price')
plt.xlabel('Time')
plt.ylabel('Closing Price')
plt.legend()
plt.show()
Explanation of the Script
-
Data Loading and Preprocessing:
- Scaling: It's essential to scale the data before training an LSTM to help the model converge faster. Here,
MinMaxScaler scales the features to a range between 0 and 1.
- Creating Sequences: LSTMs require input data in sequences. The
sequence_length parameter defines how many past time steps the model looks at to make a prediction.
- Train-Test Split: The data is split into training and testing sets based on the
test_size parameter.
-
Model Creation:
- The
create_model function builds an LSTM model with customizable hyperparameters:
units: Number of neurons in the LSTM layers.
dropout_rate: Fraction of the units to drop for the linear transformation of the inputs.
optimizer: Optimizer algorithm to use.
- The model consists of two LSTM layers with dropout and a Dense output layer.
-
Grid Search with Cross-Validation:
- Hyperparameters Tuned:
- Number of LSTM units.
- Dropout rate.
- Optimizer type.
- Batch size.
- Epochs.
- Early Stopping: Updates training with early stopping to prevent overfitting by monitoring the validation loss.
- Custom KerasRegressor: A custom wrapper
KerasRegressorWithCallbacks is created to include callbacks like EarlyStopping within GridSearchCV.
-
Model Training and Evaluation:
- Grid Search: Searches for the best combination of hyperparameters based on MAPE.
- Best Model Selection: After grid search, the best model is selected and evaluated on the test set.
- Inverse Scaling: Predictions and actual values are inverse transformed to their original scale for meaningful MAPE computation and plotting.
- Visualization: Optional plotting of actual vs. predicted closing prices to visualize performance.
Notes
-
Computation Time: Grid search, especially with deep learning models, can be computationally expensive and time-consuming. Adjust the param_grid and other parameters according to your computational resources.
-
Callbacks in GridSearchCV: The standard KerasRegressor doesn't support passing callbacks directly when used with GridSearchCV. Hence, a custom wrapper KerasRegressorWithCallbacks is created to include callbacks like EarlyStopping.
-
TimeSeriesSplit: Used for cross-validation tailored for time series data to prevent leakage of future information into the training data.
-
Adjustments: Depending on your specific dataset and requirements, you might need to adjust the sequence_length, hyperparameter ranges, and model architecture for optimal performance.
Feel free to modify the script according to your specific needs and dataset characteristics!