import sys, subprocess
IN_COLAB = "google.colab" in sys.modules
if IN_COLAB:
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "rasterio"], check=True)Day 3 · Session 2 — Flood Mapping with a PyTorch U-Net on Sentinel-1 SAR
EO AI/ML Training — Dimitrios Kasampalis (Anefelo) · CC BY-SA 4.0
Flood mapping is one of the most valuable things Sentinel-1 radar does: it sees through the clouds that cover the Philippines during every typhoon. In this lab you train a U-Net (Session 1) to segment surface water in Sentinel-1 VV/VH backscatter, evaluate it honestly on flood events it has never seen, compare it with classic SAR thresholding, and export a georeferenced flood map.
Learning objectives
By the end of this notebook you will be able to: 1. Download and inspect labelled Sentinel-1 flood chips (dB backscatter, nodata, label conventions). 2. Prepare SAR data for deep learning: fixed dB scaling, tiling, nodata masking, event-based train/val/test split. 3. Build a U-Net in PyTorch and train it with a combined BCE + Dice loss. 4. Evaluate with IoU, precision, recall and F1 — and compare against a VV threshold baseline. 5. Export a prediction as a GeoTIFF for QGIS/ArcGIS.
What you’ll need
| Runtime | Google Colab with a GPU (Runtime → Change runtime type → T4 GPU). Also runs on CPU / Apple-silicon (MPS) with fewer chips and epochs. |
| Data | Cloud to Street – Microsoft Flood Dataset (C2S-MS Floods, CC BY 4.0): 900 labelled Sentinel-1 chips (512×512 px, 10 m) from 18 flood events, 2016–2020. The notebook downloads a subset (default 90 chips ≈ 300 MB) from the open AWS bucket — no account or API key. |
| Time | ~5 min download + ~10–15 min training on a T4 GPU with the defaults. |
About the data and the Philippines. C2S-MS Floods contains no Philippine event. That is deliberate here: we test the model on held-out events, which is exactly the situation you face when applying it to a new typhoon such as Ulysses (Vamco, November 2020) in Central Luzon. Section 9 discusses that transfer.
1. Setup
On Colab, PyTorch is pre-installed; we only add rasterio for reading GeoTIFFs. Locally, install the packages from the course requirements.txt.
import os, random, re, time, urllib.request, urllib.parse
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import matplotlib.pyplot as plt
import rasterio
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
SEED = 42
random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED)
if torch.cuda.is_available():
device = torch.device("cuda")
elif torch.backends.mps.is_available():
device = torch.device("mps") # Apple silicon
else:
device = torch.device("cpu")
print("PyTorch", torch.__version__, "| rasterio", rasterio.__version__, "| device:", device)Configuration
Change these to trade speed for accuracy. More chips and epochs give better results; on CPU use e.g. N_CHIPS = 36, NUM_EPOCHS = 3.
DATA_DIR = Path("c2s_floods") # local folder for the downloaded chips
N_CHIPS = 90 # chips to download (5 per event x 18 events). Max 900.
NUM_EPOCHS = 15
BATCH_SIZE = 8
LR = 1e-3
TILE = 256 # each 512x512 chip becomes four 256x256 tiles
NUM_WORKERS = 2 if IN_COLAB else 0 # >0 workers need 'fork' (Linux); keep 0 on macOS/Windows notebooks2. Download a subset of C2S-MS Floods
The dataset lives in the public S3 bucket radiant-mlhub (AWS Open Data Registry: https://registry.opendata.aws/c2smsfloods/). It is organised as c2smsfloods/chips/<event-id>/s1/<chip-id>/{VV.tif, VH.tif, LabelWater.tif}. We list it over plain HTTPS (no AWS CLI needed) and download the same number of chips from every event, with a fixed seed so everyone gets the same subset.
BUCKET_URL = "https://radiant-mlhub.s3.us-west-2.amazonaws.com"
PREFIX = "c2smsfloods/chips/"
FILES = ["VV.tif", "VH.tif", "LabelWater.tif"]
def s3_list_prefixes(prefix):
# List the 'sub-folders' under a prefix of the public bucket (S3 ListObjectsV2 over HTTPS)
out, token = [], None
while True:
q = {"list-type": "2", "prefix": prefix, "delimiter": "/"}
if token:
q["continuation-token"] = token
xml = urllib.request.urlopen(f"{BUCKET_URL}/?{urllib.parse.urlencode(q)}", timeout=60).read().decode()
out += re.findall(r"<CommonPrefixes><Prefix>([^<]+)</Prefix>", xml)
nxt = re.search(r"<NextContinuationToken>([^<]+)</NextContinuationToken>", xml)
if not nxt:
return out
token = nxt.group(1)
def download_subset(out_dir, n_chips, seed=SEED):
events = s3_list_prefixes(PREFIX)
chips_by_event = {e: sorted(s3_list_prefixes(e + "s1/")) for e in events}
print(f"{len(events)} flood events, {sum(map(len, chips_by_event.values()))} Sentinel-1 chips available")
rng = random.Random(seed)
per_event = max(1, n_chips // len(events))
selected = []
for e in sorted(chips_by_event):
selected += rng.sample(chips_by_event[e], min(per_event, len(chips_by_event[e])))
def fetch(chip_prefix):
event_id = chip_prefix.split("/")[2][:8] # short event id
chip_id = chip_prefix.rstrip("/").split("/")[-1]
dest = Path(out_dir) / f"{event_id}_{chip_id}"
dest.mkdir(parents=True, exist_ok=True)
for f in FILES:
if not (dest / f).exists():
urllib.request.urlretrieve(f"{BUCKET_URL}/{chip_prefix}{f}", dest / f)
return dest
t0 = time.time()
with ThreadPoolExecutor(max_workers=8) as pool:
dirs = list(pool.map(fetch, selected))
print(f"{len(dirs)} chips ready in {DATA_DIR} ({time.time() - t0:.0f} s)")
return sorted(dirs)
chip_dirs = download_subset(DATA_DIR, N_CHIPS)3. Inspect the data
Always look before you train. Check the data type, value range (are these dB or linear?), nodata values and label codes.
example = chip_dirs[1]
for name in FILES:
with rasterio.open(example / name) as src:
a = src.read(1)
print(f"{name:15s} dtype={a.dtype} shape={a.shape} nodata={src.nodata} CRS={src.crs} "
f"min={a.min():.2f} max={a.max():.2f} unique={np.unique(a)[:5] if a.dtype == np.uint8 else '-'}")What you should see: VV/VH are float32 backscatter in dB (typically −30 to 0 dB; water is dark, around −20 dB and below in VV), with nodata = 0. LabelWater is uint8 with 0 = no water, 1 = water, 255 = nodata. Each chip is in its local UTM projection at 10 m.
We therefore (1) scale dB with fixed ranges, the same for every chip, so that “dark” means the same thing everywhere (per-tile min–max stretching would make a fully flooded tile look like a dry one), and (2) ignore nodata pixels in the loss and metrics.
VV_RANGE = (-30.0, 5.0) # dB range mapped to [0, 1]
VH_RANGE = (-40.0, -5.0)
def scale_db(a, lo, hi):
return np.clip((a - lo) / (hi - lo), 0.0, 1.0).astype(np.float32)
def load_chip(chip_dir):
# Returns image [2,H,W] in [0,1], label [H,W] in {0,1}, valid mask [H,W] (bool)
with rasterio.open(chip_dir / "VV.tif") as s: vv = s.read(1)
with rasterio.open(chip_dir / "VH.tif") as s: vh = s.read(1)
with rasterio.open(chip_dir / "LabelWater.tif") as s: lab = s.read(1)
valid = (lab != 255) & (vv != 0) & (vh != 0) & np.isfinite(vv) & np.isfinite(vh)
img = np.stack([scale_db(vv, *VV_RANGE), scale_db(vh, *VH_RANGE)])
img[:, ~valid] = 0.0
return img, np.where(valid, lab, 0).astype(np.float32), valid
fig, axes = plt.subplots(3, 3, figsize=(10, 10))
for row, d in enumerate(chip_dirs[:3]):
img, lab, valid = load_chip(d)
axes[row, 0].imshow(img[0], cmap="gray"); axes[row, 0].set_title("VV (scaled)")
axes[row, 1].imshow(img[1], cmap="gray"); axes[row, 1].set_title("VH (scaled)")
axes[row, 2].imshow(np.where(valid, lab, np.nan), cmap="Blues", vmin=0, vmax=1)
axes[row, 2].set_title(f"Water label ({lab[valid].mean():.0%} water)")
for ax in axes[row]: ax.axis("off")
plt.suptitle("Sentinel-1 chips and hand-labelled water masks (white = nodata)")
plt.tight_layout(); plt.show()4. Event-based split, tiling and the PyTorch Dataset
Chips from the same flood event share the same scene, date and landscape. If we split chips randomly, test chips would be near-copies of training chips and the score would be optimistic. We split by event: the test events are never seen during training — just like a new typhoon would be.
events = sorted({d.name.split("_")[0] for d in chip_dirs})
rng = random.Random(SEED)
rng.shuffle(events)
n_test, n_val = max(1, round(0.15 * len(events))), max(1, round(0.10 * len(events)))
test_events, val_events = set(events[:n_test]), set(events[n_test:n_test + n_val])
def split_of(d):
e = d.name.split("_")[0]
return "test" if e in test_events else "val" if e in val_events else "train"
splits = {s: [d for d in chip_dirs if split_of(d) == s] for s in ["train", "val", "test"]}
for s, ds in splits.items():
print(f"{s:5s}: {len(ds):3d} chips from {len({d.name.split('_')[0] for d in ds})} events")class FloodTiles(Dataset):
# Loads chips once, cuts each 512x512 chip into 256x256 tiles, optional flip/rotate augmentation
def __init__(self, chip_dirs, tile=TILE, augment=False):
self.tiles = []
for d in chip_dirs:
img, lab, valid = load_chip(d)
H, W = lab.shape
for y in range(0, H - tile + 1, tile):
for x in range(0, W - tile + 1, tile):
v = valid[y:y + tile, x:x + tile]
if v.mean() < 0.5: # skip tiles that are mostly nodata
continue
self.tiles.append((img[:, y:y + tile, x:x + tile],
lab[None, y:y + tile, x:x + tile],
v[None].astype(np.float32), f"{d.name[:8]}_{y}_{x}"))
self.augment = augment
def __len__(self):
return len(self.tiles)
def __getitem__(self, i):
img, lab, valid, _ = self.tiles[i]
img, lab, valid = map(torch.from_numpy, (img.copy(), lab.copy(), valid.copy()))
if self.augment: # identical transform for image, label and mask
k = random.randint(0, 3)
img, lab, valid = (torch.rot90(t, k, dims=(1, 2)) for t in (img, lab, valid))
if random.random() < 0.5:
img, lab, valid = (torch.flip(t, dims=(2,)) for t in (img, lab, valid))
return img, lab, valid
train_ds = FloodTiles(splits["train"], augment=True)
val_ds = FloodTiles(splits["val"])
test_ds = FloodTiles(splits["test"])
print(f"Tiles - train: {len(train_ds)}, val: {len(val_ds)}, test: {len(test_ds)}")
water_frac = np.mean([t[1][t[2] > 0].mean() for t in train_ds.tiles])
print(f"Average water fraction per training tile: {water_frac:.1%} (class imbalance!)")
g = torch.Generator().manual_seed(SEED)
train_loader = DataLoader(train_ds, batch_size=BATCH_SIZE, shuffle=True, num_workers=NUM_WORKERS, generator=g)
val_loader = DataLoader(val_ds, batch_size=BATCH_SIZE, shuffle=False, num_workers=NUM_WORKERS)
test_loader = DataLoader(test_ds, batch_size=BATCH_SIZE, shuffle=False, num_workers=NUM_WORKERS)
images, labels, valid = next(iter(train_loader))
print("Batch:", tuple(images.shape), tuple(labels.shape), tuple(valid.shape)) # (B,2,256,256) (B,1,256,256) (B,1,256,256)5. The U-Net
Encoder (4 down-sampling steps) → bottleneck → decoder (4 up-sampling steps) with skip connections that concatenate encoder features into the decoder, recovering the fine spatial detail needed for sharp water edges.
class DoubleConv(nn.Module):
# (3x3 conv -> BatchNorm -> ReLU) x 2
def __init__(self, in_ch, out_ch):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, padding=1), nn.BatchNorm2d(out_ch), nn.ReLU(inplace=True),
nn.Conv2d(out_ch, out_ch, 3, padding=1), nn.BatchNorm2d(out_ch), nn.ReLU(inplace=True))
def forward(self, x):
return self.net(x)
class Down(nn.Module):
# MaxPool (halve resolution) then DoubleConv
def __init__(self, in_ch, out_ch):
super().__init__()
self.net = nn.Sequential(nn.MaxPool2d(2), DoubleConv(in_ch, out_ch))
def forward(self, x):
return self.net(x)
class Up(nn.Module):
# Transposed conv (double resolution), concatenate skip connection, DoubleConv
def __init__(self, in_ch, out_ch):
super().__init__()
self.up = nn.ConvTranspose2d(in_ch, in_ch // 2, kernel_size=2, stride=2)
self.conv = DoubleConv(in_ch // 2 + out_ch, out_ch)
def forward(self, x, skip):
x = self.up(x)
dy, dx = skip.size(2) - x.size(2), skip.size(3) - x.size(3)
if dy or dx: # pad if the input size was not divisible by 16
x = F.pad(x, [dx // 2, dx - dx // 2, dy // 2, dy - dy // 2])
return self.conv(torch.cat([skip, x], dim=1))
class UNet(nn.Module):
def __init__(self, n_channels=2, n_classes=1, base=32):
super().__init__()
c = [base, base * 2, base * 4, base * 8, base * 16]
self.inc = DoubleConv(n_channels, c[0])
self.down1, self.down2 = Down(c[0], c[1]), Down(c[1], c[2])
self.down3, self.down4 = Down(c[2], c[3]), Down(c[3], c[4])
self.up1, self.up2 = Up(c[4], c[3]), Up(c[3], c[2])
self.up3, self.up4 = Up(c[2], c[1]), Up(c[1], c[0])
self.outc = nn.Conv2d(c[0], n_classes, kernel_size=1)
def forward(self, x):
x1 = self.inc(x); x2 = self.down1(x1); x3 = self.down2(x2); x4 = self.down3(x3); x5 = self.down4(x4)
x = self.up1(x5, x4); x = self.up2(x, x3); x = self.up3(x, x2); x = self.up4(x, x1)
return self.outc(x) # logits; apply sigmoid for probabilities
model = UNet(n_channels=2, n_classes=1, base=32).to(device)
print(f"U-Net parameters: {sum(p.numel() for p in model.parameters()):,}")
with torch.no_grad():
print("Output shape:", tuple(model(images[:2].to(device)).shape))base=32 gives ~7.8 M parameters (the original U-Net uses base=64, ~31 M) — plenty for two input bands and quick to train on Colab.
6. Loss, metrics and training
Water is a minority class, so plain binary cross-entropy (BCE) can settle on “predict dry everywhere”. We combine BCE (stable per-pixel gradients) with Dice loss (directly rewards overlap with the water class), and we mask out nodata pixels in both. We track IoU of the water class on the validation events and keep the best epoch.
def masked_bce_dice(logits, target, valid, smooth=1.0):
bce = F.binary_cross_entropy_with_logits(logits, target, weight=valid, reduction="sum") / valid.sum().clamp(min=1)
prob = torch.sigmoid(logits) * valid
inter = (prob * target).sum()
dice = (2 * inter + smooth) / (prob.sum() + (target * valid).sum() + smooth)
return 0.5 * bce + 0.5 * (1 - dice)
def confusion(pred, target, valid):
# pixel counts (TP, FP, FN, TN) over valid pixels; pred and target are 0/1 tensors
v = valid.bool()
p, t = pred.bool() & v, target.bool() & v
tp = (p & t).sum().item(); fp = (p & ~t).sum().item(); fn = (~p & t & v).sum().item()
tn = v.sum().item() - tp - fp - fn
return np.array([tp, fp, fn, tn], dtype=np.int64)
def scores(c):
tp, fp, fn, tn = c
iou = tp / max(tp + fp + fn, 1); prec = tp / max(tp + fp, 1); rec = tp / max(tp + fn, 1)
return dict(IoU=iou, precision=prec, recall=rec, F1=2 * prec * rec / max(prec + rec, 1e-9),
accuracy=(tp + tn) / max(tp + fp + fn + tn, 1))
@torch.no_grad()
def evaluate(model, loader, threshold=0.5):
model.eval()
total, conf = 0.0, np.zeros(4, dtype=np.int64)
for img, lab, val in loader:
img, lab, val = img.to(device), lab.to(device), val.to(device)
logits = model(img)
total += masked_bce_dice(logits, lab, val).item() * img.size(0)
conf += confusion((torch.sigmoid(logits) >= threshold).float(), lab, val)
return total / len(loader.dataset), scores(conf)optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=NUM_EPOCHS)
history = {"train_loss": [], "val_loss": [], "val_iou": []}
best_iou, best_path = -1.0, Path("unet_c2s_best.pt")
for epoch in range(1, NUM_EPOCHS + 1):
model.train(); t0 = time.time(); running = 0.0
for img, lab, val in train_loader:
img, lab, val = img.to(device), lab.to(device), val.to(device)
optimizer.zero_grad()
loss = masked_bce_dice(model(img), lab, val)
loss.backward()
optimizer.step()
running += loss.item() * img.size(0)
scheduler.step()
val_loss, val_scores = evaluate(model, val_loader)
history["train_loss"].append(running / len(train_ds))
history["val_loss"].append(val_loss)
history["val_iou"].append(val_scores["IoU"])
if val_scores["IoU"] > best_iou:
best_iou = val_scores["IoU"]
torch.save(model.state_dict(), best_path)
print(f"Epoch {epoch:2d}/{NUM_EPOCHS} train loss {history['train_loss'][-1]:.4f} "
f"val loss {val_loss:.4f} val IoU {val_scores['IoU']:.3f} ({time.time() - t0:.0f} s)")
print(f"Best validation IoU: {best_iou:.3f} (weights saved to {best_path})")epochs = range(1, len(history["train_loss"]) + 1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
ax1.plot(epochs, history["train_loss"], label="train"); ax1.plot(epochs, history["val_loss"], label="validation")
ax1.set_xlabel("Epoch"); ax1.set_ylabel("BCE + Dice loss"); ax1.set_title("Loss"); ax1.legend()
ax2.plot(epochs, history["val_iou"], marker="o", color="green")
ax2.set_xlabel("Epoch"); ax2.set_ylabel("Water IoU"); ax2.set_title("Validation IoU (unseen events)"); ax2.grid(True)
plt.tight_layout(); plt.show()7. Evaluate on the held-out test events — and against a classic baseline
Before deep learning, SAR flood mapping was (and operationally often still is) done by thresholding VV backscatter: smooth open water reflects the radar pulse away from the satellite, so it is dark. A fair evaluation asks: does the U-Net beat a simple threshold on the same unseen events?
model.load_state_dict(torch.load(best_path, map_location=device))
test_loss, unet_scores = evaluate(model, test_loader)
# Baseline: water where VV < -18 dB (a common starting threshold; tune it per scene in practice)
vv_thr = (-18.0 - VV_RANGE[0]) / (VV_RANGE[1] - VV_RANGE[0]) # same threshold in scaled units
conf = np.zeros(4, dtype=np.int64)
for img, lab, val in test_loader:
conf += confusion((img[:, :1] < vv_thr).float(), lab, val)
thr_scores = scores(conf)
print(f"{'metric':10s} {'U-Net':>8s} {'VV<-18dB':>9s}")
for k in unet_scores:
print(f"{k:10s} {unet_scores[k]:8.3f} {thr_scores[k]:9.3f}")Interpreting the numbers. IoU and F1 of the water class are the headline metrics; pixel accuracy is inflated because most pixels are dry. With the default settings expect a test water IoU in roughly the 0.5–0.75 range (it varies with which events land in the test split) and a U-Net that beats the single global threshold, mainly by reducing false alarms from radar shadow, smooth tarmac and dry sand. If your U-Net does not beat the threshold, train longer or on more chips.
@torch.no_grad()
def predict(img_tensor):
model.eval()
return torch.sigmoid(model(img_tensor[None].to(device)))[0, 0].cpu().numpy()
rng_vis = random.Random(1)
idx = rng_vis.sample(range(len(test_ds)), k=min(4, len(test_ds)))
fig, axes = plt.subplots(len(idx), 4, figsize=(14, 3.5 * len(idx)))
axes = np.atleast_2d(axes)
for r, i in enumerate(idx):
img, lab, val = test_ds[i]
prob = predict(img)
gt = np.where(val[0] > 0, lab[0], np.nan)
pr = np.where(val[0] > 0, prob >= 0.5, np.nan)
for ax, im, title, cmap in zip(axes[r], [img[0], img[1], gt, pr],
[f"VV ({test_ds.tiles[i][3]})", "VH", "Ground truth", "U-Net prediction"],
["gray", "gray", "Blues", "Blues"]):
ax.imshow(im, cmap=cmap, vmin=0, vmax=1); ax.set_title(title); ax.axis("off")
plt.suptitle("Test events: SAR input, reference water mask and prediction"); plt.tight_layout(); plt.show()8. Export a georeferenced flood map
The U-Net is fully convolutional, so it can predict on a whole 512×512 chip (any size divisible by 16). We write the water probability and binary mask as a GeoTIFF with the chip’s original CRS and geotransform — ready for QGIS.
chip = splits["test"][0]
img, lab, valid = load_chip(chip)
prob = predict(torch.from_numpy(img))
water = np.where(valid, (prob >= 0.5).astype(np.uint8), 255)
with rasterio.open(chip / "VV.tif") as src:
profile = src.profile.copy()
profile.update(count=1, dtype="uint8", nodata=255, compress="deflate")
out_tif = Path("flood_prediction.tif")
with rasterio.open(out_tif, "w", **profile) as dst:
dst.write(water, 1)
dst.set_band_description(1, "water (1) / no water (0) / nodata (255)")
print(f"Wrote {out_tif} | CRS {profile['crs']} | water pixels: {(water == 1).sum():,} "
f"= {(water == 1).sum() * 100 / 1e6:.2f} km² at 10 m")To vectorise the mask for a report or dashboard: rasterio.features.shapes(water, mask=water == 1, transform=profile["transform"]) → shapely polygons → geopandas.GeoDataFrame(..., crs=profile["crs"]).to_file("flood.gpkg").
9. Exercises
Exercise 1 — Precision vs recall (runnable). Run the cell below. Expected: lowering the threshold raises recall and lowers precision. For disaster response, missing a flooded village (false negative) usually costs more than a false alarm — which threshold would you choose?
for thr in [0.3, 0.5, 0.7]:
_, s = evaluate(model, test_loader, threshold=thr)
print(f"threshold {thr:.1f}: IoU {s['IoU']:.3f} precision {s['precision']:.3f} recall {s['recall']:.3f}")Exercise 2 — Does VH help? Train a model on VV only: set n_channels=1 and feed img[:, :1]. Expected: a slightly lower IoU; VH mostly helps separating flooded vegetation and wet soil from open water.
Exercise 3 — More data. Set N_CHIPS = 270 (15 per event) and NUM_EPOCHS = 25, re-run. Expected: higher and more stable test IoU — data quantity and diversity usually matter more than architecture tweaks.
Exercise 4 — Loss ablation. Replace masked_bce_dice by BCE only (0.5 * bce → bce, drop the Dice term). Expected: on tiles with little water the BCE-only model tends to under-predict water (lower recall).
Transfer to the Philippines (discussion). To map Typhoon Ulysses flooding in the Pampanga River Basin you would: export post-event Sentinel-1 GRD (VV, VH, dB) over the basin from Earth Engine (COPERNICUS/S1_GRD) or the Copernicus Data Space Ecosystem, tile it to 512×512, apply the same dB scaling, predict, and mosaic. Before trusting it, validate on a few hand-labelled Philippine tiles and, if needed, fine-tune with them. Mask permanent water (e.g. JRC Global Surface Water) to separate flood water from rivers and lakes.
10. Recap
- Sentinel-1 VV/VH in dB are scaled with fixed ranges; nodata is masked, not treated as dry land.
- Splitting by event gives an honest estimate of performance on a new flood.
- U-Net + BCE + Dice handles the water/dry imbalance; report IoU/F1 of the water class, not pixel accuracy.
- Always compare against a simple thresholding baseline.
- Predictions keep their georeference and go straight into GIS.
Data citation: Cloud to Street, Microsoft, Radiant Earth Foundation (2022). A global flood events and cloud cover dataset (Version 1.0). Radiant MLHub, https://doi.org/10.34911/rdnt.oz32gz — CC BY 4.0. Radiant MLHub has closed; the data is now hosted on AWS Open Data: https://registry.opendata.aws/c2smsfloods/