Samples into a matrix¶
limen_ml.matrix ¶
Training samples into the matrix a model learns from.
A sample is a features dictionary of blocks ({"static": {"slope_deg":
31.0}, "rain": {...}}), a 0/1 label and the split_block it belongs
to for spatial cross-validation. :func:to_matrix flattens the blocks into
"block.name" columns, in the order of the schema given: the order is what
a registered model reads back, so it never changes silently.
A feature a sample does not carry takes missing(name): NaN where "not
measured" must stay unknown (a cell with no satellite pixel is not a still
slope), 0 where absence is a true zero. The schema and that rule belong to the
application.
Sample ¶
Bases: Protocol
What a training sample carries.
TrainingMatrix
dataclass
¶
X, y, the spatial block of each row, and the ordered feature schema.
flatten ¶
flatten(features: Mapping[str, Any]) -> dict[str, float]
{"block.name": value} for the numbers of each block; everything else left out.
A sample may also carry raw inputs that are provenance, not columns (a land cover code as text, a flag): a string or a bool never becomes a number here.
to_matrix ¶
to_matrix(samples: Iterable[Sample], features: Sequence[str], *, missing: Callable[[str], float] = zero) -> TrainingMatrix
Stack samples into the matrix of the ordered schema features.
matrix_sha ¶
matrix_sha(matrix: TrainingMatrix) -> str
The SHA-256 of a matrix: same data, same hash, on any machine.
On the values rounded to nine decimals, not the raw bytes: BLAS sums in an order that depends on the number of threads, and a last-bit difference would change the hash without the data having changed. Names, labels and blocks are in it: the same numbers under other columns or another split are another dataset.
prune_collinear ¶
prune_collinear(matrix: TrainingMatrix, *, threshold: float) -> tuple[TrainingMatrix, list[tuple[str, str, float]]]
Drop each feature whose |Pearson r| with an earlier one exceeds threshold.
The schema order is the priority: the first of a collinear pair stays.
Boosted trees tolerate collinearity, but it splits the SHAP credit between
twins. The correlation of two columns is computed on the rows where both
are measured; a constant column correlates 0. Returns the matrix and the
dropped pairs (kept, dropped, r).