Skip to content

Learn

scikit-learn integration. Wraps any sklearn-compatible estimator (fit / predict / transform / decision_function / fit_predict) as a carrier-aware Operator.

Phase-1 API — subject to change

The current mode= / nan_fit= / nan_transform= kwargs are provisional. The full design (PixelTable carrier, type-named wrappers like PixelwiseClassifier, NanPolicy dataclass) will replace this surface in a follow-up (a breaking change, without aliases). Supervised estimators (classifiers / regressors) must be pre-fit out-of-graph and loaded via state_path= — in-graph supervised fit helpers are not implemented yet.

  • Universal adapter: SklearnOp, GeoArrayEstimator
  • Convenience wrappers (named algorithm, sensible defaults). Each is prefixed Pixelwise so it never shadows the scikit-learn class it wraps, and takes that estimator by keyword — gz.learn.PixelwisePCA(estimator=PCA(n_components=3)):
  • Decomposition: PixelwisePCA, PixelwiseIPCA, PixelwiseNMF
  • Clustering: PixelwiseKMeans, PixelwiseMiniBatchKMeans, PixelwiseGMM
  • Anomaly: PixelwiseIsolationForest, PixelwiseOneClassSVM, PixelwiseLocalOutlierFactor
  • Imputation: PixelwiseKNNImputer, PixelwiseIterativeImputer
  • Framework-agnostic inference: ModelOp(model=...)

Saved state

SklearnOp.save_state(path) (and GeoArrayEstimator.save_state) writes one joblib pickle holding the fitted estimator and imputer. Pass write_meta=True to also write a <path>.meta.json sidecar with the scikit-learn version, fit input shape / sample count and a UTC fit_timestamp; it is off by default so a save is deterministic and writes a single file.

Only load state files you trust

load_state(path) and the state_path= constructor argument unpickle the file with joblib.load, and unpickling can execute arbitrary code. Only load files you created yourself or that come from a source you trust as much as the code you run — never one from an untrusted upload, download or share. state_path= loads at construction, so this applies to instantiating a pipeline config too.

API reference

geoops.learn

scikit-learn integration for GeoArray operator pipelines.

.. warning::

**Phase-1 API — subject to change.** This module ships a universal
``SklearnOp`` adapter plus ``Pixelwise*`` named-algorithm convenience
wrappers (``PixelwisePCA``, ``PixelwiseKMeans``, ...) as a
first cut. The full design calls for
a ``PixelTable`` carrier, first-class shape adapters (``ToPixelMajor``,
``ToTemporalPixelMajor``, ``ToChipMajor``), and type-named estimator
wrappers (``PixelwiseClassifier`` / ``Regressor`` / ``Transformer`` /
``Clusterer`` / ``Proba`` / ``Decision``) backed by a ``NanPolicy``
dataclass. Those are not implemented yet; the current ``mode=`` /
``nan_fit=`` / ``nan_transform=`` keyword surface will be replaced
with that vocabulary in a follow-up (a breaking change, without aliases).

**State files are pickles.** ``load_state`` / ``state_path=`` unpickle
with ``joblib.load``, which can execute arbitrary code: only load
files from a trusted source. ``save_state(..., write_meta=True)``
opts in to a timestamped ``<path>.meta.json`` sidecar.

**Supervised estimators (classifiers / regressors) must be pre-fit**
out-of-graph and loaded via ``state_path=``. The operator's in-graph
fit modes (``fit_on_call`` / ``refit`` / ``fit_streaming``) take a
single ``GeoArray`` and have no path for a label tensor ``y``.
Out-of-graph fitting is the preferred pattern; in-graph fit helpers
(``fit_pixelwise``, ``fit_pixelwise_incremental``) are not
implemented yet.

GeoArrayEstimator

Marshall a scikit-learn estimator to and from GeoArray-shaped data.

scikit-learn works on 2-D (n_samples, n_features) matrices while remote-sensing cubes are channel-first rasters. This class owns the round trip between the two layouts. Axes follow the canonical channel-first order — (H, W) for 2-D input, (C, H, W) for 3-D, (T, C, H, W) for 4-D — and mode picks which axes become samples (rows) and which become features (columns):

  • "pixel": samples (H, W), features the rest. A (C, H, W) cube flattens to (H * W, C) — one row per pixel, one column per band.
  • "pixel_time": samples (T, H, W); (T, C, H, W) flattens to (T * H * W, C).
  • "spectral": samples (C,); (C, H, W) flattens to (C, H * W) — one row per band.
  • "temporal": samples (T,); features are all remaining axes.
  • "patch": samples axis 0; (N, ...) flattens to (N, prod(rest)).
  • "custom": explicit sample_axes / feature_axes (axis labels "T"/"C"/"H"/"W" or integer indices) that together must cover every input axis exactly once.

On the way back, a 1-D estimator output of length n_samples unflattens to the sample shape ("pixel" -> (H, W)); a 2-D output (n_samples, k) restores the sample axes to their original positions and places the k output-feature axis where the first input feature axis was ("pixel" on (C, H, W) -> (k, H, W)), or in front of the sample axes when there is no feature axis ("pixel" on a single-band (H, W) -> (k, H, W)), so outputs stay channel-first.

Nodata: a sample row is invalid when any of its elements is non-finite or equals the carrier's fill_value (see :mod:geoops._src.valid; plain ndarrays have no fill, so only non-finite values count). The nan_* strategies apply to every invalid row, not only NaN ones, and invalid elements are handed to NaN-tolerant estimators and imputers as NaN. Following georeader, a carrier with fill_value=0 treats 0 as nodata; pass fill_value=None (or NaN) on the input when 0 is real data.

Output fill values: rows that were not handed to the estimator are written back as nodata, and every GeoArray output declares an explicit fill_value that matches its dtype -- NaN for floating-point outputs (scores, projections, probabilities), label_fill_value (default -1) for integer outputs such as cluster-label maps (the dtype is kept), False for boolean outputs.

Carrier behavior: every method accepts a GeoArray or a plain np.ndarray. When the unflattened output's trailing two axes still match the input's spatial (H, W), the result is rewrapped to match the input carrier (GeoArray in -> GeoArray out with a fresh attrs copy; ndarray in -> ndarray out). Otherwise a bare ndarray is returned (e.g. sample-only outputs from mode="custom" or mode="spectral", or nan_transform="drop" with invalid rows).

Parameters:

Name Type Description Default
estimator Any

scikit-learn-compatible object to fit/apply.

required
mode ReshapeMode

Named reshape mode.

'pixel'
sample_axes tuple[str | int, ...] | None

Explicit sample axes for mode="custom".

None
feature_axes tuple[str | int, ...] | None

Explicit feature axes for mode="custom".

None
nan_fit NanStrategy

NaN strategy used while fitting.

'drop'
nan_transform NanStrategy

NaN strategy used while applying the estimator.

'propagate'
impute_simple_strategy str

Strategy passed to SimpleImputer.

'mean'
impute_knn_n_neighbors int

Neighbour count passed to KNNImputer.

5
impute_iterative_max_iter int

Iteration cap passed to IterativeImputer.

10
out_band_names Sequence[str] | None

Names of the output bands, written to attrs["band_names"] of GeoArray outputs (one per output band; a mismatch raises ValueError). None keeps the input's band keys when the band count is unchanged and drops them otherwise.

None
label_fill_value int

Fill value for integer outputs (e.g. cluster labels). -1 by default -- sklearn's "no cluster" label and never a valid KMeans / GMM component index. Pick another value if -1 is a real class of the wrapped estimator (e.g. IsolationForest.predict outliers).

-1

Attributes:

Name Type Description
estimator

The wrapped scikit-learn estimator (replaced on load_state).

imputer Any | None

Fitted imputer for the impute_* NaN strategies, or None. Refitted by :meth:fit; in streaming mode it is fitted on the first :meth:partial_fit batch and reused (frozen) for later batches.

is_fitted

Whether fit / partial_fit / fit_predict (or load_state) has run.

fit_geoarray_shape tuple[int, ...] | None

Shape of the last cube seen at fit time.

fit_n_samples int | None

Number of sample rows the estimator was fitted on.

Examples:

