File size: 3,617 Bytes
cc74c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/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()