To tackle the task of forecasting 2D wildfire propagation using spatio-temporal machine learning models, we'll develop a state-of-the-art model leveraging Convolutional Long Short-Term Memory (ConvLSTM) networks. ConvLSTM is well-suited for handling spatio-temporal data as it captures both spatial dependencies (via convolutional layers) and temporal dynamics (via LSTM units).
Additionally, we'll incorporate global features such as slope (alpha) and mean wind speed (u10) by concatenating them into the model, ensuring that these scalar values influence the prediction. To enhance interpretability and infuse physical information, we can integrate constraints or regularizations based on domain knowledge, but for simplicity, this example focuses on the model architecture and training pipeline.
Below is a comprehensive Python implementation using PyTorch. This code includes data preprocessing, model definition, training, and validation. Please adjust dataset paths and parameters as needed to fit your specific dataset and computational resources.
1. Setup and Imports
import os
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
2. Dataset Preparation
Assuming your data is organized with sequences of frames for wind speed (ustar), temperature (theta), and fire-line location (xi), along with scalar features alpha and u10. Modify the WildfireDataset class according to your data's specific structure.
class WildfireDataset(Dataset):
def __init__(self, data_dir, seq_len=10, transform=None):
"""
Args:
data_dir (str): Path to the dataset.
seq_len (int): Number of past timesteps to use for prediction.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
super(WildfireDataset, self).__init__()
self.data_dir = data_dir
self.seq_len = seq_len
self.transform = transform
# Load your data here. This is a placeholder.
# For example, you might have .npy files for each variable.
# Assuming all data is preprocessed and split into sequences.
self.wind = np.load(os.path.join(data_dir, 'ustar.npy')) # Shape: (num_samples, seq_len, H, W)
self.temp = np.load(os.path.join(data_dir, 'theta.npy'))
self.fire = np.load(os.path.join(data_dir, 'xi.npy'))
self.alpha = np.load(os.path.join(data_dir, 'alpha.npy')) # Shape: (num_samples,)
self.u10 = np.load(os.path.join(data_dir, 'u10.npy'))
assert len(self.wind) == len(self.temp) == len(self.fire) == len(self.alpha) == len(self.u10)
def __len__(self):
return len(self.wind)
def __getitem__(self, idx):
wind_seq = self.wind[idx] # (seq_len, H, W)
temp_seq = self.temp[idx]
fire_seq = self.fire[idx]
alpha = self.alpha[idx]
u10 = self.u10[idx]
# Stack wind and temp as channels
# Shape: (seq_len, 2, H, W)
x = np.stack((wind_seq, temp_seq), axis=1)
# Target is the next fire-line location
y = fire_seq[-1] # Assuming the last frame is the target
# Global features
global_features = np.array([alpha, u10], dtype=np.float32)
if self.transform:
x, y, global_features = self.transform((x, y, global_features))
return torch.FloatTensor(x), torch.FloatTensor(y), torch.FloatTensor(global_features)
3. Model Definition
We'll define a ConvLSTM-based model that takes the sequence of wind and temperature maps along with global features to predict the fire-line location.
class ConvLSTMCell(nn.Module):
def __init__(self, input_dim, hidden_dim, kernel_size, bias):
"""
Initialize ConvLSTM cell.
"""
super(ConvLSTMCell, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.kernel_size = kernel_size
self.padding = kernel_size // 2
self.bias = bias
self.conv = nn.Conv2d(in_channels=self.input_dim + self.hidden_dim,
out_channels=4 * self.hidden_dim,
kernel_size=self.kernel_size,
padding=self.padding,
bias=self.bias)
def forward(self, input_tensor, cur_state):
h_cur, c_cur = cur_state
combined = torch.cat([input_tensor, h_cur], dim=1) # concatenate along channel axis
combined_conv = self.conv(combined)
cc_i, cc_f, cc_o, cc_g = torch.split(combined_conv, self.hidden_dim, dim=1)
i = torch.sigmoid(cc_i)
f = torch.sigmoid(cc_f)
o = torch.sigmoid(cc_o)
g = torch.tanh(cc_g)
c_next = f * c_cur + i * g
h_next = o * torch.tanh(c_next)
return h_next, c_next
def init_hidden(self, batch_size, spatial_size):
height, width = spatial_size
device = self.conv.weight.device
return (torch.zeros(batch_size, self.hidden_dim, height, width, device=device),
torch.zeros(batch_size, self.hidden_dim, height, width, device=device))
class ConvLSTM(nn.Module):
def __init__(self, input_dim, hidden_dim, kernel_size, num_layers, global_features_dim, output_dim):
super(ConvLSTM, self).__init__()
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.global_fc = nn.Linear(global_features_dim, hidden_dim)
self.layers = nn.ModuleList()
for i in range(num_layers):
cur_input_dim = input_dim if i == 0 else hidden_dim
self.layers.append(ConvLSTMCell(cur_input_dim, hidden_dim, kernel_size, bias=True))
self.conv = nn.Conv2d(hidden_dim, output_dim, kernel_size=1)
def forward(self, input_tensor, global_features):
# input_tensor: (batch, seq_len, input_dim, H, W)
batch_size, seq_len, _, height, width = input_tensor.size()
device = input_tensor.device
hidden_states = []
cell_states = []
for i in range(self.num_layers):
h, c = self.layers[i].init_hidden(batch_size, (height, width))
hidden_states.append(h)
cell_states.append(c)
# Process global features
global_out = self.global_fc(global_features) # (batch, hidden_dim)
for t in range(seq_len):
x = input_tensor[:, t, :, :, :] # (batch, input_dim, H, W)
for i, layer in enumerate(self.layers):
h, c = layer(x, (hidden_states[i], cell_states[i]))
hidden_states[i] = h
cell_states[i] = c
x = h
# Optionally, incorporate global features at each timestep
# Here, we concatenate a broadcasted global feature map
# Alternatively, you can modify the layers to accept global features
# This example does not explicitly use global features within the ConvLSTM layers
# After processing the sequence, use the last hidden state
final_hidden = hidden_states[-1] # (batch, hidden_dim, H, W)
output = self.conv(final_hidden) # (batch, output_dim, H, W)
return output
4. Training and Validation Functions
Define functions to train and validate the model. We'll use Mean Squared Error (MSE) as the loss function since we're dealing with regression.
def train_model(model, dataloader, criterion, optimizer, device):
model.train()
running_loss = 0.0
for inputs, targets, globals_ in dataloader:
inputs = inputs.to(device) # (batch, seq_len, input_dim, H, W)
targets = targets.to(device) # (batch, H, W)
globals_ = globals_.to(device) # (batch, 2)
optimizer.zero_grad()
outputs = model(inputs, globals_) # (batch, output_dim=1, H, W)
outputs = outputs.squeeze(1) # (batch, H, W)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
running_loss += loss.item() * inputs.size(0)
epoch_loss = running_loss / len(dataloader.dataset)
return epoch_loss
def validate_model(model, dataloader, criterion, device):
model.eval()
running_loss = 0.0
with torch.no_grad():
for inputs, targets, globals_ in dataloader:
inputs = inputs.to(device)
targets = targets.to(device)
globals_ = globals_.to(device)
outputs = model(inputs, globals_)
outputs = outputs.squeeze(1)
loss = criterion(outputs, targets)
running_loss += loss.item() * inputs.size(0)
epoch_loss = running_loss / len(dataloader.dataset)
return epoch_loss
5. Training Pipeline
Set up the training pipeline, including data loaders, model instantiation, optimizer, and loss function.
def main():
# Hyperparameters
data_dir = '/path/to/your/data' # Replace with your data directory
batch_size = 8
num_epochs = 50
learning_rate = 1e-3
seq_len = 10
input_dim = 2 # wind speed and temperature
hidden_dim = 64
kernel_size = 3
num_layers = 2
output_dim = 1 # fire-line location
global_features_dim = 2 # alpha and u10
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Prepare Dataset
dataset = WildfireDataset(data_dir, seq_len=seq_len)
train_size, val_size = train_test_split(len(dataset), test_size=0.2, random_state=42)
train_dataset, val_dataset = torch.utils.data.random_split(dataset, [train_size, val_size])
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=4)
# Initialize Model
model = ConvLSTM(input_dim=input_dim,
hidden_dim=hidden_dim,
kernel_size=kernel_size,
num_layers=num_layers,
global_features_dim=global_features_dim,
output_dim=output_dim).to(device)
# Loss and Optimizer
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Training Loop
best_val_loss = float('inf')
for epoch in range(num_epochs):
train_loss = train_model(model, train_loader, criterion, optimizer, device)
val_loss = validate_model(model, val_loader, criterion, device)
print(f"Epoch {epoch+1}/{num_epochs} | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}")
# Save the best model
if val_loss < best_val_loss:
best_val_loss = val_loss
torch.save(model.state_dict(), 'best_model.pth')
print("Saved Best Model")
# Plotting loss curves
# (Optional) You can store epoch losses and plot them here
if __name__ == '__main__':
main()
6. Inference and Visualization
After training, you can load the best model and perform inference on the validation set or new data. Here's an example of how to visualize the predictions.
def visualize_prediction(model, dataloader, device, num_samples=3):
model.eval()
with torch.no_grad():
for i, (inputs, targets, globals_) in enumerate(dataloader):
if i >= num_samples:
break
inputs = inputs.to(device)
targets = targets.to(device)
globals_ = globals_.to(device)
outputs = model(inputs, globals_)
outputs = outputs.squeeze(1).cpu().numpy()
targets = targets.cpu().numpy()
for j in range(inputs.size(0)):
plt.figure(figsize=(12, 4))
plt.subplot(1, 3, 1)
plt.title("Input Wind")
plt.imshow(inputs[j, -1, 0, :, :].cpu(), cmap='jet')
plt.colorbar()
plt.subplot(1, 3, 2)
plt.title("True Fire Line")
plt.imshow(targets[j], cmap='hot')
plt.colorbar()
plt.subplot(1, 3, 3)
plt.title("Predicted Fire Line")
plt.imshow(outputs[j], cmap='hot')
plt.colorbar()
plt.show()
# To use the visualization, add the following after training:
# load the best model
model.load_state_dict(torch.load('best_model.pth'))
visualize_prediction(model, val_loader, device)
7. Enhancements and Considerations
-
Data Preprocessing: Ensure that your data is normalized appropriately. For example, wind speed and temperature can be standardized or scaled to a specific range.
-
Sequence Prediction: The current model predicts the fire-line at the next timestep. For multi-step forecasting, you might need to iterate the prediction or modify the model to predict multiple future frames.
-
Physical Constraints: To infuse physical information, consider adding regularization terms to the loss that enforce physics-based relationships or use architectures that inherently respect physical laws.
-
Advanced Architectures: Explore transformer-based models for potentially better performance on long sequences or more complex dependencies.
-
Hyperparameter Tuning: Experiment with different hyperparameters such as learning rate, hidden dimensions, number of layers, and sequence lengths to optimize performance.
-
Evaluation Metrics: Besides MSE, consider using other metrics like Structural Similarity Index (SSIM) or Intersection over Union (IoU) for better assessment of spatial predictions.
-
Data Augmentation: Apply spatial augmentations (e.g., rotations, flips) to increase the diversity of training data and improve model generalization.
This implementation provides a solid foundation for developing a spatio-temporal model to forecast wildfire spread. Depending on the specific characteristics of your dataset and the challenge requirements, you might need to adjust or extend this code accordingly.