>>> from sklearn.decomposition import PCA
>>> est = GeoArrayEstimator(PCA(n_components=2), mode="pixel")
>>> projected = est.fit(scene).transform(scene)
Source code in packages/geotoolz-ops/src/geoops/learn/_src/estimators.py
 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
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
class GeoArrayEstimator:
    """Marshall a scikit-learn estimator to and from GeoArray-shaped data.

    scikit-learn works on 2-D ``(n_samples, n_features)`` matrices while
    remote-sensing cubes are channel-first rasters. This class owns the
    round trip between the two layouts. Axes follow the canonical
    channel-first order — ``(H, W)`` for 2-D input, ``(C, H, W)`` for
    3-D, ``(T, C, H, W)`` for 4-D — and ``mode`` picks which axes become
    samples (rows) and which become features (columns):

    - ``"pixel"``: samples ``(H, W)``, features the rest. A ``(C, H, W)``
      cube flattens to ``(H * W, C)`` — one row per pixel, one column
      per band.
    - ``"pixel_time"``: samples ``(T, H, W)``; ``(T, C, H, W)`` flattens
      to ``(T * H * W, C)``.
    - ``"spectral"``: samples ``(C,)``; ``(C, H, W)`` flattens to
      ``(C, H * W)`` — one row per band.
    - ``"temporal"``: samples ``(T,)``; features are all remaining axes.
    - ``"patch"``: samples axis ``0``; ``(N, ...)`` flattens to
      ``(N, prod(rest))``.
    - ``"custom"``: explicit ``sample_axes`` / ``feature_axes`` (axis
      labels ``"T"/"C"/"H"/"W"`` or integer indices) that together must
      cover every input axis exactly once.

    On the way back, a 1-D estimator output of length ``n_samples``
    unflattens to the sample shape (``"pixel"`` -> ``(H, W)``); a 2-D
    output ``(n_samples, k)`` restores the sample axes to their original
    positions and places the ``k`` output-feature axis where the first
    input feature axis was (``"pixel"`` on ``(C, H, W)`` -> ``(k, H, W)``),
    or in front of the sample axes when there is no feature axis
    (``"pixel"`` on a single-band ``(H, W)`` -> ``(k, H, W)``), so outputs
    stay channel-first.

    Nodata: a sample row is *invalid* when any of its elements is
    non-finite or equals the carrier's ``fill_value`` (see
    :mod:`geoops._src.valid`; plain ndarrays have no fill, so only
    non-finite values count). The ``nan_*`` strategies apply to every
    invalid row, not only NaN ones, and invalid elements are handed to
    NaN-tolerant estimators and imputers as ``NaN``. Following georeader,
    a carrier with ``fill_value=0`` treats ``0`` as nodata; pass
    ``fill_value=None`` (or ``NaN``) on the input when ``0`` is
    real data.

    Output fill values: rows that were not handed to the estimator are
    written back as nodata, and every GeoArray output declares an
    explicit ``fill_value`` that matches its dtype -- ``NaN`` for
    floating-point outputs (scores, projections, probabilities),
    ``label_fill_value`` (default ``-1``) for integer outputs such as
    cluster-label maps (the dtype is kept), ``False`` for boolean outputs.

    Carrier behavior: every method accepts a ``GeoArray`` or a plain
    ``np.ndarray``. When the unflattened output's trailing two axes still
    match the input's spatial ``(H, W)``, the result is rewrapped to
    match the input carrier (GeoArray in -> GeoArray out with a fresh
    ``attrs`` copy; ndarray in -> ndarray out). Otherwise a bare ndarray is
    returned (e.g. sample-only outputs from ``mode="custom"`` or
    ``mode="spectral"``, or ``nan_transform="drop"`` with invalid rows).

    Args:
        estimator: scikit-learn-compatible object to fit/apply.
        mode: Named reshape mode.
        sample_axes: Explicit sample axes for ``mode="custom"``.
        feature_axes: Explicit feature axes for ``mode="custom"``.
        nan_fit: NaN strategy used while fitting.
        nan_transform: NaN strategy used while applying the estimator.
        impute_simple_strategy: Strategy passed to ``SimpleImputer``.
        impute_knn_n_neighbors: Neighbour count passed to ``KNNImputer``.
        impute_iterative_max_iter: Iteration cap passed to ``IterativeImputer``.
        out_band_names: Names of the output bands, written to
            ``attrs["band_names"]`` of GeoArray outputs (one per output
            band; a mismatch raises ``ValueError``). ``None`` keeps the
            input's band keys when the band count is unchanged and drops
            them otherwise.
        label_fill_value: Fill value for integer outputs (e.g. cluster
            labels). ``-1`` by default -- sklearn's "no cluster" label and
            never a valid KMeans / GMM component index. Pick another value
            if ``-1`` is a real class of the wrapped estimator (e.g.
            ``IsolationForest.predict`` outliers).

    Attributes:
        estimator: The wrapped scikit-learn estimator (replaced on
            ``load_state``).
        imputer: Fitted imputer for the ``impute_*`` NaN strategies, or
            ``None``. Refitted by :meth:`fit`; in streaming mode it is
            fitted on the first :meth:`partial_fit` batch and reused
            (frozen) for later batches.
        is_fitted: Whether ``fit`` / ``partial_fit`` / ``fit_predict``
            (or ``load_state``) has run.
        fit_geoarray_shape: Shape of the last cube seen at fit time.
        fit_n_samples: Number of sample rows the estimator was fitted on.

    Examples:
        >>> from sklearn.decomposition import PCA
        >>> est = GeoArrayEstimator(PCA(n_components=2), mode="pixel")
        >>> projected = est.fit(scene).transform(scene)
    """

    def __init__(
        self,
        estimator: Any,
        *,
        mode: ReshapeMode = "pixel",
        sample_axes: tuple[str | int, ...] | None = None,
        feature_axes: tuple[str | int, ...] | None = None,
        nan_fit: NanStrategy = "drop",
        nan_transform: NanStrategy = "propagate",
        impute_simple_strategy: str = "mean",
        impute_knn_n_neighbors: int = 5,
        impute_iterative_max_iter: int = 10,
        out_band_names: Sequence[str] | None = None,
        label_fill_value: int = -1,
    ) -> None:
        self.estimator = estimator
        self.mode = mode
        self.sample_axes = sample_axes
        self.feature_axes = feature_axes
        self.nan_fit = nan_fit
        self.nan_transform = nan_transform
        self.impute_simple_strategy = impute_simple_strategy
        self.impute_knn_n_neighbors = impute_knn_n_neighbors
        self.impute_iterative_max_iter = impute_iterative_max_iter
        self.out_band_names = None if out_band_names is None else list(out_band_names)
        self.label_fill_value = int(label_fill_value)
        self.imputer: Any | None = None
        self.is_fitted = False
        self.fit_geoarray_shape: tuple[int, ...] | None = None
        self.fit_n_samples: int | None = None

        _validate_nan_strategy(nan_fit)
        _validate_nan_strategy(nan_transform)
        if mode == "custom" and (sample_axes is None or feature_axes is None):
            raise ValueError(
                "GeoArrayEstimator requires sample_axes and feature_axes "
                'when mode="custom"'
            )

    def fit(self, gt: GeoArray | np.ndarray) -> Self:
        """Fit the wrapped estimator on the flattened sample matrix.

        The cube is reshaped to ``(n_samples, n_features)`` according to
        ``mode`` (e.g. ``"pixel"`` sends ``(C, H, W)`` to ``(H * W, C)``),
        the ``nan_fit`` strategy is applied to the rows, and the result
        is handed to ``estimator.fit``.

        Args:
            gt: Input cube — a ``GeoArray`` or plain ``np.ndarray``.

        Returns:
            This estimator, for chaining.
        """
        flat = self._flatten(gt)
        x_fit, _ = self._prepare_fit(flat)
        self.estimator.fit(x_fit)
        self.is_fitted = True
        self.fit_geoarray_shape = tuple(np.asarray(gt).shape)
        self.fit_n_samples = int(x_fit.shape[0])
        return self

    def partial_fit(self, gt: GeoArray | np.ndarray) -> Self:
        """Incrementally fit the wrapped estimator on one flattened batch.

        Same ``(n_samples, n_features)`` marshalling and ``nan_fit``
        handling as :meth:`fit`, but routed to ``estimator.partial_fit``
        so streaming estimators accumulate state across calls. With an
        ``impute_*`` ``nan_fit`` strategy the imputer is fitted on the
        first batch only and reused (``imputer.transform``) for every
        later batch, so no batch re-derives the imputation statistics.

        Args:
            gt: Input cube — a ``GeoArray`` or plain ``np.ndarray``.

        Returns:
            This estimator, for chaining.

        Raises:
            TypeError: If the wrapped estimator has no ``partial_fit``.
        """
        if not hasattr(self.estimator, "partial_fit"):
            raise TypeError(
                f"{type(self.estimator).__name__} does not support partial_fit"
            )
        flat = self._flatten(gt)
        x_fit, _ = self._prepare_fit(flat, reuse_imputer=True)
        self.estimator.partial_fit(x_fit)
        self.is_fitted = True
        self.fit_geoarray_shape = tuple(np.asarray(gt).shape)
        self.fit_n_samples = int(x_fit.shape[0])
        return self

    def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Apply ``estimator.transform`` and unflatten the result.

        The cube is flattened to ``(n_samples, n_features)`` per
        ``mode``, ``nan_transform`` is applied, and the estimator output
        of shape ``(n_samples,)`` or ``(n_samples, k)`` is reshaped back
        (the ``k`` output-feature axis replaces the first input feature
        axis — ``"pixel"`` mode maps ``(C, H, W)`` input to ``(k, H, W)``
        output).

        Returns a carrier matching the input (GeoArray in -> GeoArray
        out, ndarray in -> ndarray out) when the output's trailing axes
        match the input's spatial ``(H, W)`` shape; otherwise returns a
        bare :class:`numpy.ndarray` (e.g. for sample-only outputs from
        ``mode="custom"``, or ``nan_transform="drop"`` with invalid rows).
        """
        return self._apply_task(gt, "transform")

    def predict(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Apply ``estimator.predict`` and unflatten the result.

        See :meth:`transform` for the reshaping and carrier contract.
        """
        return self._apply_task(gt, "predict")

    def predict_proba(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Apply ``estimator.predict_proba`` and unflatten the result.

        See :meth:`transform` for the reshaping and carrier contract.
        """
        return self._apply_task(gt, "predict_proba")

    def decision_function(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Apply ``estimator.decision_function`` and unflatten the result.

        See :meth:`transform` for the reshaping and carrier contract.
        """
        return self._apply_task(gt, "decision_function")

    def inverse_transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Apply ``estimator.inverse_transform`` and unflatten the result.

        See :meth:`transform` for the reshaping and carrier contract.
        """
        return self._apply_task(gt, "inverse_transform")

    def fit_predict(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Apply ``estimator.fit_predict`` and unflatten the result.

        Fitting uses the ``nan_fit`` strategy (like :meth:`fit`); see
        :meth:`transform` for the reshaping and carrier contract.

        Raises:
            TypeError: If the wrapped estimator has no ``fit_predict``.
        """
        if not hasattr(self.estimator, "fit_predict"):
            raise TypeError(
                f"{type(self.estimator).__name__} does not support fit_predict"
            )
        flat = self._flatten(gt)
        x_fit, valid = self._prepare_fit(flat)
        y_fit = self.estimator.fit_predict(x_fit)
        self.is_fitted = True
        self.fit_geoarray_shape = tuple(np.asarray(gt).shape)
        self.fit_n_samples = int(x_fit.shape[0])
        return self._unflatten_apply_result(gt, flat, y_fit, valid)

    def save_state(self, path: str | Path, *, write_meta: bool = False) -> None:
        """Persist the fitted estimator and any fitted imputer with joblib.

        The file is a joblib pickle: load it only where you would run code
        from its author (see :meth:`load_state`).

        Args:
            path: Destination file (parent directories are created).
            write_meta: Also write a ``<path>.meta.json`` sidecar recording
                the scikit-learn version, the fit input shape / sample
                count and a UTC ``fit_timestamp``. Off by default so saving
                is deterministic and writes exactly one file.
        """
        state_path = Path(path)
        state_path.parent.mkdir(parents=True, exist_ok=True)
        joblib = optional_module("joblib", "learn", feature="save_state")
        joblib.dump(
            {
                "estimator": self.estimator,
                "imputer": self.imputer,
                "is_fitted": self.is_fitted,
                "fit_geoarray_shape": self.fit_geoarray_shape,
                "fit_n_samples": self.fit_n_samples,
            },
            state_path,
        )
        if write_meta:
            _write_metadata(
                state_path,
                fit_geoarray_shape=self.fit_geoarray_shape,
                fit_n_samples=self.fit_n_samples,
            )

    def load_state(self, path: str | Path) -> None:
        """Load a fitted estimator and imputer previously saved with joblib.

        Warning:
            ``joblib.load`` unpickles the file, and unpickling can execute
            arbitrary code. Only load state files you created yourself or
            obtained from a source you trust as much as the code you run;
            never load one from an untrusted upload, download or share.
        """
        state_path = Path(path)
        if not state_path.exists():
            raise FileNotFoundError(f"Sklearn state file not found: {state_path}")
        joblib = optional_module("joblib", "learn", feature="load_state")
        state = joblib.load(state_path)
        self.estimator = state["estimator"]
        self.imputer = state.get("imputer")
        self.is_fitted = bool(state.get("is_fitted", True))
        shape = state.get("fit_geoarray_shape")
        self.fit_geoarray_shape = None if shape is None else tuple(shape)
        n_samples = state.get("fit_n_samples")
        self.fit_n_samples = None if n_samples is None else int(n_samples)

    def _flatten(self, gt: GeoArray | np.ndarray) -> _FlatGeoArray:
        arr = np.asarray(gt)
        axes = resolve_axes(arr.ndim, self.mode, self.sample_axes, self.feature_axes)
        x, layout = cube_to_samples(
            arr, band_axis=axes.feature_axes, sample_axes=axes.sample_axes
        )
        invalid, _ = cube_to_samples(
            invalid_values(gt),
            band_axis=axes.feature_axes,
            sample_axes=axes.sample_axes,
        )
        if invalid.any():
            # Fill values become NaN so imputers / NaN-tolerant estimators
            # (``propagate_raw``) recognise them as missing.
            x = as_float(x).copy()
            x[invalid] = np.nan
        return _FlatGeoArray(x=x, valid=~invalid.any(axis=1), layout=layout)

    def _prepare_fit(
        self, flat: _FlatGeoArray, *, reuse_imputer: bool = False
    ) -> tuple[Num[np.ndarray, "m c"], Bool[np.ndarray, " n"]]:
        strategy = self.nan_fit
        x, valid = flat.x, flat.valid
        if strategy == "error" and not valid.all():
            raise ValueError(
                "GeoArrayEstimator.fit received NaN / non-finite / fill values"
            )
        if strategy == "error":
            return x, valid
        if strategy == "drop":
            return x[valid], valid
        if strategy in {"propagate", "propagate_raw"}:
            # At fit time both pass the array through unchanged; the
            # apply-time behavior diverges (see ``_prepare_transform``).
            return x, np.ones(x.shape[0], dtype=bool)
        if reuse_imputer and self.imputer is not None:
            return self.imputer.transform(x), np.ones(x.shape[0], dtype=bool)
        self.imputer = _make_imputer(
            strategy,
            simple_strategy=self.impute_simple_strategy,
            knn_n_neighbors=self.impute_knn_n_neighbors,
            iterative_max_iter=self.impute_iterative_max_iter,
        )
        return self.imputer.fit_transform(x), np.ones(x.shape[0], dtype=bool)

    def _prepare_transform(
        self, flat: _FlatGeoArray
    ) -> tuple[Num[np.ndarray, "m c"], Bool[np.ndarray, " n"]]:
        """Apply ``nan_transform`` strategy to apply-time input.

        Invalid rows are those with a NaN, non-finite or fill element.
        ``"drop"`` strips invalid rows and the unflatten step truncates the
        sample axis to the valid rows only (output has fewer samples).
        ``"propagate"`` also strips invalid rows from the estimator input
        but the unflatten step writes the output fill (``NaN`` or
        ``label_fill_value``) at those positions so the spatial layout is
        preserved -- callers using raster carriers want this.
        ``"propagate_raw"`` passes rows through unchanged (fill elements
        as ``NaN``) so NaN-tolerant estimators (e.g. imputers) can see the
        missing values.
        Imputer strategies require a previously fitted imputer to avoid
        leaking inference-batch statistics into preprocessing.
        """
        strategy = self.nan_transform
        x, valid = flat.x, flat.valid
        if strategy == "error" and not valid.all():
            raise ValueError(
                "GeoArrayEstimator.transform received NaN / non-finite / fill values"
            )
        if strategy == "error":
            return x, valid
        if strategy == "drop":
            return x[valid], valid
        if strategy == "propagate":
            # Strip invalid rows from the estimator input; unflatten will
            # refill those positions with the output fill value.
            return x[valid], valid
        if strategy == "propagate_raw":
            # Pass rows through unchanged so NaN-tolerant estimators receive
            # the NaNs directly.
            return x, np.ones(x.shape[0], dtype=bool)
        if self.imputer is None:
            raise RuntimeError(
                f"nan_transform={strategy!r} requires a fitted imputer. Fit "
                f"the estimator first with a matching nan_fit strategy, or "
                f"load a saved state via load_state(). Fitting a fresh "
                f"imputer at transform time would leak inference-batch "
                f"statistics into preprocessing."
            )
        return self.imputer.transform(x), np.ones(x.shape[0], dtype=bool)

    def _apply_task(
        self, gt: GeoArray | np.ndarray, task: Task
    ) -> GeoArray | np.ndarray:
        if not hasattr(self.estimator, task):
            raise TypeError(f"{type(self.estimator).__name__} does not support {task}")
        flat = self._flatten(gt)
        x_apply, valid = self._prepare_transform(flat)
        y_apply = getattr(self.estimator, task)(x_apply)
        if self.nan_transform == "drop" and not valid.all():
            # ``drop`` returns only the rows the estimator actually saw,
            # collapsing the sample axis -- the result can no longer be
            # reshaped into the original spatial layout, so we return a
            # bare ndarray. Use ``propagate`` to preserve the layout.
            return np.asarray(y_apply)
        return self._unflatten_apply_result(gt, flat, y_apply, valid)

    def _unflatten_apply_result(
        self,
        gt: GeoArray | np.ndarray,
        flat: _FlatGeoArray,
        y_apply: Shaped[np.ndarray, " m"] | Shaped[np.ndarray, "m k"],
        valid: Bool[np.ndarray, " n"],
    ) -> GeoArray | np.ndarray:
        y = np.asarray(y_apply)
        fill_value = output_fill_value(y.dtype, self.label_fill_value)
        if valid.all():
            dense = y
        else:
            out_shape = (valid.shape[0], *y.shape[1:])
            if fill_value is None:
                dtype = np.result_type(y.dtype, float)
            elif y.dtype.kind in "iu":
                # Widen (e.g. uint8 labels with a -1 fill) only when needed.
                dtype = np.promote_types(y.dtype, np.min_scalar_type(fill_value))
            else:
                dtype = y.dtype
            dense = np.full(
                out_shape, np.nan if fill_value is None else fill_value, dtype=dtype
            )
            dense[valid] = y
        out = _restore_shape(dense, flat)
        # When the trailing axes do not match the input spatial (H, W),
        # ``wrap_like`` cannot attach CRS/transform
        # meaningfully (e.g. sample-only outputs from ``mode="custom"`` or
        # ``mode="spectral"``). Return a bare ndarray in that case; callers
        # / wrappers are responsible for re-attaching geo metadata.
        if out.ndim < 2 or out.shape[-2:] != np.asarray(gt).shape[-2:]:
            return out
        return wrap_like(
            gt,
            out,
            fill_value=np.nan if fill_value is None else fill_value,
            band_names=self.out_band_names,
        )

decision_function(gt)

Apply estimator.decision_function and unflatten the result.

See :meth:transform for the reshaping and carrier contract.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/estimators.py
def decision_function(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Apply ``estimator.decision_function`` and unflatten the result.

    See :meth:`transform` for the reshaping and carrier contract.
    """
    return self._apply_task(gt, "decision_function")

fit(gt)

Fit the wrapped estimator on the flattened sample matrix.

The cube is reshaped to (n_samples, n_features) according to mode (e.g. "pixel" sends (C, H, W) to (H * W, C)), the nan_fit strategy is applied to the rows, and the result is handed to estimator.fit.

Parameters:

Name Type Description Default
gt GeoArray | ndarray

Input cube — a GeoArray or plain np.ndarray.

required

Returns:

Type Description
Self

This estimator, for chaining.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/estimators.py
def fit(self, gt: GeoArray | np.ndarray) -> Self:
    """Fit the wrapped estimator on the flattened sample matrix.

    The cube is reshaped to ``(n_samples, n_features)`` according to
    ``mode`` (e.g. ``"pixel"`` sends ``(C, H, W)`` to ``(H * W, C)``),
    the ``nan_fit`` strategy is applied to the rows, and the result
    is handed to ``estimator.fit``.

    Args:
        gt: Input cube — a ``GeoArray`` or plain ``np.ndarray``.

    Returns:
        This estimator, for chaining.
    """
    flat = self._flatten(gt)
    x_fit, _ = self._prepare_fit(flat)
    self.estimator.fit(x_fit)
    self.is_fitted = True
    self.fit_geoarray_shape = tuple(np.asarray(gt).shape)
    self.fit_n_samples = int(x_fit.shape[0])
    return self

fit_predict(gt)

Apply estimator.fit_predict and unflatten the result.

Fitting uses the nan_fit strategy (like :meth:fit); see :meth:transform for the reshaping and carrier contract.

Raises:

Type Description
TypeError

If the wrapped estimator has no fit_predict.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/estimators.py
def fit_predict(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Apply ``estimator.fit_predict`` and unflatten the result.

    Fitting uses the ``nan_fit`` strategy (like :meth:`fit`); see
    :meth:`transform` for the reshaping and carrier contract.

    Raises:
        TypeError: If the wrapped estimator has no ``fit_predict``.
    """
    if not hasattr(self.estimator, "fit_predict"):
        raise TypeError(
            f"{type(self.estimator).__name__} does not support fit_predict"
        )
    flat = self._flatten(gt)
    x_fit, valid = self._prepare_fit(flat)
    y_fit = self.estimator.fit_predict(x_fit)
    self.is_fitted = True
    self.fit_geoarray_shape = tuple(np.asarray(gt).shape)
    self.fit_n_samples = int(x_fit.shape[0])
    return self._unflatten_apply_result(gt, flat, y_fit, valid)

inverse_transform(gt)

Apply estimator.inverse_transform and unflatten the result.

See :meth:transform for the reshaping and carrier contract.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/estimators.py
def inverse_transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Apply ``estimator.inverse_transform`` and unflatten the result.

    See :meth:`transform` for the reshaping and carrier contract.
    """
    return self._apply_task(gt, "inverse_transform")

load_state(path)

Load a fitted estimator and imputer previously saved with joblib.

Warning

joblib.load unpickles the file, and unpickling can execute arbitrary code. Only load state files you created yourself or obtained from a source you trust as much as the code you run; never load one from an untrusted upload, download or share.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/estimators.py
def load_state(self, path: str | Path) -> None:
    """Load a fitted estimator and imputer previously saved with joblib.

    Warning:
        ``joblib.load`` unpickles the file, and unpickling can execute
        arbitrary code. Only load state files you created yourself or
        obtained from a source you trust as much as the code you run;
        never load one from an untrusted upload, download or share.
    """
    state_path = Path(path)
    if not state_path.exists():
        raise FileNotFoundError(f"Sklearn state file not found: {state_path}")
    joblib = optional_module("joblib", "learn", feature="load_state")
    state = joblib.load(state_path)
    self.estimator = state["estimator"]
    self.imputer = state.get("imputer")
    self.is_fitted = bool(state.get("is_fitted", True))
    shape = state.get("fit_geoarray_shape")
    self.fit_geoarray_shape = None if shape is None else tuple(shape)
    n_samples = state.get("fit_n_samples")
    self.fit_n_samples = None if n_samples is None else int(n_samples)

partial_fit(gt)

Incrementally fit the wrapped estimator on one flattened batch.

Same (n_samples, n_features) marshalling and nan_fit handling as :meth:fit, but routed to estimator.partial_fit so streaming estimators accumulate state across calls. With an impute_* nan_fit strategy the imputer is fitted on the first batch only and reused (imputer.transform) for every later batch, so no batch re-derives the imputation statistics.

Parameters:

Name Type Description Default
gt GeoArray | ndarray

Input cube — a GeoArray or plain np.ndarray.

required

Returns:

Type Description
Self

This estimator, for chaining.

Raises:

Type Description
TypeError

If the wrapped estimator has no partial_fit.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/estimators.py
def partial_fit(self, gt: GeoArray | np.ndarray) -> Self:
    """Incrementally fit the wrapped estimator on one flattened batch.

    Same ``(n_samples, n_features)`` marshalling and ``nan_fit``
    handling as :meth:`fit`, but routed to ``estimator.partial_fit``
    so streaming estimators accumulate state across calls. With an
    ``impute_*`` ``nan_fit`` strategy the imputer is fitted on the
    first batch only and reused (``imputer.transform``) for every
    later batch, so no batch re-derives the imputation statistics.

    Args:
        gt: Input cube — a ``GeoArray`` or plain ``np.ndarray``.

    Returns:
        This estimator, for chaining.

    Raises:
        TypeError: If the wrapped estimator has no ``partial_fit``.
    """
    if not hasattr(self.estimator, "partial_fit"):
        raise TypeError(
            f"{type(self.estimator).__name__} does not support partial_fit"
        )
    flat = self._flatten(gt)
    x_fit, _ = self._prepare_fit(flat, reuse_imputer=True)
    self.estimator.partial_fit(x_fit)
    self.is_fitted = True
    self.fit_geoarray_shape = tuple(np.asarray(gt).shape)
    self.fit_n_samples = int(x_fit.shape[0])
    return self

predict(gt)

Apply estimator.predict and unflatten the result.

See :meth:transform for the reshaping and carrier contract.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/estimators.py
def predict(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Apply ``estimator.predict`` and unflatten the result.

    See :meth:`transform` for the reshaping and carrier contract.
    """
    return self._apply_task(gt, "predict")

predict_proba(gt)

Apply estimator.predict_proba and unflatten the result.

See :meth:transform for the reshaping and carrier contract.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/estimators.py
def predict_proba(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Apply ``estimator.predict_proba`` and unflatten the result.

    See :meth:`transform` for the reshaping and carrier contract.
    """
    return self._apply_task(gt, "predict_proba")

save_state(path, *, write_meta=False)

Persist the fitted estimator and any fitted imputer with joblib.

The file is a joblib pickle: load it only where you would run code from its author (see :meth:load_state).

Parameters:

Name Type Description Default
path str | Path

Destination file (parent directories are created).

required
write_meta bool

Also write a <path>.meta.json sidecar recording the scikit-learn version, the fit input shape / sample count and a UTC fit_timestamp. Off by default so saving is deterministic and writes exactly one file.

False
Source code in packages/geotoolz-ops/src/geoops/learn/_src/estimators.py
def save_state(self, path: str | Path, *, write_meta: bool = False) -> None:
    """Persist the fitted estimator and any fitted imputer with joblib.

    The file is a joblib pickle: load it only where you would run code
    from its author (see :meth:`load_state`).

    Args:
        path: Destination file (parent directories are created).
        write_meta: Also write a ``<path>.meta.json`` sidecar recording
            the scikit-learn version, the fit input shape / sample
            count and a UTC ``fit_timestamp``. Off by default so saving
            is deterministic and writes exactly one file.
    """
    state_path = Path(path)
    state_path.parent.mkdir(parents=True, exist_ok=True)
    joblib = optional_module("joblib", "learn", feature="save_state")
    joblib.dump(
        {
            "estimator": self.estimator,
            "imputer": self.imputer,
            "is_fitted": self.is_fitted,
            "fit_geoarray_shape": self.fit_geoarray_shape,
            "fit_n_samples": self.fit_n_samples,
        },
        state_path,
    )
    if write_meta:
        _write_metadata(
            state_path,
            fit_geoarray_shape=self.fit_geoarray_shape,
            fit_n_samples=self.fit_n_samples,
        )

transform(gt)

Apply estimator.transform and unflatten the result.

The cube is flattened to (n_samples, n_features) per mode, nan_transform is applied, and the estimator output of shape (n_samples,) or (n_samples, k) is reshaped back (the k output-feature axis replaces the first input feature axis — "pixel" mode maps (C, H, W) input to (k, H, W) output).

Returns a carrier matching the input (GeoArray in -> GeoArray out, ndarray in -> ndarray out) when the output's trailing axes match the input's spatial (H, W) shape; otherwise returns a bare :class:numpy.ndarray (e.g. for sample-only outputs from mode="custom", or nan_transform="drop" with invalid rows).

Source code in packages/geotoolz-ops/src/geoops/learn/_src/estimators.py
def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Apply ``estimator.transform`` and unflatten the result.

    The cube is flattened to ``(n_samples, n_features)`` per
    ``mode``, ``nan_transform`` is applied, and the estimator output
    of shape ``(n_samples,)`` or ``(n_samples, k)`` is reshaped back
    (the ``k`` output-feature axis replaces the first input feature
    axis — ``"pixel"`` mode maps ``(C, H, W)`` input to ``(k, H, W)``
    output).

    Returns a carrier matching the input (GeoArray in -> GeoArray
    out, ndarray in -> ndarray out) when the output's trailing axes
    match the input's spatial ``(H, W)`` shape; otherwise returns a
    bare :class:`numpy.ndarray` (e.g. for sample-only outputs from
    ``mode="custom"``, or ``nan_transform="drop"`` with invalid rows).
    """
    return self._apply_task(gt, "transform")

ModelOp

Bases: Operator

Wrap any callable as an Operator.

Materialises the GeoArray to a plain np.ndarray (via np.asarray) before handing it to the model — frameworks that strip the subclass (torch, JAX, sklearn) don't care, and frameworks that preserve it (numpy proper) still see something sensible.

Output contract: the model's return value is passed through as-is and never rewrapped into the input carrier -- a GeoArray input yields whatever the model returns (an np.ndarray, a torch tensor, ...) without transform / crs / fill_value. Rewrap it yourself, or use :class:SklearnOp, which restores the grid for per-pixel estimators.

Parameters:

Name Type Description Default
model Any

Any object that can be called as model(arr) or whose method attribute can be called as model.predict(arr). No framework imports; the shape is checked structurally at construction.

required
method str

Method name to invoke on model. Default "__call__" — equivalent to model(arr). Set to "predict" for sklearn estimators; the model must then satisfy :class:pipekit_ops.Predictor.

'__call__'
batch_size int | None

If set, split the input along axis 0 into chunks of this size, call the model once per chunk, concatenate the results along axis 0. Useful when the model can't fit the whole input in GPU memory.

None

Raises:

Type Description
TypeError

At construction, when method="predict" and model is not a :class:pipekit_ops.Predictor, when method="__call__" and model is not callable, or when model has no callable method attribute.

Note

forbid_in_yaml = True — the model is a runtime object and won't round-trip to YAML. Users typically pin a model artifact (state-dict + class config) themselves.

Examples:

A scikit-learn estimator sees the raw array, so feed it the (n_samples, n_features) table it was fit on; for per-pixel prediction on a (C, H, W) scene use :class:SklearnOp, which flattens the pixels and restores the grid::

op = ModelOp(model=rf_clf, method="predict")
labels = op(features)  # features: (n_samples, n_features)

Batched inference with a torch model::

op = ModelOp(model=unet_model, batch_size=8)
preds = op(chips_gt)  # iterates 8 chips at a time
Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class ModelOp(Operator):
    """Wrap any callable as an Operator.

    Materialises the GeoArray to a plain ``np.ndarray`` (via
    ``np.asarray``) before handing it to the model — frameworks that
    strip the subclass (torch, JAX, sklearn) don't care, and frameworks
    that preserve it (numpy proper) still see something sensible.

    Output contract: the model's return value is passed through **as-is**
    and never rewrapped into the input carrier -- a ``GeoArray`` input
    yields whatever the model returns (an ``np.ndarray``, a torch tensor,
    ...) without ``transform`` / ``crs`` / ``fill_value``. Rewrap
    it yourself, or use :class:`SklearnOp`, which restores the grid for
    per-pixel estimators.

    Args:
        model: Any object that can be called as ``model(arr)`` or whose
            ``method`` attribute can be called as
            ``model.predict(arr)``. No framework imports; the shape is
            checked structurally at construction.
        method: Method name to invoke on ``model``. Default
            ``"__call__"`` — equivalent to ``model(arr)``. Set to
            ``"predict"`` for sklearn estimators; the model must then
            satisfy :class:`pipekit_ops.Predictor`.
        batch_size: If set, split the input along axis 0 into chunks of
            this size, call the model once per chunk, concatenate the
            results along axis 0. Useful when the model can't fit the
            whole input in GPU memory.

    Raises:
        TypeError: At construction, when ``method="predict"`` and
            ``model`` is not a :class:`pipekit_ops.Predictor`, when
            ``method="__call__"`` and ``model`` is not callable, or when
            ``model`` has no callable ``method`` attribute.

    Note:
        ``forbid_in_yaml = True`` — the model is a runtime object and
        won't round-trip to YAML. Users typically pin a model artifact
        (state-dict + class config) themselves.

    Examples:
        A scikit-learn estimator sees the raw array, so feed it the
        ``(n_samples, n_features)`` table it was fit on; for per-pixel
        prediction on a ``(C, H, W)`` scene use :class:`SklearnOp`,
        which flattens the pixels and restores the grid::

            op = ModelOp(model=rf_clf, method="predict")
            labels = op(features)  # features: (n_samples, n_features)

        Batched inference with a torch model::

            op = ModelOp(model=unet_model, batch_size=8)
            preds = op(chips_gt)  # iterates 8 chips at a time
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # any model: unknown until configured
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space", "time"}, reach=None
    )

    forbid_in_yaml: ClassVar[bool] = True
    # ConfigMixin would auto-derive `model` from `__init__` as a non-JSON
    # opaque object; override with a curated debug repr below.
    __config_mixin_auto__: ClassVar[bool] = False

    def __init__(
        self,
        *,
        model: Any,
        method: str = "__call__",
        batch_size: int | None = None,
    ) -> None:
        if method == "predict":
            if not isinstance(model, Predictor):
                raise TypeError(
                    f'ModelOp(method="predict") needs a pipekit Predictor (an '
                    f"object with a predict method); got {type(model).__name__}"
                )
        elif method == "__call__":
            if not callable(model):
                raise TypeError(
                    f"ModelOp model must be callable; got {type(model).__name__}"
                )
        elif not callable(getattr(model, method, None)):
            raise TypeError(
                f"ModelOp model {type(model).__name__} has no callable "
                f"{method!r} method"
            )
        self.model = model
        self.method = method
        self.batch_size = batch_size

    def _resolve_callable(self) -> Any:
        if self.method == "__call__":
            return self.model
        return getattr(self.model, self.method)

    def _apply(self, gt: Carrier) -> Any:
        reject_geotensor(gt, type(self).__name__)
        arr = np.asarray(gt)
        fn = self._resolve_callable()
        if self.batch_size is None:
            return fn(arr)
        return self._batched(fn, arr)

    def _batched(self, fn: Any, arr: np.ndarray) -> np.ndarray:
        """Split ``arr`` along axis 0, call ``fn`` per chunk, concatenate.

        Plain ``np.concatenate`` along axis 0 — works when the model's
        output preserves the batch dimension (the common case).

        Empty inputs (``arr.shape[0] == 0``) are passed straight to the
        model in one call: ``np.concatenate`` cannot accept an empty list
        of chunks, and the model is free to return a meaningful
        zero-length result.
        """
        n = arr.shape[0]
        if n == 0:
            return fn(arr)
        chunks: list[Any] = []
        bs = int(self.batch_size or n)
        for start in range(0, n, bs):
            chunks.append(fn(arr[start : start + bs]))
        return np.concatenate(chunks, axis=0)

    def get_config(self) -> dict[str, Any]:
        return {
            "model_type": type(self.model).__name__,
            "method": self.method,
            "batch_size": self.batch_size,
        }

PixelwiseGMM

Bases: SklearnOp

Gaussian mixture convenience operator.

Pins mode="pixel" and task="predict_proba" — the output has one band per mixture component; every other :class:SklearnOp keyword argument passes through.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class PixelwiseGMM(SklearnOp):
    """Gaussian mixture convenience operator.

    Pins ``mode="pixel"`` and ``task="predict_proba"`` — the output has
    one band per mixture component; every other :class:`SklearnOp`
    keyword argument passes through.
    """

    def __init__(self, *, estimator: Any, **kwargs: Any) -> None:
        kwargs.setdefault("mode", "pixel")
        kwargs.setdefault("task", "predict_proba")
        super().__init__(estimator=estimator, **kwargs)

PixelwiseIPCA

Bases: SklearnOp

Streaming IncrementalPCA convenience operator.

Pins mode="pixel", fit_mode="fit_streaming" (each call routes through partial_fit), task="transform"; every other :class:SklearnOp keyword argument passes through.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class PixelwiseIPCA(SklearnOp):
    """Streaming IncrementalPCA convenience operator.

    Pins ``mode="pixel"``, ``fit_mode="fit_streaming"`` (each call routes
    through ``partial_fit``), ``task="transform"``; every other
    :class:`SklearnOp` keyword argument passes through.
    """

    # partial_fit on every call: the state follows each scene
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space", "time"},
        effects={"band": "mix", "time": "reduce"},
        reach=None,
    )

    def __init__(self, *, estimator: Any, **kwargs: Any) -> None:
        kwargs.setdefault("mode", "pixel")
        kwargs.setdefault("fit_mode", "fit_streaming")
        kwargs.setdefault("task", "transform")
        super().__init__(estimator=estimator, **kwargs)

PixelwiseIsolationForest

Bases: SklearnOp

Pixel-wise IsolationForest anomaly-score convenience operator.

Pins mode="pixel" and task="decision_function" — the output is a single-band anomaly-score map; every other :class:SklearnOp keyword argument passes through.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class PixelwiseIsolationForest(SklearnOp):
    """Pixel-wise IsolationForest anomaly-score convenience operator.

    Pins ``mode="pixel"`` and ``task="decision_function"`` — the output
    is a single-band anomaly-score map; every other :class:`SklearnOp`
    keyword argument passes through.
    """

    def __init__(self, *, estimator: Any, **kwargs: Any) -> None:
        kwargs.setdefault("mode", "pixel")
        kwargs.setdefault("task", "decision_function")
        super().__init__(estimator=estimator, **kwargs)

PixelwiseIterativeImputer

Bases: SklearnOp

Pixel-wise IterativeImputer convenience operator.

Pins mode="pixel", task="transform", and nan_fit=nan_transform="propagate"; every other :class:SklearnOp keyword argument passes through.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class PixelwiseIterativeImputer(SklearnOp):
    """Pixel-wise IterativeImputer convenience operator.

    Pins ``mode="pixel"``, ``task="transform"``, and
    ``nan_fit=nan_transform="propagate"``; every other
    :class:`SklearnOp` keyword argument passes through.
    """

    def __init__(self, *, estimator: Any, **kwargs: Any) -> None:
        kwargs.setdefault("mode", "pixel")
        kwargs.setdefault("task", "transform")
        kwargs.setdefault("nan_fit", "propagate")
        kwargs.setdefault("nan_transform", "propagate")
        super().__init__(estimator=estimator, **kwargs)

PixelwiseKMeans

Bases: SklearnOp

Pixel-wise KMeans label convenience operator.

Pins mode="pixel" and task="predict" — the output is a single-band cluster-label map; every other :class:SklearnOp keyword argument passes through.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class PixelwiseKMeans(SklearnOp):
    """Pixel-wise KMeans label convenience operator.

    Pins ``mode="pixel"`` and ``task="predict"`` — the output is a
    single-band cluster-label map; every other :class:`SklearnOp`
    keyword argument passes through.
    """

    def __init__(self, *, estimator: Any, **kwargs: Any) -> None:
        kwargs.setdefault("mode", "pixel")
        kwargs.setdefault("task", "predict")
        super().__init__(estimator=estimator, **kwargs)

PixelwiseKNNImputer

Bases: SklearnOp

Pixel-wise KNNImputer convenience operator.

Pins mode="pixel", task="transform", and nan_fit=nan_transform="propagate" so the NaN-tolerant imputer fits on the clean rows and NaN placement is preserved for it to fill; every other :class:SklearnOp keyword argument passes through.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class PixelwiseKNNImputer(SklearnOp):
    """Pixel-wise KNNImputer convenience operator.

    Pins ``mode="pixel"``, ``task="transform"``, and
    ``nan_fit=nan_transform="propagate"`` so the NaN-tolerant imputer
    fits on the clean rows and NaN placement is preserved for it to
    fill; every other :class:`SklearnOp` keyword argument passes
    through.
    """

    def __init__(self, *, estimator: Any, **kwargs: Any) -> None:
        kwargs.setdefault("mode", "pixel")
        kwargs.setdefault("task", "transform")
        kwargs.setdefault("nan_fit", "propagate")
        kwargs.setdefault("nan_transform", "propagate")
        super().__init__(estimator=estimator, **kwargs)

PixelwiseLocalOutlierFactor

Bases: SklearnOp

Pixel-wise LocalOutlierFactor convenience operator.

Pins mode="pixel" and task="decision_function"; requires the estimator to be constructed with novelty=True (sklearn only exposes decision_function in novelty mode). Every other :class:SklearnOp keyword argument passes through.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class PixelwiseLocalOutlierFactor(SklearnOp):
    """Pixel-wise LocalOutlierFactor convenience operator.

    Pins ``mode="pixel"`` and ``task="decision_function"``; requires the
    estimator to be constructed with ``novelty=True`` (sklearn only
    exposes ``decision_function`` in novelty mode). Every other
    :class:`SklearnOp` keyword argument passes through.
    """

    def __init__(self, *, estimator: Any, **kwargs: Any) -> None:
        kwargs.setdefault("mode", "pixel")
        kwargs.setdefault("task", "decision_function")
        super().__init__(estimator=estimator, **kwargs)

PixelwiseMiniBatchKMeans

Bases: SklearnOp

Streaming MiniBatchKMeans convenience operator.

Pins mode="pixel", fit_mode="fit_streaming" (each call routes through partial_fit), task="predict"; every other :class:SklearnOp keyword argument passes through.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class PixelwiseMiniBatchKMeans(SklearnOp):
    """Streaming MiniBatchKMeans convenience operator.

    Pins ``mode="pixel"``, ``fit_mode="fit_streaming"`` (each call routes
    through ``partial_fit``), ``task="predict"``; every other
    :class:`SklearnOp` keyword argument passes through.
    """

    def __init__(self, *, estimator: Any, **kwargs: Any) -> None:
        kwargs.setdefault("mode", "pixel")
        kwargs.setdefault("fit_mode", "fit_streaming")
        kwargs.setdefault("task", "predict")
        super().__init__(estimator=estimator, **kwargs)

PixelwiseNMF

Bases: SklearnOp

Pixel-wise NMF convenience operator.

Pins mode="pixel" and task="transform"; every other :class:SklearnOp keyword argument passes through.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class PixelwiseNMF(SklearnOp):
    """Pixel-wise NMF convenience operator.

    Pins ``mode="pixel"`` and ``task="transform"``; every other
    :class:`SklearnOp` keyword argument passes through.
    """

    def __init__(self, *, estimator: Any, **kwargs: Any) -> None:
        kwargs.setdefault("mode", "pixel")
        kwargs.setdefault("task", "transform")
        super().__init__(estimator=estimator, **kwargs)

PixelwiseOneClassSVM

Bases: SklearnOp

Pixel-wise OneClassSVM anomaly-score convenience operator.

Pins mode="pixel" and task="decision_function"; every other :class:SklearnOp keyword argument passes through.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class PixelwiseOneClassSVM(SklearnOp):
    """Pixel-wise OneClassSVM anomaly-score convenience operator.

    Pins ``mode="pixel"`` and ``task="decision_function"``; every other
    :class:`SklearnOp` keyword argument passes through.
    """

    def __init__(self, *, estimator: Any, **kwargs: Any) -> None:
        kwargs.setdefault("mode", "pixel")
        kwargs.setdefault("task", "decision_function")
        super().__init__(estimator=estimator, **kwargs)

PixelwisePCA

Bases: SklearnOp

Pixel-wise PCA convenience operator.

Pins mode="pixel", task="transform", nan_fit="drop"; every other :class:SklearnOp keyword argument passes through.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class PixelwisePCA(SklearnOp):
    """Pixel-wise PCA convenience operator.

    Pins ``mode="pixel"``, ``task="transform"``, ``nan_fit="drop"``;
    every other :class:`SklearnOp` keyword argument passes through.
    """

    def __init__(self, *, estimator: Any, **kwargs: Any) -> None:
        kwargs.setdefault("mode", "pixel")
        kwargs.setdefault("task", "transform")
        kwargs.setdefault("nan_fit", "drop")
        super().__init__(estimator=estimator, **kwargs)

SklearnOp

Bases: Operator

Universal adapter for scikit-learn-compatible estimators on GeoArrays.

Delegates the (C, H, W) <-> (n_samples, n_features) marshalling to :class:GeoArrayEstimator and adds the fitting lifecycle (fit_mode) plus joblib state persistence. Metadata-independent: accepts a GeoArray or a plain np.ndarray and returns a matching carrier whenever the estimator output preserves the input's spatial (H, W) layout; sample-only outputs (and nan_transform="drop" with invalid rows) come back as bare ndarrays.

Parameters:

Name Type Description Default
estimator Any

scikit-learn-compatible object to wrap.

required
mode ReshapeMode

Named reshape mode passed to :class:GeoArrayEstimator.

'pixel'
sample_axes tuple[str | int, ...] | None

Explicit sample axes for mode="custom".

None
feature_axes tuple[str | int, ...] | None

Explicit feature axes for mode="custom".

None
fit_mode FitMode

Fitting lifecycle: "pre_fit" (loaded state, never fitted in-graph), "fit_on_call" (fit once on the first call -- exactly once even under concurrent calls -- then reuse), "refit" (fit on every call), "fit_streaming" (partial_fit every call; invalid with task="fit_predict") or "fit_only" (fit, return the input). refit / fit_streaming / fit_only and task="fit_predict" mutate the estimator on every call, so their results depend on call history; each call's fit + apply runs under a per-operator lock, which serialises concurrent calls (pipekit_ops.ThreadMap) rather than racing them.

'fit_on_call'
task Task | None

Estimator method used at apply time. None auto-detects.

None
nan_fit NanStrategy

NaN strategy used while fitting.

'drop'
nan_transform NanStrategy

NaN strategy used while applying the estimator.

'propagate'
state_path str | Path | None

Optional joblib path to load immediately, in the constructor. Loading unpickles the file, which can execute arbitrary code: only pass files from a trusted source (see :meth:load_state).

None
out_band_names list[str] | None

Names of the output bands, written to attrs["band_names"] of GeoArray outputs (must match the output band count). None keeps the input's band keys when the band count is unchanged and drops them otherwise.

None
label_fill_value int

Fill value of integer outputs such as cluster-label maps (default -1). Float outputs always use NaN. See :class:GeoArrayEstimator for the nodata rules (fill pixels of the input are excluded from fits and come back as the output fill).

-1

Fitted operator (see Fitted operators in the concepts guide): :meth:fit / :meth:partial_fit fit the estimator explicitly and :meth:transform / :meth:predict apply it without fitting, so the operator satisfies :class:pipekit_ops.FittableTransformer and :class:pipekit_ops.Predictor. The fitted estimator is never part of get_config() (persist it with :meth:save_state).

Examples:

>>> from sklearn.decomposition import PCA
>>> op = SklearnOp(estimator=PCA(n_components=3), mode="pixel")
>>> projected = op(scene)
>>> # or fit on one scene, apply to others:
>>> op = SklearnOp(estimator=PCA(n_components=3)).fit(train_scene)
>>> projected = op.transform(scene)
Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class SklearnOp(Operator):
    """Universal adapter for scikit-learn-compatible estimators on GeoArrays.

    Delegates the ``(C, H, W) <-> (n_samples, n_features)`` marshalling
    to :class:`GeoArrayEstimator` and adds the fitting lifecycle
    (``fit_mode``) plus joblib state persistence. Metadata-independent:
    accepts a ``GeoArray`` or a plain ``np.ndarray`` and returns a
    matching carrier whenever the estimator output preserves the input's
    spatial ``(H, W)`` layout; sample-only outputs (and
    ``nan_transform="drop"`` with invalid rows) come back as bare ndarrays.

    Args:
        estimator: scikit-learn-compatible object to wrap.
        mode: Named reshape mode passed to :class:`GeoArrayEstimator`.
        sample_axes: Explicit sample axes for ``mode="custom"``.
        feature_axes: Explicit feature axes for ``mode="custom"``.
        fit_mode: Fitting lifecycle: ``"pre_fit"`` (loaded state, never
            fitted in-graph), ``"fit_on_call"`` (fit once on the first
            call -- exactly once even under concurrent calls -- then
            reuse), ``"refit"`` (fit on every call), ``"fit_streaming"``
            (``partial_fit`` every call; invalid with
            ``task="fit_predict"``) or ``"fit_only"`` (fit, return the
            input). ``refit`` / ``fit_streaming`` / ``fit_only`` and
            ``task="fit_predict"`` mutate the estimator on every call, so
            their results depend on call history; each call's fit + apply
            runs under a per-operator lock, which serialises concurrent
            calls (``pipekit_ops.ThreadMap``) rather than racing them.
        task: Estimator method used at apply time. ``None`` auto-detects.
        nan_fit: NaN strategy used while fitting.
        nan_transform: NaN strategy used while applying the estimator.
        state_path: Optional joblib path to load immediately, in the
            constructor. Loading unpickles the file, which can execute
            arbitrary code: only pass files from a trusted source (see
            :meth:`load_state`).
        out_band_names: Names of the output bands, written to
            ``attrs["band_names"]`` of GeoArray outputs (must match the
            output band count). ``None`` keeps the input's band keys when
            the band count is unchanged and drops them otherwise.
        label_fill_value: Fill value of integer outputs such as
            cluster-label maps (default ``-1``). Float outputs always use
            ``NaN``. See :class:`GeoArrayEstimator` for the nodata rules
            (fill pixels of the input are excluded from fits and come back
            as the output fill).

    Fitted operator (see *Fitted operators* in the concepts guide):
    :meth:`fit` / :meth:`partial_fit` fit the estimator explicitly and
    :meth:`transform` / :meth:`predict` apply it without fitting, so the
    operator satisfies :class:`pipekit_ops.FittableTransformer` and
    :class:`pipekit_ops.Predictor`. The fitted estimator is never
    part of ``get_config()`` (persist it with :meth:`save_state`).

    Examples:
        >>> from sklearn.decomposition import PCA
        >>> op = SklearnOp(estimator=PCA(n_components=3), mode="pixel")
        >>> projected = op(scene)
        >>> # or fit on one scene, apply to others:
        >>> op = SklearnOp(estimator=PCA(n_components=3)).fit(train_scene)
        >>> projected = op.transform(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # every non-spatial axis is a feature; the estimator is fitted over every pixel
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "time"},
        effects={"band": "mix", "time": "reduce"},
        fit={"space"},
    )

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(
        self,
        *,
        estimator: Any,
        mode: ReshapeMode = "pixel",
        sample_axes: tuple[str | int, ...] | None = None,
        feature_axes: tuple[str | int, ...] | None = None,
        fit_mode: FitMode = "fit_on_call",
        task: Task | None = None,
        nan_fit: NanStrategy = "drop",
        nan_transform: NanStrategy = "propagate",
        impute_simple_strategy: str = "mean",
        impute_knn_n_neighbors: int = 5,
        impute_iterative_max_iter: int = 10,
        state_path: str | Path | None = None,
        out_band_names: list[str] | None = None,
        label_fill_value: int = -1,
    ) -> None:
        _validate_fit_mode(fit_mode)
        resolved_task = _resolve_task(estimator, task)
        if fit_mode == "fit_streaming" and not hasattr(estimator, "partial_fit"):
            raise TypeError(
                f"{type(estimator).__name__} does not support fit_streaming "
                "because it has no partial_fit method"
            )
        if fit_mode in {"pre_fit", "fit_streaming"} and resolved_task == "fit_predict":
            # fit_predict refits from scratch on every call, so it can
            # neither reuse a loaded state nor accumulate partial_fit batches.
            raise ValueError(
                f'fit_mode="{fit_mode}" is not valid with task="fit_predict"'
            )
        if fit_mode == "pre_fit" and state_path is None:
            raise ValueError(
                'fit_mode="pre_fit" requires state_path to point at a '
                "previously fitted estimator state"
            )

        self.estimator = estimator
        self.mode = mode
        self.sample_axes = sample_axes
        self.feature_axes = feature_axes
        self.fit_mode = fit_mode
        self.task = task
        self.nan_fit = nan_fit
        self.nan_transform = nan_transform
        self.impute_simple_strategy = impute_simple_strategy
        self.impute_knn_n_neighbors = impute_knn_n_neighbors
        self.impute_iterative_max_iter = impute_iterative_max_iter
        self.state_path = None if state_path is None else str(state_path)
        self.out_band_names = out_band_names
        self.label_fill_value = label_fill_value
        self._task = resolved_task
        self._geo_estimator = GeoArrayEstimator(
            estimator,
            mode=mode,
            sample_axes=sample_axes,
            feature_axes=feature_axes,
            nan_fit=nan_fit,
            nan_transform=nan_transform,
            impute_simple_strategy=impute_simple_strategy,
            impute_knn_n_neighbors=impute_knn_n_neighbors,
            impute_iterative_max_iter=impute_iterative_max_iter,
            out_band_names=out_band_names,
            label_fill_value=label_fill_value,
        )
        if state_path is not None:
            self.load_state(state_path)

    @property
    def is_fitted(self) -> bool:
        """Whether the wrapped estimator has been fitted (or loaded)."""
        return self._geo_estimator.is_fitted

    def fit(self, gt: GeoArray | np.ndarray) -> Self:
        """Fit the wrapped estimator on ``gt`` (``nan_fit`` strategy applies).

        Returns:
            This operator, for chaining.
        """
        self._geo_estimator.fit(gt)
        return self

    def partial_fit(self, gt: GeoArray | np.ndarray) -> Self:
        """Update a streaming estimator with one more batch.

        Returns:
            This operator, for chaining.
        """
        self._geo_estimator.partial_fit(gt)
        return self

    def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Apply ``estimator.transform`` without fitting."""
        return self._geo_estimator.transform(gt)

    def predict(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Apply ``estimator.predict`` without fitting."""
        return self._geo_estimator.predict(gt)

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        geo = self._geo_estimator
        if self.fit_mode == "pre_fit":
            return getattr(geo, self._task)(gt)
        if self.fit_mode == "fit_on_call" and self._task != "fit_predict":
            fit_once(self, gt, lambda: geo.is_fitted)
            return getattr(geo, self._task)(gt)
        # The remaining modes mutate the estimator on every call; the lock
        # keeps each call's fit + apply atomic under concurrent callers.
        with fit_lock(self):
            if self._task == "fit_predict":
                return geo.fit_predict(gt)
            if self.fit_mode == "fit_streaming":
                geo.partial_fit(gt)
            else:  # "refit" / "fit_only"
                geo.fit(gt)
            if self.fit_mode == "fit_only":
                return gt
            return getattr(geo, self._task)(gt)

    def save_state(self, path: str | Path, *, write_meta: bool = False) -> None:
        """Persist fitted estimator state to ``path`` (a joblib pickle).

        Args:
            path: Destination file.
            write_meta: Also write a timestamped ``<path>.meta.json``
                sidecar (scikit-learn version, fit shape / sample count,
                UTC ``fit_timestamp``); off by default. See
                :meth:`GeoArrayEstimator.save_state`.
        """
        self._geo_estimator.save_state(path, write_meta=write_meta)
        self.estimator = self._geo_estimator.estimator
        self.state_path = str(path)

    def load_state(self, path: str | Path) -> None:
        """Load fitted estimator state from ``path``.

        Warning:
            The state file is a joblib pickle and unpickling can execute
            arbitrary code. Only load files you created or that come from
            a source you trust as much as the code you run.
        """
        self._geo_estimator.load_state(path)
        self.estimator = self._geo_estimator.estimator
        self.state_path = str(path)

    def get_config(self) -> dict[str, Any]:
        # Keys mirror the constructor; the estimator (a runtime object) is
        # summarised as a debug payload with the task it resolves to.
        params = (
            self.estimator.get_params(deep=False)
            if hasattr(self.estimator, "get_params")
            else {}
        )
        estimator_path = (
            f"{type(self.estimator).__module__}.{type(self.estimator).__name__}"
        )
        return {
            "estimator": {
                "class": estimator_path,
                # ``strict``: nested estimators (``Pipeline.steps``),
                # ``RandomState`` and callables become their ``repr`` and
                # non-finite floats ``'nan'`` / ``'inf'``, so the payload
                # always survives strict ``json.dumps`` with no key dropped.
                "params": jsonable(params, strict=True),
                "resolved_task": self._task,
            },
            "mode": self.mode,
            "sample_axes": jsonable(self.sample_axes),
            "feature_axes": jsonable(self.feature_axes),
            "fit_mode": self.fit_mode,
            "task": self.task,
            "nan_fit": self.nan_fit,
            "nan_transform": self.nan_transform,
            "impute_simple_strategy": self.impute_simple_strategy,
            "impute_knn_n_neighbors": self.impute_knn_n_neighbors,
            "impute_iterative_max_iter": self.impute_iterative_max_iter,
            "state_path": self.state_path,
            "out_band_names": self.out_band_names,
            "label_fill_value": self.label_fill_value,
        }

is_fitted property

Whether the wrapped estimator has been fitted (or loaded).

fit(gt)

Fit the wrapped estimator on gt (nan_fit strategy applies).

Returns:

Type Description
Self

This operator, for chaining.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
def fit(self, gt: GeoArray | np.ndarray) -> Self:
    """Fit the wrapped estimator on ``gt`` (``nan_fit`` strategy applies).

    Returns:
        This operator, for chaining.
    """
    self._geo_estimator.fit(gt)
    return self

load_state(path)

Load fitted estimator state from path.

Warning

The state file is a joblib pickle and unpickling can execute arbitrary code. Only load files you created or that come from a source you trust as much as the code you run.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
def load_state(self, path: str | Path) -> None:
    """Load fitted estimator state from ``path``.

    Warning:
        The state file is a joblib pickle and unpickling can execute
        arbitrary code. Only load files you created or that come from
        a source you trust as much as the code you run.
    """
    self._geo_estimator.load_state(path)
    self.estimator = self._geo_estimator.estimator
    self.state_path = str(path)

partial_fit(gt)

Update a streaming estimator with one more batch.

Returns:

Type Description
Self

This operator, for chaining.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
def partial_fit(self, gt: GeoArray | np.ndarray) -> Self:
    """Update a streaming estimator with one more batch.

    Returns:
        This operator, for chaining.
    """
    self._geo_estimator.partial_fit(gt)
    return self

predict(gt)

Apply estimator.predict without fitting.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
def predict(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Apply ``estimator.predict`` without fitting."""
    return self._geo_estimator.predict(gt)

save_state(path, *, write_meta=False)

Persist fitted estimator state to path (a joblib pickle).

Parameters:

Name Type Description Default
path str | Path

Destination file.

required
write_meta bool

Also write a timestamped <path>.meta.json sidecar (scikit-learn version, fit shape / sample count, UTC fit_timestamp); off by default. See :meth:GeoArrayEstimator.save_state.

False
Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
def save_state(self, path: str | Path, *, write_meta: bool = False) -> None:
    """Persist fitted estimator state to ``path`` (a joblib pickle).

    Args:
        path: Destination file.
        write_meta: Also write a timestamped ``<path>.meta.json``
            sidecar (scikit-learn version, fit shape / sample count,
            UTC ``fit_timestamp``); off by default. See
            :meth:`GeoArrayEstimator.save_state`.
    """
    self._geo_estimator.save_state(path, write_meta=write_meta)
    self.estimator = self._geo_estimator.estimator
    self.state_path = str(path)

transform(gt)

Apply estimator.transform without fitting.

Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Apply ``estimator.transform`` without fitting."""
    return self._geo_estimator.transform(gt)