Certainly! When increasing the dataset size, it’s common for the performance of machine learning models, including LSTM networks, to be affected. This can be due to various factors such as the need to adjust hyperparameters to better fit the larger dataset or potential overfitting.
Implementing Random Search for hyperparameter tuning can help identify the optimal set of hyperparameters that improve your model’s performance on the expanded dataset. Below, I’ll guide you through integrating Keras Tuner—a powerful library for hyperparameter tuning with TensorFlow/Keras—into your existing script to perform Random Search.
Step 1: Install Keras Tuner
First, ensure that you have the Keras Tuner library installed. You can install it using pip:
pip install keras-tuner
Step 2: Import Necessary Libraries
Add the Keras Tuner imports at the beginning of your script:
from kerastuner import RandomSearch
from kerastuner.engine.hyperparameters import HyperParameters
Step 3: Define the Model-Building Function
Create a function that builds and compiles your LSTM model. This function will accept a HyperParameters object to define the search space.
def build_model(hp):
model = Sequential()
# Tune the number of LSTM layers
for i in range(hp.Int('num_layers', 1, 3)):
# Tune the number of units in each LSTM layer
units = hp.Int(f'units_{i}', min_value=50, max_value=200, step=50)
if i == 0:
model.add(LSTM(units=units, return_sequences=(i < hp.Int('num_layers', 1, 3) - 1), input_shape=(X_train.shape[1], X_train.shape[2])))
else:
model.add(LSTM(units=units, return_sequences=(i < hp.Int('num_layers', 1, 3) - 1)))
# Optionally add dropout
if hp.Boolean(f'dropout_{i}'):
model.add(tf.keras.layers.Dropout(rate=hp.Float(f'dropout_rate_{i}', 0.0, 0.5, step=0.1)))
# Add Dense layer
model.add(Dense(1))
# Tune the learning rate for the optimizer
learning_rate = hp.Float('learning_rate', 1e-4, 1e-2, sampling='log')
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
loss='mean_squared_error',
metrics=['mean_absolute_percentage_error'])
return model
Step 4: Initialize the Random Search Tuner
Set up the Random Search tuner with the defined model-building function and specify the search space parameters such as the number of trials and executions per trial.
# Initialize the Random Search tuner
tuner = RandomSearch(
build_model,
objective='val_mean_absolute_percentage_error',
max_trials=20, # Number of different hyperparameter combinations to try
executions_per_trial=1, # Number of models to build and fit for each trial
directory='lstm_tuner',
project_name='stock_price_prediction'
)
Step 5: Define Early Stopping to Prevent Overfitting During Tuning
Implement early stopping to save time during the hyperparameter search by halting training when the model stops improving.
# Define Early Stopping
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
Step 6: Run the Hyperparameter Search
Fit the tuner to explore different hyperparameter combinations.
# Perform hyperparameter search
tuner.search(
X_train, y_train,
epochs=100,
batch_size=16,
validation_split=0.1,
callbacks=[early_stop],
verbose=1
)
Step 7: Retrieve the Best Model
After the search is complete, retrieve the best model and evaluate its performance.
# Get the optimal hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print(f"""
The hyperparameter search is complete. The optimal number of layers is {best_hps.get('num_layers')},
with each LSTM layer having units: {[best_hps.get(f'units_{i}') for i in range(best_hps.get('num_layers'))]]},
and the optimal learning rate for the optimizer is {best_hps.get('learning_rate')}.
""")
# Build the best model
best_model = tuner.hypermodel.build(best_hps)
# Train the best model
history = best_model.fit(
X_train, y_train,
epochs=100,
batch_size=16,
validation_split=0.1,
callbacks=[early_stop],
verbose=1
)
# Evaluate the best model on the test set
predictions = best_model.predict(X_test)
# Inverse Transform and calculate MAPE as before
# ... (same as in your original script)
Step 8: Adjust the Original Training Process
Since the tuner already trains models, you might want to separate the tuning phase from the final training. Once you have the best hyperparameters, you can proceed to train the final model on the entire training data and then perform predictions as you did originally.
Complete Integration Example
Here’s how you can integrate the above steps into your existing script. I'll provide the modified sections while keeping the rest of your script intact.
# ... [Your existing imports and initial setup] ...
# Add Keras Tuner imports
from kerastuner import RandomSearch
from kerastuner.engine.hyperparameters import HyperParameters
# ... [Your data loading and preprocessing steps] ...
# 4. Create Sequences for LSTM (unchanged)
def create_sequences(data, sequence_length):
X = []
y = []
for i in range(sequence_length, len(data)):
X.append(data[i-sequence_length:i])
y.append(data[i][3]) # 'Closing Price' is the 4th feature (index 3)
return np.array(X), np.array(y)
sequence_length = 70 # You can adjust this value
X, y = create_sequences(scaled_data, sequence_length)
# 5. Manual Train-Test Split to Ensure Alignment (unchanged)
train_size = int(len(X) * 0.8)
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
# 6. Define the Model-Building Function for Keras Tuner
def build_model(hp):
model = Sequential()
# Tune the number of LSTM layers
for i in range(hp.Int('num_layers', 1, 3)):
# Tune the number of units in each LSTM layer
units = hp.Int(f'units_{i}', min_value=50, max_value=200, step=50)
if i == 0:
model.add(LSTM(units=units, return_sequences=(i < hp.Int('num_layers', 1, 3) - 1), input_shape=(X_train.shape[1], X_train.shape[2])))
else:
model.add(LSTM(units=units, return_sequences=(i < hp.Int('num_layers', 1, 3) - 1)))
# Optionally add dropout
if hp.Boolean(f'dropout_{i}'):
model.add(tf.keras.layers.Dropout(rate=hp.Float(f'dropout_rate_{i}', 0.0, 0.5, step=0.1)))
# Add Dense layer
model.add(Dense(1))
# Tune the learning rate for the optimizer
learning_rate = hp.Float('learning_rate', 1e-4, 1e-2, sampling='log')
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
loss='mean_squared_error',
metrics=['mean_absolute_percentage_error'])
return model
# Initialize the Random Search tuner
tuner = RandomSearch(
build_model,
objective='val_mean_absolute_percentage_error',
max_trials=20, # You can adjust this number
executions_per_trial=1,
directory='lstm_tuner',
project_name='stock_price_prediction'
)
# Define Early Stopping
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
# Perform hyperparameter search
tuner.search(
X_train, y_train,
epochs=100,
batch_size=16,
validation_split=0.1,
callbacks=[early_stop],
verbose=1
)
# Get the optimal hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print(f"""
The hyperparameter search is complete. The optimal number of layers is {best_hps.get('num_layers')},
with each LSTM layer having units: {[best_hps.get(f'units_{i}') for i in range(best_hps.get('num_layers'))]]},
and the optimal learning rate for the optimizer is {best_hps.get('learning_rate')}.
""")
# Build the best model
best_model = tuner.hypermodel.build(best_hps)
# Train the best model
history = best_model.fit(
X_train, y_train,
epochs=100,
batch_size=16,
validation_split=0.1,
callbacks=[early_stop],
verbose=1
)
# 9. Make Predictions on Test Set using the Best Model
predictions = best_model.predict(X_test)
# Inverse Transform to Get Actual Prices (unchanged)
scaler_target = MinMaxScaler()
scaler_target.min_ = scaler.min_[3]
scaler_target.scale_ = scaler.scale_[3]
y_test_inverse = scaler_target.inverse_transform(y_test.reshape(-1, 1))
predictions_inverse = scaler_target.inverse_transform(predictions)
# 10. Calculate MAPE (unchanged)
mape = mean_absolute_percentage_error(y_test_inverse, predictions_inverse)
print(f"\nMean Absolute Percentage Error (MAPE): {mape * 100:.2f}%")
# 11. Plot Actual vs Predicted Closing Prices (unchanged)
plt.figure(figsize=(14, 7))
plt.plot(y_test_inverse, color='blue', label='Actual Closing Price')
plt.plot(predictions_inverse, color='red', label='Predicted Closing Price')
plt.title('Actual vs Predicted Closing Prices')
plt.xlabel('Time')
plt.ylabel('Closing Price')
plt.legend()
plt.show()
# ... [The rest of your script for future predictions remains unchanged] ...
Additional Recommendations
-
Monitor Overfitting:
- Ensure that your model isn't overfitting by comparing training and validation loss. Use dropout and regularization as needed.
-
Data Quality:
- When adding more data, ensure that it's clean and consistent. Poor quality data can degrade model performance.
-
Feature Engineering:
- With more data, consider adding more features or engineering new ones that might help the model learn better.
-
Scaling:
- Always scale your data appropriately, especially when using neural networks. Ensure that scaling parameters are derived from the training set only to prevent data leakage.
-
Sequence Length:
- Experiment with different sequence lengths (
sequence_length = 70) to see if shorter or longer sequences improve performance.
-
Increase Search Space:
- Depending on computational resources, you might want to explore a broader range of hyperparameters or increase the number of trials in the Random Search.
Conclusion
By integrating Keras Tuner’s Random Search into your LSTM model pipeline, you can systematically explore different hyperparameter configurations to find the optimal settings that enhance your model’s performance, especially when dealing with larger datasets. This approach helps in adapting the model to new data trends and complexities introduced by the increased dataset size.
Feel free to adjust the max_trials, search ranges, and other hyperparameters based on your specific requirements and computational resources.