Certainly! Let's address the issues in your Python script for time series regression using LSTM and provide a corrected and optimized version. Below are the key areas we'll focus on:
- Indentation and Syntax: Ensuring proper code structure for readability and execution.
- Data Scaling: Avoiding data leakage by fitting scalers only on the training data.
- Sequence Padding: Handling padding appropriately based on whether sequences have uniform lengths.
- Model Architecture: Ensuring the LSTM layers align with the output shape.
- Performance Metrics: Correctly calculating metrics without unintended data modifications.
Here's the revised script with detailed explanations and corrections:
import pandas as pd
import numpy as np
import pickle
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
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_all = []
y_all = []
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': 'Top_tension_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
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]
X_all.append(features)
y_all.append(target)
# Convert lists to NumPy arrays
X_all = np.array(X_all) # Shape: [num_simulations, time_steps, 6]
y_all = np.array(y_all) # Shape: [num_simulations, time_steps]
# ===========================
# 2. Train-Test Split
# ===========================
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
X_all, y_all, test_size=0.2, random_state=42
)
# ===========================
# 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_sim * time_steps, 6]
y_train_flat = y_train.flatten().reshape(-1, 1) # Shape: [num_sim * time_steps, 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(y_train.shape)
# Transform testing data
X_test_flat = X_test.reshape(-1, X_test.shape[2])
y_test_flat = y_test.flatten().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(y_test.shape)
# Expand y dimensions for LSTM (required shape: [samples, time_steps, 1])
y_train_scaled = y_train_scaled[:, :, np.newaxis]
y_test_scaled = y_test_scaled[:, :, np.newaxis]
# ===========================
# 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
# ===========================
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train_scaled.shape[1], X_train_scaled.shape[2])))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
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, # Increased batch size for efficiency
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)
# Inverse transform the predictions and actual values to original scale
y_pred = loaded_scaler_target.inverse_transform(y_pred_scaled.reshape(-1, 1)).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()
Detailed Explanations and Corrections
-
Indentation and Syntax:
- Ensured that all code blocks are properly indented for readability and to prevent
IndentationError.
- Organized the script into logical sections with comments for better understanding.
-
Data Scaling:
- Avoided Data Leakage: Scalers (
MinMaxScaler) are fitted only on the training data. This ensures that the model doesn't have prior knowledge of the test data, leading to a more accurate evaluation.
- Scaling Process:
- Flattened the training features and targets to fit the scalers.
- Transformed both training and testing data using the fitted scalers.
- Reshaped the scaled data back to their original dimensions suitable for LSTM input.
-
Sequence Padding:
- Assumption: All simulations have the same number of time steps. If this is not the case, additional steps for padding and masking would be necessary.
- Padding: Since sequences are assumed to have uniform lengths, padding is skipped to simplify the model architecture.
-
Model Architecture:
- LSTM Layers:
- Both LSTM layers have
return_sequences=True to maintain the sequence output, aligning with the target shape.
- Dropout Layers: Added after each LSTM layer to prevent overfitting.
- Dense Layer: Concludes the model with a single neuron suitable for regression tasks.
- Batch Size: Increased to 32 from 1 for computational efficiency. Adjust as needed based on dataset size and hardware capabilities.
-
Performance Metrics:
- MAPE Calculation: Ensured that division by zero is avoided by filtering out zero targets.
- Flattened Predictions: Both predictions and actual values are flattened to compute metrics accurately.
- Consistency: Metrics are calculated on the same number of samples to ensure validity.
-
Additional Recommendations:
- Early Stopping: Monitors
val_loss with a patience of 10 epochs to halt training when no improvement is observed.
Handling Variable Sequence Lengths (If Applicable)
If your simulations have varying numbers of time steps, you'll need to incorporate padding and masking to handle the different sequence lengths. Here's how you can modify the script to accommodate this:
-
Import Necessary Module:
from tensorflow.keras.layers import Masking
-
Apply Padding:
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Determine the maximum sequence length
max_length = max(x.shape[0] for x in X_all)
# Apply padding
X_all_padded = pad_sequences(X_all, maxlen=max_length, dtype='float32', padding='post')
y_all_padded = pad_sequences(y_all, maxlen=max_length, dtype='float32', padding='post')
-
Modify the Model:
model = Sequential()
# Add Masking layer to ignore the padded time steps
model.add(Masking(mask_value=0.0, input_shape=(max_length, X_train_scaled.shape[2])))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(Dense(units=1))
-
Ensure Proper Scaling: When sequences are padded, ensure that the padded values do not interfere with scaling (e.g., scaling should map padded zeros correctly).
Final Notes
- Batch Size: Depending on your dataset size and available computational resources, you might need to adjust the
batch_size for optimal performance.
- Model Complexity: The number of LSTM units and layers can be tuned based on the complexity of your data and the performance of the model.
- Evaluation: Always evaluate the model on unseen data to ensure its generalizability.
By implementing these corrections and optimizations, your script should run more effectively, providing accurate time series regression results for cable tension based on vessel motion features.