Certainly! The issue you've identified is that by appending all simulation data together, the LSTM is being trained and tested on sequences that include unrealistic discontinuities at the points where one simulation ends and another begins. This can introduce artificial patterns into the model that don't exist in real operational conditions and can degrade the performance of your predictions.
To properly address this problem, we need to ensure that the LSTM only processes continuous sequences from within the same simulation and that these sequences do not cross over into data from other simulations. Here's how we can do this:
-
Generate Sequences Within Simulations:
- Instead of treating each entire simulation as a single sequence, we'll split the data from each simulation into multiple smaller sequences of a fixed length.
- This way, the LSTM will learn from realistic, continuous patterns within each simulation without being affected by the discontinuities between simulations.
-
Ensure Sequences Don't Cross Simulations:
- We'll use grouping to make sure that when we split our data into training and test sets, sequences from the same simulation are only in one set (either training or testing), not both.
- This prevents data leakage and ensures the model isn't trained on patterns that might appear in the test set due to the same simulation conditions.
-
Adjust the Model for Sequence Prediction:
- We'll modify the LSTM model to predict a single target value for each input sequence, which is more appropriate for many time series regression tasks.
- This involves setting
return_sequences=False in the final LSTM layer.
Below is the modified code that incorporates these changes:
import pandas as pd
import numpy as np
import pickle
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import GroupShuffleSplit
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping, Callback
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
import matplotlib.pyplot as plt
import time
# ===========================
# 1. Data Loading and Preprocessing
# ===========================
# Set simulation data loading option (only "option1" is available now)
simulation_data = "option1"
# Initialize lists to hold features and targets
X_sequences = []
y_sequences = []
groups = []
sequence_length = 50 # Define the length of sequences
if simulation_data == "option1":
# Define file paths for each variable
file_paths = {
'heave': 'heave_data.txt',
'heaveVelocity': 'heaveVelocity_data.txt',
'surge': 'surge_data.txt',
'surgeVelocity': 'surgeVelocity_data.txt',
'sway': 'sway_data.txt',
'swayVelocity': 'swayVelocity_data.txt',
'cable_tension': 'compression_max_data.txt'
}
# Load each variable's data from the respective text files
data_dict = {}
for variable, file_path in file_paths.items():
data = pd.read_csv(file_path, header=None)
data_dict[variable] = data # Each column represents a separate simulation
num_simulations = data_dict['heave'].shape[1] # Number of simulations
# Extract features and targets for each simulation and generate sequences
for i in range(num_simulations):
# Extract features for the i-th simulation
heave = data_dict['heave'].iloc[:, i].values
heaveVelocity = data_dict['heaveVelocity'].iloc[:, i].values
surge = data_dict['surge'].iloc[:, i].values
surgeVelocity = data_dict['surgeVelocity'].iloc[:, i].values
sway = data_dict['sway'].iloc[:, i].values
swayVelocity = data_dict['swayVelocity'].iloc[:, i].values
# Stack features horizontally (shape: [time_steps, 6])
features = np.column_stack([
heave,
heaveVelocity,
surge,
surgeVelocity,
sway,
swayVelocity
])
# Extract target for the i-th simulation
target = data_dict['cable_tension'].iloc[:, i].values # Shape: [time_steps]
# Generate sequences
num_sequences = len(features) - sequence_length
for t in range(num_sequences):
X_seq = features[t:t + sequence_length]
y_seq = target[t + sequence_length] # Predicting the value at t + sequence_length
X_sequences.append(X_seq)
y_sequences.append(y_seq)
groups.append(i) # Keep track of the simulation index
# Convert lists to NumPy arrays
X_sequences = np.array(X_sequences) # Shape: [num_sequences_total, sequence_length, num_features]
y_sequences = np.array(y_sequences) # Shape: [num_sequences_total]
groups = np.array(groups) # Shape: [num_sequences_total]
# ===========================
# 2. Train-Test Split with Grouping
# ===========================
from sklearn.model_selection import GroupShuffleSplit
# Split the data into training and testing sets using GroupShuffleSplit
gss = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
train_idx, test_idx = next(gss.split(X_sequences, y_sequences, groups=groups))
X_train, X_test = X_sequences[train_idx], X_sequences[test_idx]
y_train, y_test = y_sequences[train_idx], y_sequences[test_idx]
# Now, sequences from the same simulation are only in one set
# ===========================
# 3. Data Scaling
# ===========================
# Initialize scalers
scaler_features = MinMaxScaler()
scaler_target = MinMaxScaler()
# Flatten the training data to fit the scalers
X_train_flat = X_train.reshape(-1, X_train.shape[2]) # Shape: [num_samples * seq_length, n_features]
y_train_flat = y_train.reshape(-1, 1) # Shape: [num_samples, 1]
# Fit scalers on training data
scaler_features.fit(X_train_flat)
scaler_target.fit(y_train_flat)
# Transform training data
X_train_scaled = scaler_features.transform(X_train_flat).reshape(X_train.shape)
y_train_scaled = scaler_target.transform(y_train_flat).reshape(-1)
# Transform testing data
X_test_flat = X_test.reshape(-1, X_test.shape[2])
y_test_flat = y_test.reshape(-1, 1)
X_test_scaled = scaler_features.transform(X_test_flat).reshape(X_test.shape)
y_test_scaled = scaler_target.transform(y_test_flat).reshape(-1)
# ===========================
# 4. Custom Callback for Timing
# ===========================
class TimeHistory(Callback):
def on_train_begin(self, logs=None):
self.times = []
def on_epoch_begin(self, epoch, logs=None):
self.epoch_time_start = time.time()
def on_epoch_end(self, epoch, logs=None):
epoch_time = time.time() - self.epoch_time_start
self.times.append(epoch_time)
print(f"Epoch {epoch + 1} time: {epoch_time:.2f} seconds")
time_callback = TimeHistory()
# ===========================
# 5. Building the LSTM Model
# ===========================
sequence_length = X_train_scaled.shape[1]
n_features = X_train_scaled.shape[2]
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(sequence_length, n_features)))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=False)) # Changed to return_sequences=False
model.add(Dropout(0.2))
model.add(Dense(units=1)) # Output layer for regression
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# ===========================
# 6. Training the Model
# ===========================
# EarlyStopping to prevent overfitting
early_stopping = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
# Start training timer
start_time = time.time()
# Train the model
history = model.fit(
X_train_scaled, y_train_scaled,
epochs=100,
batch_size=32,
validation_split=0.2,
callbacks=[early_stopping, time_callback],
shuffle=True # Shuffle for better generalization
)
# End training timer
end_time = time.time()
total_time = end_time - start_time
print(f"Total Training Time: {total_time:.2f} seconds")
# ===========================
# 7. Saving the Model and Scalers
# ===========================
# Save the trained model
model.save('cable_tension_lstm_model.h5')
print("Model saved to disk as 'cable_tension_lstm_model.h5'")
# Save the scalers
with open('scaler_features.pkl', 'wb') as f:
pickle.dump(scaler_features, f)
with open('scaler_target.pkl', 'wb') as f:
pickle.dump(scaler_target, f)
print("Scalers saved to disk as 'scaler_features.pkl' and 'scaler_target.pkl'")
# ===========================
# 8. Loading the Model and Scalers
# ===========================
# Load the model
loaded_model = load_model('cable_tension_lstm_model.h5')
# Load the scalers
with open('scaler_features.pkl', 'rb') as f:
loaded_scaler_features = pickle.load(f)
with open('scaler_target.pkl', 'rb') as f:
loaded_scaler_target = pickle.load(f)
# ===========================
# 9. Making Predictions
# ===========================
# Predict on the test set
y_pred_scaled = loaded_model.predict(X_test_scaled) # Shape: [num_samples, 1]
# Inverse transform the predictions and actual values to original scale
y_pred = loaded_scaler_target.inverse_transform(y_pred_scaled).flatten()
y_test_original = loaded_scaler_target.inverse_transform(y_test_scaled.reshape(-1, 1)).flatten()
# ===========================
# 10. Evaluating the Model
# ===========================
# Calculate performance metrics
mse = mean_squared_error(y_test_original, y_pred)
rmse = np.sqrt(mse)
mae = mean_absolute_error(y_test_original, y_pred)
# Avoid division by zero in MAPE
non_zero = y_test_original != 0
mape = np.mean(np.abs((y_test_original[non_zero] - y_pred[non_zero]) / y_test_original[non_zero])) * 100
r2 = r2_score(y_test_original, y_pred)
print(f"Mean Squared Error (MSE): {mse:.4f}")
print(f"Root Mean Squared Error (RMSE): {rmse:.4f}")
print(f"Mean Absolute Error (MAE): {mae:.4f}")
print(f"Mean Absolute Percentage Error (MAPE): {mape:.2f}%")
print(f"R2 Score: {r2:.4f}")
# ===========================
# 11. Visualizing the Results
# ===========================
plt.figure(figsize=(12, 6))
plt.plot(y_test_original, label='Actual Cable Tension', alpha=0.7)
plt.plot(y_pred, label='Predicted Cable Tension', alpha=0.7)
plt.title('Actual vs Predicted Cable Tension')
plt.xlabel('Samples')
plt.ylabel('Cable Tension (kN)')
plt.legend()
plt.show()
Explanation of Changes:
-
Data Sequencing Within Simulations:
- We introduced a
sequence_length (e.g., 50) and generated sequences within each simulation without crossing over to other simulations.
- This is done by sliding a window over each simulation's data and extracting sequences of fixed length.
-
Group-Aware Train-Test Split:
- We used
GroupShuffleSplit from scikit-learn to split the data into training and testing sets, ensuring that sequences from the same simulation are not shared between the sets.
-
Adjusted Scaling Procedure:
- Scaling is performed on the flattened training data and then reshaped back to the original dimensions after transformation.
-
Modified LSTM Model Architecture:
- The last LSTM layer's
return_sequences parameter is set to False since we're predicting a single target value for each sequence.
- The output layer remains a
Dense layer with a single unit for regression.
-
Consistent Evaluation Metrics:
- The evaluation metrics remain the same, but they're computed on the properly sequenced and non-overlapping test data.
By implementing these changes, the LSTM model now learns from realistic, continuous sequences within each simulation and avoids the unrealistic discontinuities that occur between simulations. This should improve the model's ability to generalize and provide more accurate predictions on new data.
Feel free to adjust the sequence_length based on the specifics of your data and the temporal dependencies in your problem. Longer sequences capture more temporal context but may require more computational resources and data.