ted-downstream-eo / examples /openet_readout.py
ZiyunPOLYU's picture
Add downstream readout examples
d41b4f3 verified
Raw History Blame Contribute Delete
8.66 kB
#!/usr/bin/env python3
"""OpenET downstream readout on the files in this dataset.
The readout is the AlphaEarth OpenET trial, which TESSERA v2 also uses:
* official split, 3,000 train and 32,683 test
* 10 ET bins, column ``partition`` in ``regression/openet/sample_index.parquet``
* draws per bin: 1 point x 1000 repeats, 10 x 500, 300 x 1
* ordinary least squares with an intercept, no penalty and no feature scaling
* kNN regression at k=1 and k=3, uniform average of the neighbours
* the suite score is the best of those three readouts
* random seed 42
Two inputs are wired up:
* ``alphaearth``: annual 64-d embedding, ``regression/openet/alphaearth_annual_v1.npz``.
This is the public annual product. It is not the paper's time-conditioned
embedding. On the full 300-per-bin train split its linear R^2 is about -0.13.
* ``hls_year_mean``: mean of Blue..NDVI over the calendar-year 3-day cube,
``ready_3day/openet_fullband_3day.nc``
That cube is the label's calendar year, 122 steps. It is not the paper's
365.25-day support window ending at the target month, and it is not the
target month alone. Those two windows are the masks ``official_support_mask``
and ``valid_month_mask`` inside ``regression/openet/hls_l30.tar`` and
``hls_s30.tar``. The month window is where TESSERA v2 reports its 0.69.
python openet_readout.py --features alphaearth --shots 300
python openet_readout.py --features hls_year_mean --shots 300
"""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
REPO = "ZiyunPOLYU/ted-downstream-eo"
AEF_REPO = "regression/openet/alphaearth_annual_v1.npz"
INDEX_REPO = "regression/openet/sample_index.parquet"
CUBE_REPO = "ready_3day/openet_fullband_3day.nc"
COMMON = ("Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2", "NDVI")
def _local(path: str | None, repo_path: str) -> Path:
if path:
return Path(path)
from huggingface_hub import hf_hub_download
return Path(hf_hub_download(REPO, repo_path, repo_type="dataset"))
def _table(index_path: Path) -> pd.DataFrame:
frame = pd.read_parquet(
index_path,
columns=["sample_id", "source_idx", "label", "split", "partition", "year"],
)
frame = frame.sort_values("source_idx").reset_index(drop=True)
if len(frame) != 35683:
raise RuntimeError(f"Expected 35683 OpenET rows, got {len(frame)}")
if set(frame.split.astype(str)) != {"train", "test"}:
raise RuntimeError(f"Unexpected splits: {sorted(frame.split.unique())}")
return frame
def _align(sample_id: np.ndarray, frame: pd.DataFrame) -> np.ndarray:
order = pd.Series(np.arange(len(sample_id)), index=sample_id.astype(str))
return order.loc[frame.sample_id.astype(str)].to_numpy()
def load_alphaearth(path: Path, frame: pd.DataFrame) -> np.ndarray:
with np.load(path, allow_pickle=False) as payload:
take = _align(payload["sample_id"], frame)
embedding = np.asarray(payload["embedding"], dtype=np.float32)[take]
valid = np.asarray(payload["valid"], dtype=bool)[take]
embedding = embedding.copy()
embedding[~valid] = np.nan
return embedding
def load_hls_year_mean(path: Path, frame: pd.DataFrame) -> np.ndarray:
import netCDF4
with netCDF4.Dataset(path) as ds:
names = [str(item) for item in ds.variables["band"][:]]
columns = [names.index(name) for name in COMMON]
take = _align(np.asarray(ds.variables["sample_id"][:]).astype(str), frame)
cube = np.asarray(ds.variables["data"][:, columns, take], dtype=np.float32)
with np.errstate(all="ignore"):
return np.nanmean(cube, axis=0).T
def _metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict:
residual = y_pred - y_true
ss_res = float(np.sum(residual ** 2))
ss_tot = float(np.sum((y_true - float(y_true.mean())) ** 2))
r2 = float("nan") if ss_tot == 0 else 1.0 - ss_res / ss_tot
return {
"r2": r2,
"r2_chance_adjusted": max(0.0, r2) if np.isfinite(r2) else float("nan"),
"mae": float(np.mean(np.abs(residual))),
"rmse": float(np.sqrt(np.mean(residual ** 2))),
}
def _fit_predict(x_train, y_train, x_test, kind: str) -> np.ndarray:
if kind == "linear":
design = np.concatenate([x_train, np.ones((len(x_train), 1), dtype=np.float32)], axis=1)
coef, *_ = np.linalg.lstsq(design, y_train.astype(np.float64), rcond=None)
test = np.concatenate([x_test, np.ones((len(x_test), 1), dtype=np.float32)], axis=1)
return test.astype(np.float64) @ coef
k = 1 if kind == "knn1" else 3
train = np.ascontiguousarray(x_train, dtype=np.float32)
test = np.ascontiguousarray(x_test, dtype=np.float32)
train_sq = np.sum(train * train, axis=1, dtype=np.float32)
test_sq = np.sum(test * test, axis=1, dtype=np.float32)
pred = np.empty(len(test), dtype=np.float64)
for start in range(0, len(test), 4096):
stop = min(len(test), start + 4096)
distance = test_sq[start:stop, None] + train_sq[None, :] - 2.0 * (test[start:stop] @ train.T)
chosen = np.argpartition(distance, kth=k - 1, axis=1)[:, :k]
pred[start:stop] = y_train[chosen].mean(axis=1)
return pred
def _subsample(train_at: np.ndarray, partition: np.ndarray, samples_n: int, rng: np.random.Generator) -> np.ndarray:
chosen = []
for part in range(10):
pool = train_at[partition[train_at] == part]
take = samples_n if pool.size >= samples_n else int(pool.size)
if take == 0 or (take != samples_n and samples_n != 300):
raise RuntimeError(f"Partition {part} has {pool.size} train rows, need {samples_n}")
pick = pool if take == pool.size else rng.choice(pool, size=take, replace=False)
chosen.append(np.sort(pick))
return np.concatenate(chosen)
def score(name: str, embedding: np.ndarray, frame: pd.DataFrame, shots: list[int]) -> pd.DataFrame:
finite = np.isfinite(embedding).all(axis=1)
split = frame.split.astype(str).to_numpy()
label = frame.label.to_numpy(dtype=np.float64)
partition = frame.partition.to_numpy(dtype=np.int64)
train_at = np.flatnonzero((split == "train") & finite)
test_at = np.flatnonzero((split == "test") & finite)
rows = []
repeats = {1: 1000, 10: 500, 300: 1}
small = np.random.default_rng(42)
for samples_n in shots:
if samples_n == 300:
draws = [_subsample(train_at, partition, 300, np.random.default_rng(42))]
else:
draws = [_subsample(train_at, partition, samples_n, small) for _ in range(repeats[samples_n])]
for kind in ("linear", "knn1", "knn3"):
store = []
for subset in draws:
pred = _fit_predict(embedding[subset], label[subset], embedding[test_at], kind)
store.append(_metrics(label[test_at], pred))
summary = {key: float(np.mean([item[key] for item in store])) for key in store[0]}
summary["r2_std"] = float(np.std([item["r2"] for item in store], ddof=1)) if len(store) > 1 else 0.0
rows.append({
"model": name,
"readout": kind,
"samples_per_bin": samples_n,
"repeats": repeats[samples_n],
"n_train": int(len(draws[-1])),
"n_test": int(test_at.size),
**summary,
})
print(
f"{name} {kind} n={len(draws[-1])} R2={summary['r2']:.4f} MAE={summary['mae']:.2f}",
flush=True,
)
return pd.DataFrame(rows)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--features", choices=("alphaearth", "hls_year_mean"), default="alphaearth")
parser.add_argument("--shots", default="300")
parser.add_argument("--index", default="")
parser.add_argument("--alphaearth", default="")
parser.add_argument("--cube", default="")
parser.add_argument("--out", default="")
args = parser.parse_args()
frame = _table(_local(args.index or None, INDEX_REPO))
if args.features == "alphaearth":
embedding = load_alphaearth(_local(args.alphaearth or None, AEF_REPO), frame)
else:
embedding = load_hls_year_mean(_local(args.cube or None, CUBE_REPO), frame)
shots = [int(item) for item in args.shots.split(",") if item]
table = score(args.features, embedding, frame, shots)
if args.out:
destination = Path(args.out)
destination.parent.mkdir(parents=True, exist_ok=True)
table.to_csv(destination, index=False)
print(destination)
if __name__ == "__main__":
main()