Datasets:
Download examples/classification_cube.py from ZiyunPOLYU/ted-downstream-eo: direct link, hf CLI and curl.
- Browser
- Download file 3.62 kB
-
https://huggingface.co/datasets/ZiyunPOLYU/ted-downstream-eo/resolve/main/examples/classification_cube.py
- Command line
-
hf download hf://datasets/ZiyunPOLYU/ted-downstream-eo/examples/classification_cube.py
-
curl -L -o classification_cube.py https://huggingface.co/datasets/ZiyunPOLYU/ted-downstream-eo/resolve/main/examples/classification_cube.py
3.62 kB
| #!/usr/bin/env python3 | |
| """Read a task-ready classification cube and fit a temporal-mean linear probe. | |
| ``data`` is float32 with shape (time, band, sample). The first seven bands are | |
| Blue, Green, Red, NIR, SWIR1, SWIR2, NDVI, in DN x10000 except NDVI. Empty | |
| steps are NaN. ``sensor`` is 0 empty, 1 S30, 2 L30. | |
| CityRep and LUCAS store ``split``. The five older classification cubes do not; | |
| their published splits are spatial blocks and are not in the file. This example | |
| uses the stored split and does not rescale features. | |
| python classification_cube.py --dataset cityrep --limit 4000 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import numpy as np | |
| REPO = "ZiyunPOLYU/ted-downstream-eo" | |
| CUBES = { | |
| "cityrep": "ready_3day/cityrep_fullband_3day.nc", | |
| "lucas": "ready_3day/lucas_fullband_3day.nc", | |
| "cdl": "ready_3day/cdl_fullband_3day.nc", | |
| "cropharvest": "ready_3day/cropharvest_fullband_3day.nc", | |
| "globaltree": "ready_3day/globaltree_fullband_3day.nc", | |
| "glance": "ready_3day/glance_fullband_3day.nc", | |
| "lcmap": "ready_3day/lcmap_fullband_3day.nc", | |
| } | |
| COMMON = 7 | |
| def _open(dataset: str, path: str): | |
| import netCDF4 | |
| from huggingface_hub import hf_hub_download | |
| local = path or hf_hub_download(REPO, CUBES[dataset], repo_type="dataset") | |
| return netCDF4.Dataset(local) | |
| def _mean_features(ds, limit: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]: | |
| n = ds.dimensions["sample"].size if limit <= 0 else min(limit, ds.dimensions["sample"].size) | |
| cube = np.asarray(ds.variables["data"][:, :COMMON, :n], dtype=np.float32) | |
| with np.errstate(all="ignore"): | |
| features = np.nanmean(cube, axis=0).T | |
| labels = np.asarray(ds.variables["label"][:n]) | |
| split = np.asarray(ds.variables["split"][:n]).astype(str) if "split" in ds.variables else np.array([""] * n) | |
| return features, labels, split | |
| def _linear(x_train: np.ndarray, y_train: np.ndarray, x_test: np.ndarray) -> np.ndarray: | |
| classes = np.unique(y_train) | |
| design = np.concatenate([x_train, np.ones((len(x_train), 1), dtype=np.float32)], axis=1) | |
| targets = (y_train[:, None] == classes[None, :]).astype(np.float64) | |
| coef, *_ = np.linalg.lstsq(design, targets, rcond=None) | |
| test = np.concatenate([x_test, np.ones((len(x_test), 1), dtype=np.float32)], axis=1) | |
| return classes[(test @ coef).argmax(axis=1)] | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--dataset", choices=tuple(CUBES), default="cityrep") | |
| parser.add_argument("--cube", default="") | |
| parser.add_argument("--limit", type=int, default=0) | |
| args = parser.parse_args() | |
| with _open(args.dataset, args.cube) as ds: | |
| print("time", [str(item) for item in ds.variables["time"][:4]], "...", ds.dimensions["time"].size) | |
| print("bands", [str(item) for item in ds.variables["band"][:]]) | |
| print("note", ds.note) | |
| features, labels, split = _mean_features(ds, args.limit) | |
| finite = np.isfinite(features).all(axis=1) | |
| print(f"samples={len(features)} finite={int(finite.sum())} labeled_splits={sorted(set(split))}") | |
| train = finite & (split == "train") | |
| test = finite & (split == "test") | |
| if not train.any() or not test.any(): | |
| print("This cube has no train/test split column to score. CityRep and LUCAS do.") | |
| return | |
| pred = _linear(features[train], labels[train].astype(np.int64), features[test]) | |
| accuracy = float(np.mean(pred == labels[test].astype(np.int64))) | |
| print(f"temporal-mean linear accuracy={accuracy:.4f} n_train={int(train.sum())} n_test={int(test.sum())}") | |
| if __name__ == "__main__": | |
| main() | |