Skip to main content

Day 4, Session 2: LSTM Drought Forecasting Lab (Student Notebook)

Forecasting monthly Sentinel-2 NDVI for Bukidnon and South Cotabato, Mindanao

Open In Colab

Learning objectives

By the end of this lab you will be able to:

  1. Retrieve a monthly Sentinel-2 NDVI time series for two Mindanao provinces with Google Earth Engine (or load the cached sample)
  2. Turn the series into supervised sliding-window samples (12 months in → next month out)
  3. Split the data by time (train / validation / test years) and scale it without leakage
  4. Build and train a two-layer LSTM in PyTorch, with early stopping
  5. 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

  1. Run the cells in order. Cells marked TODO need your code; they raise NotImplementedError until you complete them.
  2. Earth Engine is off by default (USE_EARTH_ENGINE = False), so the lab works offline with the cached sample. Implementing fetch_monthly_ndvi() (Part 4) is an optional stretch exercise.
  3. Each part states what output to expect, so you can check your work before moving on.

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).

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}')

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)."""
    # TODO (optional stretch exercise): implement with the Earth Engine Python API.
    # 1. Load ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED'), filter by date and CLOUDY_PIXEL_PERCENTAGE <= cloud_pct.
    # 2. Map a function that keeps SCL classes 4 (vegetation), 5 (bare soil) and 6 (water) and adds an NDVI band
    #    (image.normalizedDifference(['B8', 'B4']).rename('NDVI')).
    # 3. Optional: cropland mask = ee.ImageCollection('ESA/WorldCover/v200').first().eq(40).
    # 4. For each region (ee.Geometry.Rectangle(bbox)) and month: median composite -> reduceRegion(ee.Reducer.mean()).
    #    Hint: build an ee.FeatureCollection per region and year, then call .getInfo() once per request.
    # 5. Pivot to wide format (columns month, NDVI_Bukidnon, NDVI_SouthCotabato) and interpolate small gaps.
    raise NotImplementedError('fetch_monthly_ndvi() is a stretch exercise; the cached sample will be used.')

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.

# TODO: plot each column in `locations` against ndvi_df['month'] and add the 0.40 threshold line
#   fig, ax = plt.subplots(figsize=(10, 5))
#   for column in locations: ax.plot(...)
#   ax.axhline(0.4, ...); add a title, axis labels and a legend
raise NotImplementedError('Plot the NDVI series with the 0.40 threshold line.')

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]

# TODO: build summary_df with one row per province and the columns
#       location, mean_nov_apr, mean_may_oct, lowest_ndvi, lowest_month (format 'YYYY-MM')
# Hint: ndvi_df['month'].dt.month.isin(nov_apr) selects the Nov-Apr rows; Series.idxmin() finds the lowest row.
raise NotImplementedError('Create the seasonal summary table.')

Part 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

# TODO: loop over `locations`; for idx in range(LOOKBACK, len(values) - HORIZON + 1):
#         history = values[idx - LOOKBACK:idx]; target = values[idx + HORIZON - 1]; target_month = months[idx + HORIZON - 1]
#       collect dicts and build sequence_df = pd.DataFrame(records)
raise NotImplementedError('Create sequence_df from LOOKBACK/HORIZON.')

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')

# TODO: define boolean masks on sequence_df['target_month']:
#       train_mask (<= train_end), val_mask (between train_end and val_end), test_mask (> val_end)
#       and print the number of samples in each
raise NotImplementedError('Create the temporal train/val/test masks.')

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).

# TODO: compute ndvi_min / ndvi_max from ndvi_df rows with month <= train_end (all `locations` columns)
#       and define scale(arr) and invert(arr)
raise NotImplementedError('Derive scale()/invert() from the training NDVI range.')

# TODO: write stack_split(mask) returning X (samples, LOOKBACK, 1), y (samples, 1), dates, locations,
#       all scaled with scale(); then create X_train/y_train, X_val/y_val, X_test/y_test

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):
        # TODO: store features and targets as float32 tensors
        raise NotImplementedError

    def __len__(self):
        # TODO: return the number of samples
        raise NotImplementedError

    def __getitem__(self, idx):
        # TODO: return (features[idx], targets[idx])
        raise NotImplementedError

BATCH_SIZE = 16
# TODO: create train_loader (shuffle=True) and val_loader (shuffle=False)
raise NotImplementedError('Build the Dataset and DataLoaders.')

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__()
        # TODO: 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))
        raise NotImplementedError

    def forward(self, x):
        # TODO: run lstm1 -> dropout -> lstm2, take the LAST time step (out[:, -1, :]), apply dropout and the head
        raise NotImplementedError

# TODO: model = NDVIForecaster().to(device); criterion = nn.MSELoss(); optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
raise NotImplementedError('Instantiate the model, loss and optimizer.')

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).

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)."""
    # TODO: model.train() or model.eval(); loop over batches; move tensors to `device`;
    #       if training: zero_grad -> forward -> loss -> backward -> step; accumulate loss and MAE weighted by batch size
    raise NotImplementedError

EPOCHS = 150
PATIENCE = 20

# TODO: loop over epochs, call run_epoch for train and (inside torch.no_grad()) for validation,
#       append to history = {'epoch': [], 'train_loss': [], 'val_loss': [], 'train_mae': [], 'val_mae': []},
#       keep a copy of the best state_dict, stop after PATIENCE epochs without improvement, then reload the best weights
raise NotImplementedError('Train the model and record the history.')

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.

# TODO: history_df = pd.DataFrame(history); make a 1x2 figure with MSE (left) and MAE (right), train vs validation
raise NotImplementedError('Plot the learning curves.')

Part 15 · Evaluate on the held-out test year

  1. Predict the test year, convert back to NDVI with invert() and build results_df.
  2. 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).

# TODO: model.eval(); with torch.no_grad(): predict X_test; invert() predictions and y_test;
#       build results_df with columns target_month, location, actual_ndvi, predicted_ndvi
#       plus the baselines: persistence_ndvi = invert(X_test[:, -1, 0]), seasonal_ndvi = invert(X_test[:, -12, 0])
raise NotImplementedError('Predict the test year and build results_df.')
# TODO: for each forecast column (predicted_ndvi, persistence_ndvi, seasonal_ndvi) compute MAE and RMSE
#       against actual_ndvi and show them in a small DataFrame
raise NotImplementedError('Report MAE and RMSE for the LSTM and the baselines.')
# TODO: for each province plot actual vs LSTM forecast (and optionally the persistence baseline)
#       over the test year, with the 0.40 threshold line
raise NotImplementedError('Plot actual vs predicted NDVI per province.')

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

# TODO: add boolean columns actual_drought / predicted_drought to results_df,
#       print pd.crosstab(...) and compute precision = TP / (TP + FP) and recall = TP / (TP + FN)
#       (guard against division by zero)
raise NotImplementedError('Turn forecasts into drought alerts and score them.')

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.