Files
remote-sensing/scripts/training/train_ndvi_convlstm.py
T

81 lines
2.7 KiB
Python

#!/usr/bin/env python
# coding: utf-8
import os
import json
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from tqdm import tqdm
from core.ndvi_data_loader import NDVITimeSeriesDataset
print("=" * 70)
print("🚀 Training ConvLSTM Spatial-Temporal model for NDVI (REAL DATA & GPU)")
print("=" * 70)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"[SYSTEM] Device: {device.type.upper()}")
dataset = NDVITimeSeriesDataset(sequence_length=3, spatial=True)
dataloader = DataLoader(dataset, batch_size=2, shuffle=True)
class ConvLSTMCell(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3):
super().__init__()
self.conv = nn.Conv2d(in_channels + out_channels, 4 * out_channels, kernel_size, padding=1)
def forward(self, x, h, c):
combined = torch.cat([x, h], dim=1)
gates = self.conv(combined)
i, f, o, g = torch.chunk(gates, 4, dim=1)
i, f, o, g = torch.sigmoid(i), torch.sigmoid(f), torch.sigmoid(o), torch.tanh(g)
c_next = f * c + i * g
h_next = o * torch.tanh(c_next)
return h_next, c_next
class MiniConvLSTM(nn.Module):
def __init__(self):
super().__init__()
self.cell = ConvLSTMCell(1, 16)
self.out_conv = nn.Conv2d(16, 1, kernel_size=1)
def forward(self, x):
B, T, C, H, W = x.shape
h = torch.zeros(B, 16, H, W).to(x.device)
c = torch.zeros(B, 16, H, W).to(x.device)
for t in range(T):
h, c = self.cell(x[:, t], h, c)
return self.out_conv(h)
model = MiniConvLSTM().to(device)
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=1e-3)
print("\n[TRAIN] Bắt đầu Training...")
model.train()
total_loss = 0
for epoch in range(20):
for inputs, targets in dataloader:
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
total_loss += loss.item()
avg_loss = total_loss / (len(dataloader) * 20)
print(f"✅ Training completed! Avg MSE Loss (RMSE): {avg_loss**0.5:.4f}")
model_dir = "ndvi_forecast_model"
model_path = os.path.join(model_dir, "ndvi_convlstm_real.pth")
torch.save(model.state_dict(), model_path)
with open(os.path.join(model_dir, "ndvi_convlstm_real_info.json"), "w") as f:
json.dump({
"model_type": "ConvLSTM Spatial-Temporal (Real Data & GPU)",
"target": "NDVI", "epoch": 20,
"rmse": float(avg_loss**0.5), "mae": float(avg_loss)
}, f, indent=2)
print("[SAVE] Model info saved.")