import os
import random
import subprocess
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
plt.style.use('seaborn-v0_8-whitegrid')
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'PyTorch {torch.__version__} | pandas {pd.__version__} | device: {device}')Day 4, Session 2: LSTM Drought Forecasting Lab (Instructor Notebook)
Forecasting monthly Sentinel-2 NDVI for Bukidnon and South Cotabato, Mindanao
Learning objectives
By the end of this lab you will be able to:
- Retrieve a monthly Sentinel-2 NDVI time series for two Mindanao provinces with Google Earth Engine (or load the cached sample)
- Turn the series into supervised sliding-window samples (12 months in → next month out)
- Split the data by time (train / validation / test years) and scale it without leakage
- Build and train a two-layer LSTM in PyTorch, with early stopping
- Compare the LSTM against simple baselines and turn forecasts into drought alerts (precision / recall)
What you’ll need
- Runtime: Google Colab (CPU is enough; training takes well under a minute) or a local Python 3.10+ environment with PyTorch 2.x, pandas, NumPy and matplotlib
- Data: by default the lab uses a small cached file,
day4/data/mindanao_ndvi_sample.csv(monthly mean NDVI, 2018-2023, two provinces). The notebook finds it locally or downloads it from the course repository - Optional: live Sentinel-2 NDVI from Earth Engine. This needs an Earth Engine account and a Google Cloud project registered for Earth Engine (free for non-commercial use)
- Time: about 2.5 hours, including discussion
How to use this notebook
- This is the worked-solution version. It has the same parts as the student notebook; every TODO is solved here.
- Run it once before class. Earth Engine is off by default so the lab runs offline; to demonstrate live data, set
USE_EARTH_ENGINE = Trueand your Cloud project ID in Part 2. - If Earth Engine or the network is slow during delivery, keep the cached sample: the modelling part is identical.
Framework note: Session 1 used TensorFlow/Keras. This lab deliberately uses PyTorch so that you see the same LSTM idea in both major frameworks. The architecture (2 LSTM layers, 64 → 32 units, dropout 0.2, small dense head) is the same as in Session 1.
Part 1 · Setup
Imports, random seeds (for reproducible results) and the compute device.
Expected output: library versions and device: cpu (or cuda on a GPU runtime).
Part 2 · Connect to Google Earth Engine (optional)
Earth Engine now requires a Google Cloud project registered for Earth Engine: ee.Initialize(project="your-cloud-project"). Leave USE_EARTH_ENGINE = False to work with the cached sample. If the connection fails, the notebook prints the reason and falls back to the cached sample, so the rest of the lab still runs.
Expected output: either Connected to Earth Engine project: ... or Earth Engine disabled: the lab will use the cached NDVI sample.
USE_EARTH_ENGINE = False # set to True for live Sentinel-2 NDVI
EE_PROJECT = os.environ.get('EE_PROJECT', 'your-cloud-project') # replace with your Cloud project ID
ee = None
if USE_EARTH_ENGINE:
try:
try:
import ee
except ImportError: # earthengine-api is preinstalled on Colab; install it elsewhere
subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', 'earthengine-api'], check=True)
import ee
if EE_PROJECT == 'your-cloud-project':
raise ValueError('set EE_PROJECT to your own Cloud project ID first')
try:
ee.Initialize(project=EE_PROJECT)
except Exception:
ee.Authenticate() # opens a sign-in prompt (Colab) or a browser window (local)
ee.Initialize(project=EE_PROJECT)
print(f'Connected to Earth Engine project: {EE_PROJECT}')
except Exception as exc:
print(f'Earth Engine not available ({exc}). Falling back to the cached NDVI sample.')
USE_EARTH_ENGINE = False
else:
print('Earth Engine disabled: the lab will use the cached NDVI sample.')Part 3 · Study areas and period
Two provinces with large rain-fed corn and other upland crops: Bukidnon and South Cotabato. To keep the lab simple we use rough bounding boxes (lon/lat) rather than official boundaries; for real work use administrative boundaries (for example from NAMRIA or the PSA) and mask to cropland, as fetch_monthly_ndvi() does with ESA WorldCover.
# Rough bounding boxes: [west, south, east, north]
REGIONS = {
'Bukidnon': [124.36, 7.05, 125.63, 8.84],
'South Cotabato': [124.28, 5.68, 125.30, 6.88],
}
# Period used for a live Earth Engine fetch (end date is exclusive)
START_DATE, END_DATE = '2019-01-01', '2026-01-01'Part 4 · Helper: monthly Sentinel-2 NDVI from Earth Engine
For each province and month: take Sentinel-2 surface reflectance (COPERNICUS/S2_SR_HARMONIZED), mask clouds and shadows with the Scene Classification Layer (SCL), compute NDVI, build a median composite, keep only cropland pixels (ESA WorldCover class 40) and average over the province. One request per province and year keeps the requests small.
This cell only defines the function; it is called in Part 5 when USE_EARTH_ENGINE = True.
def fetch_monthly_ndvi(regions, start_date, end_date, cloud_pct=60, scale=100, cropland_only=True):
"""Return a wide DataFrame: month, NDVI_<Region> (one column per region, spaces removed)."""
def mask_and_ndvi(image):
scl = image.select('SCL')
clear = scl.eq(4).Or(scl.eq(5)).Or(scl.eq(6)) # vegetation, bare soil, water
ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
return ndvi.updateMask(clear).copyProperties(image, ['system:time_start'])
s2 = (ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
.filterDate(start_date, end_date)
.filter(ee.Filter.lte('CLOUDY_PIXEL_PERCENTAGE', cloud_pct))
.map(mask_and_ndvi))
cropland = ee.ImageCollection('ESA/WorldCover/v200').first().eq(40) if cropland_only else None
months = pd.date_range(start_date, end_date, freq='MS', inclusive='left')
records = []
for name, bbox in regions.items():
geom = ee.Geometry.Rectangle(bbox)
def monthly_mean(date_str):
start = ee.Date(date_str)
img = s2.filterBounds(geom).filterDate(start, start.advance(1, 'month')).median()
if cropland is not None:
img = img.updateMask(cropland)
stats = img.reduceRegion(reducer=ee.Reducer.mean(), geometry=geom, scale=scale,
bestEffort=True, maxPixels=1e9)
value = ee.Algorithms.If(stats.contains('NDVI'), stats.get('NDVI'), None)
return ee.Feature(None, {'month': start.format('YYYY-MM-01'), 'ndvi': value})
for year in sorted(set(months.year)): # one request per region and year
dates = [d.strftime('%Y-%m-%d') for d in months[months.year == year]]
fc = ee.FeatureCollection(ee.List(dates).map(monthly_mean))
for feat in fc.getInfo()['features']:
records.append({'month': feat['properties']['month'], 'location': name,
'ndvi': feat['properties'].get('ndvi')})
print(f' fetched {name}')
df = pd.DataFrame(records)
df['month'] = pd.to_datetime(df['month'])
wide = df.pivot(index='month', columns='location', values='ndvi').sort_index()
wide = wide.interpolate(limit_direction='both') # fill months with no clear observation
wide.columns = [f'NDVI_{c.replace(" ", "")}' for c in wide.columns]
return wide.reset_index()Part 5 · Load the NDVI data (live from Earth Engine or cached sample)
The cached sample is looked up next to the notebook (../data/, day4/data/ or the current folder) and otherwise downloaded from the course repository.
Expected output (cached sample): 72 rows (January 2018 to December 2023) and the columns month, NDVI_Bukidnon, NDVI_SouthCotabato.
SAMPLE_URL = ('https://raw.githubusercontent.com/anefelo/eo-ai-ml-training/main/'
'day4/data/mindanao_ndvi_sample.csv')
def load_cached_sample():
for candidate in [Path('../data/mindanao_ndvi_sample.csv'),
Path('day4/data/mindanao_ndvi_sample.csv'),
Path('mindanao_ndvi_sample.csv')]:
if candidate.exists():
print(f'Loaded cached sample: {candidate}')
return pd.read_csv(candidate)
print(f'Downloading cached sample: {SAMPLE_URL}')
return pd.read_csv(SAMPLE_URL)
ndvi_df = None
if USE_EARTH_ENGINE:
try:
ndvi_df = fetch_monthly_ndvi(REGIONS, START_DATE, END_DATE)
ndvi_df.to_csv('mindanao_ndvi_gee.csv', index=False)
print(f'Fetched {len(ndvi_df)} months from Earth Engine (saved to mindanao_ndvi_gee.csv)')
except NotImplementedError as exc:
print(f'{exc}')
except Exception as exc:
print(f'Earth Engine fetch failed ({exc}); using the cached sample.')
if ndvi_df is None:
ndvi_df = load_cached_sample()
ndvi_df['month'] = pd.to_datetime(ndvi_df['month'])
locations = [col for col in ndvi_df.columns if col.startswith('NDVI_')]
print(f'{len(ndvi_df)} months: {ndvi_df.month.min():%Y-%m} to {ndvi_df.month.max():%Y-%m} | series: {locations}')
ndvi_df.head()Part 6 · Explore the NDVI series
Plot both provinces on one chart with a horizontal line at NDVI = 0.40, the illustrative drought threshold used in this lab. Then answer: which months and years dip lowest, and do the two provinces behave the same way?
Expected output: one line chart, two series, values roughly between 0.25 and 0.70.
fig, ax = plt.subplots(figsize=(10, 5))
for column in locations:
ax.plot(ndvi_df['month'], ndvi_df[column], marker='o', markersize=3, label=column.replace('NDVI_', ''))
ax.axhline(0.4, color='red', linestyle='--', linewidth=1, label='NDVI 0.40 (illustrative drought threshold)')
ax.set_title('Monthly mean NDVI: Bukidnon vs South Cotabato')
ax.set_ylabel('NDVI')
ax.set_xlabel('Month')
ax.legend(loc='lower right')
plt.tight_layout()
plt.show()Part 7 · Seasonal statistics
For each province compute: mean NDVI for November-April and for May-October, and the lowest NDVI with its month.
Note: Mindanao’s rainfall regime differs between provinces (PAGASA’s climate types III and IV), so there is no single “dry season” for the island. The two six-month halves here are just a simple way to compare seasons; check PAGASA’s climatology for your own area.
Expected output: a 2-row table with columns location, mean_nov_apr, mean_may_oct, lowest_ndvi, lowest_month.
nov_apr = [11, 12, 1, 2, 3, 4]
may_oct = [5, 6, 7, 8, 9, 10]
summary_rows = []
for column in locations:
month_num = ndvi_df['month'].dt.month
min_idx = ndvi_df[column].idxmin()
summary_rows.append({
'location': column.replace('NDVI_', ''),
'mean_nov_apr': round(ndvi_df.loc[month_num.isin(nov_apr), column].mean(), 3),
'mean_may_oct': round(ndvi_df.loc[month_num.isin(may_oct), column].mean(), 3),
'lowest_ndvi': round(ndvi_df.loc[min_idx, column], 3),
'lowest_month': ndvi_df.loc[min_idx, 'month'].strftime('%Y-%m'),
})
summary_df = pd.DataFrame(summary_rows)
summary_dfPart 8 · Build sliding-window sequences
For each province, every sample uses the previous 12 months of NDVI (LOOKBACK) to predict the NDVI 1 month later (HORIZON). Store location, target_month, sequence (a NumPy array of 12 values) and target in sequence_df.
Expected output (cached sample): 120 samples (60 per province).
LOOKBACK = 12 # months of history
HORIZON = 1 # predict 1 month ahead
records = []
for column in locations:
values = ndvi_df[column].values.astype(np.float32)
months = ndvi_df['month'].values
for idx in range(LOOKBACK, len(values) - HORIZON + 1):
records.append({
'location': column,
'target_month': months[idx + HORIZON - 1],
'sequence': values[idx - LOOKBACK:idx],
'target': values[idx + HORIZON - 1],
})
sequence_df = pd.DataFrame(records)
print(f'{len(sequence_df)} samples')
sequence_df.head()Part 9 · Temporal train / validation / test split
Never shuffle time series before splitting: the model must be tested on months that come after everything it was trained on. We use the last year as test, the year before as validation and everything earlier for training (with the cached sample: train 2019-2021, validation 2022, test 2023).
Expected output (cached sample): 72 train, 24 validation, 24 test samples.
last_year = ndvi_df['month'].dt.year.max()
train_end = pd.Timestamp(f'{last_year - 2}-12-31')
val_end = pd.Timestamp(f'{last_year - 1}-12-31')
train_mask = sequence_df['target_month'] <= train_end
val_mask = (sequence_df['target_month'] > train_end) & (sequence_df['target_month'] <= val_end)
test_mask = sequence_df['target_month'] > val_end
print(f'Train: {train_mask.sum()} samples (targets up to {train_end:%Y-%m})')
print(f'Validation: {val_mask.sum()} samples ({last_year - 1})')
print(f'Test: {test_mask.sum()} samples ({last_year})')Part 10 · Scale with the training period only
Min-max scale NDVI to [0, 1] using the minimum and maximum of the training months only; using all data would leak information about the test period into training. Then stack the sequences into arrays of shape (samples, 12, 1) for the LSTM.
Expected output (cached sample): shapes (72, 12, 1), (24, 12, 1), (24, 12, 1).
train_values = ndvi_df.loc[ndvi_df['month'] <= train_end, locations].values.flatten()
ndvi_min, ndvi_max = float(train_values.min()), float(train_values.max())
print(f'Training NDVI range: {ndvi_min:.3f} to {ndvi_max:.3f}')
def scale(arr):
return (arr - ndvi_min) / (ndvi_max - ndvi_min)
def invert(arr):
return arr * (ndvi_max - ndvi_min) + ndvi_min
def stack_split(mask):
X = np.stack(sequence_df.loc[mask, 'sequence'].values)
y = sequence_df.loc[mask, 'target'].values.astype(np.float32)
dates = sequence_df.loc[mask, 'target_month'].values
locs = sequence_df.loc[mask, 'location'].values
return scale(X)[:, :, None].astype(np.float32), scale(y)[:, None].astype(np.float32), dates, locs
X_train, y_train, dates_train, locs_train = stack_split(train_mask)
X_val, y_val, dates_val, locs_val = stack_split(val_mask)
X_test, y_test, dates_test, locs_test = stack_split(test_mask)
print(X_train.shape, X_val.shape, X_test.shape)Part 11 · PyTorch Dataset and DataLoader
A Dataset returns one (sequence, target) pair; a DataLoader batches them. Shuffling the training windows is fine (each window already contains its own history); the split itself stays temporal.
class SequenceDataset(Dataset):
def __init__(self, features, targets):
self.features = torch.tensor(features, dtype=torch.float32)
self.targets = torch.tensor(targets, dtype=torch.float32)
def __len__(self):
return len(self.features)
def __getitem__(self, idx):
return self.features[idx], self.targets[idx]
BATCH_SIZE = 16
generator = torch.Generator().manual_seed(SEED) # reproducible shuffling
train_loader = DataLoader(SequenceDataset(X_train, y_train), batch_size=BATCH_SIZE, shuffle=True, generator=generator)
val_loader = DataLoader(SequenceDataset(X_val, y_val), batch_size=BATCH_SIZE, shuffle=False)
print(f'{len(train_loader.dataset)} training and {len(val_loader.dataset)} validation samples')Part 12 · Define the LSTM forecaster
Same design as the Keras model in Session 1: LSTM (64 units) → dropout → LSTM (32 units) → dropout → dense (16, ReLU) → 1 output.
Expected output: the model printout and about 30,000 trainable parameters.
class NDVIForecaster(nn.Module):
def __init__(self, input_size=1, hidden_sizes=(64, 32), dropout=0.2):
super().__init__()
self.lstm1 = nn.LSTM(input_size, hidden_sizes[0], batch_first=True)
self.lstm2 = nn.LSTM(hidden_sizes[0], hidden_sizes[1], batch_first=True)
self.dropout = nn.Dropout(dropout)
self.head = nn.Sequential(nn.Linear(hidden_sizes[1], 16), nn.ReLU(), nn.Linear(16, 1))
def forward(self, x):
out, _ = self.lstm1(x)
out, _ = self.lstm2(self.dropout(out))
last = self.dropout(out[:, -1, :]) # hidden state at the last time step
return self.head(last)
model = NDVIForecaster().to(device)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
print(model)
print(f'Trainable parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad):,}')Part 13 · Training loop with early stopping
Train for up to EPOCHS epochs, track train/validation MSE and MAE, and keep the weights from the epoch with the lowest validation loss (early stopping with PATIENCE epochs).
Expected output: a log line every 10 epochs; validation MAE falls to a few hundredths (scaled units).
import copy
def run_epoch(data_loader, model, criterion, optimizer=None):
"""One pass over data_loader. Trains if an optimizer is given, otherwise evaluates. Returns (mean MSE, mean MAE)."""
model.train() if optimizer else model.eval()
total_loss, total_mae = 0.0, 0.0
for features, targets in data_loader:
features, targets = features.to(device), targets.to(device)
if optimizer:
optimizer.zero_grad()
outputs = model(features)
loss = criterion(outputs, targets)
if optimizer:
loss.backward()
optimizer.step()
n = features.size(0)
total_loss += loss.item() * n
total_mae += torch.mean(torch.abs(outputs - targets)).item() * n
size = len(data_loader.dataset)
return total_loss / size, total_mae / size
EPOCHS = 150
PATIENCE = 20
history = {'epoch': [], 'train_loss': [], 'val_loss': [], 'train_mae': [], 'val_mae': []}
best_val, best_state, epochs_without_improvement = float('inf'), None, 0
for epoch in range(1, EPOCHS + 1):
train_loss, train_mae = run_epoch(train_loader, model, criterion, optimizer)
with torch.no_grad():
val_loss, val_mae = run_epoch(val_loader, model, criterion)
for key, value in zip(history, (epoch, train_loss, val_loss, train_mae, val_mae)):
history[key].append(value)
if val_loss < best_val:
best_val, best_state, epochs_without_improvement = val_loss, copy.deepcopy(model.state_dict()), 0
else:
epochs_without_improvement += 1
if epoch % 10 == 0 or epoch == 1:
print(f'Epoch {epoch:03d} | train_loss={train_loss:.4f} val_loss={val_loss:.4f} val_mae={val_mae:.4f}')
if epochs_without_improvement >= PATIENCE:
print(f'Early stopping at epoch {epoch}')
break
model.load_state_dict(best_state)
print(f'Best validation MSE: {best_val:.4f} (epoch {history["val_loss"].index(best_val) + 1})')Part 14 · Learning curves
Plot train vs validation MSE and MAE per epoch. A validation curve that rises while the training curve keeps falling means overfitting.
history_df = pd.DataFrame(history)
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
for ax, metric, label in [(axes[0], 'loss', 'MSE'), (axes[1], 'mae', 'MAE')]:
ax.plot(history_df['epoch'], history_df[f'train_{metric}'], label=f'Train {label}')
ax.plot(history_df['epoch'], history_df[f'val_{metric}'], label=f'Validation {label}')
ax.set_xlabel('Epoch')
ax.set_ylabel(f'{label} (scaled NDVI)')
ax.set_title(label)
ax.legend()
plt.tight_layout()
plt.show()Part 15 · Evaluate on the held-out test year
- Predict the test year, convert back to NDVI with
invert()and buildresults_df. - Compute MAE and RMSE, and compare with two baselines that any forecast must beat:
- persistence: next month = this month
- seasonal naive: next month = same month last year
Expected output: a table of MAE/RMSE for the LSTM and both baselines (NDVI units), then one plot per province. On the small cached sample the LSTM should roughly match or beat persistence; if it does not, discuss why (only 72 training samples).
model.eval()
with torch.no_grad():
y_test_pred = model(torch.tensor(X_test, device=device)).cpu().numpy().squeeze()
results_df = pd.DataFrame({
'target_month': pd.to_datetime(dates_test),
'location': [loc.replace('NDVI_', '') for loc in locs_test],
'actual_ndvi': invert(y_test.squeeze()),
'predicted_ndvi': invert(y_test_pred),
'persistence_ndvi': invert(X_test[:, -1, 0]), # last observed month
'seasonal_ndvi': invert(X_test[:, -LOOKBACK + HORIZON - 1, 0]), # same month one year earlier
}).sort_values(['location', 'target_month']).reset_index(drop=True)
results_df.head()def mae(a, b):
return float(np.mean(np.abs(a - b)))
def rmse(a, b):
return float(np.sqrt(np.mean((a - b) ** 2)))
metrics = pd.DataFrame([
{'forecast': name, 'MAE': mae(results_df[col], results_df['actual_ndvi']),
'RMSE': rmse(results_df[col], results_df['actual_ndvi'])}
for name, col in [('LSTM', 'predicted_ndvi'), ('Persistence', 'persistence_ndvi'),
('Seasonal naive', 'seasonal_ndvi')]
]).round(3)
metricsfig, axes = plt.subplots(1, results_df['location'].nunique(), figsize=(13, 4), sharey=True)
for ax, (location, group) in zip(np.atleast_1d(axes), results_df.groupby('location')):
ax.plot(group['target_month'], group['actual_ndvi'], marker='o', label='Actual')
ax.plot(group['target_month'], group['predicted_ndvi'], marker='x', linestyle='--', label='LSTM forecast')
ax.plot(group['target_month'], group['persistence_ndvi'], color='grey', alpha=0.6, linestyle=':', label='Persistence')
ax.axhline(0.4, color='red', linestyle='--', linewidth=1, label='NDVI 0.40')
ax.set_title(f'{location}: test-year NDVI, 1-month-ahead forecast')
ax.set_xlabel('Month')
ax.tick_params(axis='x', rotation=45)
np.atleast_1d(axes)[0].set_ylabel('NDVI')
np.atleast_1d(axes)[0].legend(loc='best')
plt.tight_layout()
plt.show()Part 16 · From forecasts to drought alerts
Flag a month as “drought” when NDVI < 0.40 (an illustrative threshold for this lab, not an official PAGASA or DA criterion; operational systems use anomalies relative to each place’s own normal, for example a vegetation condition index). Compare predicted vs actual flags with a confusion matrix, precision and recall.
Expected output: a 2×2 confusion table and precision/recall. A single test year may contain few or no drought months: if so, precision/recall are undefined, which is itself a lesson about evaluating rare events.
DROUGHT_THRESHOLD = 0.40
results_df['actual_drought'] = results_df['actual_ndvi'] < DROUGHT_THRESHOLD
results_df['predicted_drought'] = results_df['predicted_ndvi'] < DROUGHT_THRESHOLD
confusion = pd.crosstab(results_df['actual_drought'], results_df['predicted_drought'],
rownames=['actual drought'], colnames=['predicted drought'], dropna=False)
print(confusion, '\n')
tp = int((results_df['actual_drought'] & results_df['predicted_drought']).sum())
fp = int((~results_df['actual_drought'] & results_df['predicted_drought']).sum())
fn = int((results_df['actual_drought'] & ~results_df['predicted_drought']).sum())
precision = tp / (tp + fp) if (tp + fp) else float('nan')
recall = tp / (tp + fn) if (tp + fn) else float('nan')
print(f'Drought months in test year: {tp + fn} actual, {tp + fp} predicted')
print(f'Precision: {precision:.2f} | Recall: {recall:.2f} (nan = undefined: no positive cases)')Recap and reflection
What you did: monthly Sentinel-2 NDVI → 12-month sliding windows → temporal split and leakage-free scaling → two-layer PyTorch LSTM with early stopping → comparison with persistence and seasonal baselines → drought alerts with precision/recall.
Reflect: 1. Did the LSTM beat the persistence baseline? What does that tell you about how much there is to learn from 72 training samples? 2. How would the results change with administrative boundaries and a cropland mask instead of bounding boxes? 3. Which covariates would you add next (rainfall, ONI / El Niño index, soil moisture, Sentinel-1 backscatter), and how would you align them in time? 4. Why is an NDVI anomaly (relative to each month’s normal) a better drought signal than a fixed 0.40 threshold?
Next: Session 3 looks at foundation models and embeddings, which can supply better features for exactly this kind of small-data problem, and at XAI methods (for example Integrated Gradients) to see which past months drive a forecast.
Teaching notes
- Demonstrate
USE_EARTH_ENGINE = Trueonce (live fetch for two provinces and seven years takes a few minutes); otherwise stay on the cached sample. - Typical discussion: with so few samples, persistence is a strong baseline. Use it to discuss data quantity, pooling more locations (municipalities, pixels) and adding covariates.
- Extensions: add rainfall/ONI as extra input features (
input_size > 1), predict 3 months ahead (HORIZON = 3), forecast NDVI anomalies instead of raw NDVI, or apply Integrated Gradients (Captum) to the trained LSTM.