Skip to content

FeatureArrayEstimator

sklearn_raster.FeatureArrayEstimator

FeatureArrayEstimator(wrapped_estimator: EstimatorType)

Bases: Generic[EstimatorType], BaseEstimator

An estimator wrapper with overriden methods for n-dimensional feature arrays.

Parameters:

Name Type Description Default
wrapped_estimator BaseEstimator

An sklearn-compatible estimator. Supported methods will be overriden to work with n-dimensional feature arrays. If the estimator is already fit, it will be reset and a warning will be raised.

required

Attributes:

Name Type Description
n_features_in_ int

The number of features used to fit the estimator.

n_targets_in_ int

The number of targets used to fit the estimator.

feature_names_in_ list of str

The names of features used to fit the estimator. If the estimator is fit without feature names, e.g. using a Numpy array, this is an empty list.

target_names_in_ list of str

The names of targets used to fit the estimator. If the estimator is fit without target names, e.g. using a Numpy array, this is an empty list.

Examples:

Instantiate an sklearn estimator, wrap it with a FeatureArrayEstimator, then fit as usual:

>>> from sklearn.neighbors import KNeighborsRegressor
>>> from sklearn_raster.datasets import load_swo_ecoplot
>>> X_img, X, y = load_swo_ecoplot(as_dataset=True)
>>> est = FeatureArrayEstimator(KNeighborsRegressor(n_neighbors=3)).fit(X, y)

Use the fitted FeatureArrayEstimator to generate predictions from raster data stored in Numpy or Xarray types:

>>> pred = est.predict(X_img)
>>> pred.PSME_COV.shape
(128, 128)
Source code in src/sklearn_raster/estimator.py
def __init__(self, wrapped_estimator: EstimatorType):
    self.wrapped_estimator = self._reset_estimator(wrapped_estimator)

Attributes

wrapped_estimator instance-attribute

wrapped_estimator = _reset_estimator(wrapped_estimator)

Functions

fit

fit(X, y=None, **kwargs) -> FeatureArrayEstimator[EstimatorType]

Fit an estimator from a training set (X, y).

Parameters:

Name Type Description Default
X array-like, sparse matrix

The training input samples.

array-like
y array-like of shape (n_samples,) or (n_samples, n_outputs)

The target values (class labels in classification, real numbers in regression). Single-output targets of shape (n_samples, 1) will be squeezed to shape (n_samples,) to allow consistent prediction across all estimators.

None
**kwargs dict

Additional keyword arguments passed to the estimator's fit method, e.g. sample_weight.

{}

Returns:

Name Type Description
self FeatureArrayEstimator

The wrapper around the fitted estimator.

Source code in src/sklearn_raster/estimator.py
@requires_implementation
def fit(self, X, y=None, **kwargs) -> FeatureArrayEstimator[EstimatorType]:
    """
    Fit an estimator from a training set (X, y).

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        The training input samples.
    y : array-like of shape (n_samples,) or (n_samples, n_outputs)
        The target values (class labels in classification, real numbers in
        regression). Single-output targets of shape (n_samples, 1) will be squeezed
        to shape (n_samples,) to allow consistent prediction across all estimators.
    **kwargs : dict
        Additional keyword arguments passed to the estimator's `fit` method, e.g.
        `sample_weight`.

    Returns
    -------
    self : FeatureArrayEstimator
        The wrapper around the fitted estimator.
    """
    if y is not None:
        # Squeeze extra y dimensions. This will convert from shape (n_samples, 1)
        # which causes inconsistent output shapes with different sklearn estimators,
        # to (n_samples,), which has a consistent output shape.
        y = y.squeeze()
    self.wrapped_estimator = self.wrapped_estimator.fit(X, y, **kwargs)

    self.n_features_in_: int = np.asarray(X).shape[-1]
    self.feature_names_in_ = self._get_names(X)
    self.n_targets_in_ = self._get_n_targets(y)
    self.target_names_in_ = self._get_names(y)

    return self

inverse_transform

inverse_transform(X: FeatureArrayType, *, skip_nodata: bool = True, nodata_input: NoDataType | MissingType = MISSING, nodata_output: float | int = nan, ensure_min_samples: int = 1, allow_cast: bool = False, check_output_for_nodata: bool = True, keep_attrs: bool = False, inner_thread_limit: int | None = 1, **inverse_transform_kwargs) -> FeatureArrayType

Apply the inverse transformation to n-dimensional X features.

Parameters:

Name Type Description Default
X Numpy or Xarray features

The n-dimensional input features. Array types should be in the shape (features, ...) while xr.Dataset should include features as variables. Features should correspond with those used to fit the estimator.

required
skip_nodata bool

If True, NoData and NaN values will be skipped during prediction. This speeds up processing of partially masked features, but may be incompatible if estimators expect a consistent number of input samples.

True
nodata_input float, sequence of floats, dict, or None

Values encoded as NoData in the input array to be masked in the output array. These can be defined with:

  • A single value broadcast to all features.
  • A sequence with one value for each feature.
  • A dict mapping from feature name or index to value.

A value of None disables masking for the selected feature. NaN is always treated as NoData and does not need to be specified. When nodata_input is not provided, it will be inferred if possible based on available metadata for the given array type, e.g. _FillValue attributes.

MISSING
nodata_output float or int or tuple

NoData samples in the input features will be replaced with this value in the output features. If the value does not fit the array dtype returned by the estimator, an error will be raised unless allow_cast is True. Defaults to np.nan.

nan
ensure_min_samples int

The minimum number of samples that should be passed to transform. If the array is fully masked and skip_nodata=True, dummy values (0) will be inserted to ensure this number of samples. The minimum supported number of samples depends on the estimator used. No effect if the array contains enough unmasked samples or if skip_nodata=False.

1
allow_cast bool

If True and the estimator output dtype is incompatible with the chosen nodata_output value, the output will be cast to the correct dtype instead of raising an error.

False
check_output_for_nodata bool

If True and nodata_output is not np.nan, a warning will be raised if the selected nodata_output value is returned by the estimator, as this may indicate a valid sample being masked.

True
keep_attrs bool

If True and the input is an Xarray object, the output will keep all attributes of the input features, unless they're set by the estimator (e.g. _FillValue or long_name). Note that some attributes (e.g. scale_factor) may become inaccurate, which is why they are dropped by default. The history attribute will always be kept. No effect if the input is a Numpy array.

False
inner_thread_limit int or None

The maximum number of threads allowed per Dask worker. Higher values can result in nested parallelism and oversubscription, which may cause slowdowns, stalls, or system crashes. Use caution when increasing the limit or disabling it by setting to None.

1
**inverse_transform_kwargs

Additional arguments passed to the estimator's inverse_transform method.

{}

Returns:

Type Description
Numpy or Xarray features

The inverse-transformed features. Array types will be in the shape (features, ...) while xr.Dataset will store features as variables.

Source code in src/sklearn_raster/estimator.py
@requires_implementation
@requires_fitted
def inverse_transform(
    self,
    X: FeatureArrayType,
    *,
    skip_nodata: bool = True,
    nodata_input: NoDataType | MissingType = MissingType.MISSING,
    nodata_output: float | int = np.nan,
    ensure_min_samples: int = 1,
    allow_cast: bool = False,
    check_output_for_nodata: bool = True,
    keep_attrs: bool = False,
    inner_thread_limit: int | None = 1,
    **inverse_transform_kwargs,
) -> FeatureArrayType:
    """
    Apply the inverse transformation to n-dimensional X features.

    Parameters
    ----------
    X : Numpy or Xarray features
        The n-dimensional input features. Array types should be in the shape
        (features, ...) while xr.Dataset should include features as variables.
        Features should correspond with those used to fit the estimator.
    skip_nodata : bool, default=True
        If True, NoData and NaN values will be skipped during prediction. This
        speeds up processing of partially masked features, but may be incompatible
        if estimators expect a consistent number of input samples.
    nodata_input : float, sequence of floats, dict, or None, optional
        Values encoded as NoData in the input array to be masked in the output
        array. These can be defined with:

        - A single value broadcast to all features.
        - A sequence with one value for each feature.
        - A dict mapping from feature name or index to value.

        A value of None disables masking for the selected feature. NaN is always
        treated as NoData and does not need to be specified. When `nodata_input` is
        not provided, it will be inferred if possible based on available metadata
        for the given array type, e.g. `_FillValue` attributes.
    nodata_output : float or int or tuple, optional
        NoData samples in the input features will be replaced with this value in the
        output features. If the value does not fit the array dtype returned by the
        estimator, an error will be raised unless `allow_cast` is True. Defaults to
        np.nan.
    ensure_min_samples : int, default 1
        The minimum number of samples that should be passed to `transform`. If the
        array is fully masked and `skip_nodata=True`, dummy values (0) will be
        inserted to ensure this number of samples. The minimum supported number of
        samples depends on the estimator used. No effect if the array contains
        enough unmasked samples or if `skip_nodata=False`.
    allow_cast : bool, default=False
        If True and the estimator output dtype is incompatible with the chosen
        `nodata_output` value, the output will be cast to the correct dtype instead
        of raising an error.
    check_output_for_nodata : bool, default True
        If True and `nodata_output` is not np.nan, a warning will be raised if the
        selected `nodata_output` value is returned by the estimator, as this may
        indicate a valid sample being masked.
    keep_attrs : bool, default=False
        If True and the input is an Xarray object, the output will keep all
        attributes of the input features, unless they're set by the estimator (e.g.
        `_FillValue` or `long_name`). Note that some attributes (e.g.
        `scale_factor`) may become inaccurate, which is why they are dropped by
        default. The `history` attribute will always be kept. No effect if the
        input is a Numpy array.
    inner_thread_limit : int or None, default=1
        The maximum number of threads allowed per Dask worker. Higher values can
        result in nested parallelism and oversubscription, which may cause
        slowdowns, stalls, or system crashes. Use caution when increasing the limit
        or disabling it by setting to `None`.
    **inverse_transform_kwargs
        Additional arguments passed to the estimator's `inverse_transform` method.

    Returns
    -------
    Numpy or Xarray features
        The inverse-transformed features. Array types will be in the shape
        (features, ...) while xr.Dataset will store features as variables.
    """
    features = FeatureArray.from_feature_array(X, nodata_input=nodata_input)

    ufunc = FeaturewiseUfunc(
        suppress_feature_name_warnings(self.wrapped_estimator.inverse_transform),
        outputs=[
            Output.from_1d(
                name="feature",
                size=self.n_features_in_,
                coords=self.feature_names_in_
                or generate_sequential_names(self.n_features_in_, "feature"),
                dtype=np.float64,
            )
        ],
    )
    return ufunc(
        features,
        skip_nodata=skip_nodata,
        nodata_output=nodata_output,
        ensure_min_samples=ensure_min_samples,
        allow_cast=allow_cast,
        check_output_for_nodata=check_output_for_nodata,
        nan_fill=0.0,
        keep_attrs=keep_attrs,
        inner_thread_limit=inner_thread_limit,
        **inverse_transform_kwargs,
    )

kneighbors

kneighbors(X: FeatureArrayType, *, n_neighbors: int | None = None, return_distance: Literal[True] = True, skip_nodata: bool = True, nodata_input: NoDataType | MissingType = MISSING, nodata_output: MaybeTuple[float | int] | None = None, ensure_min_samples: int = 1, allow_cast: bool = False, check_output_for_nodata: bool = True, keep_attrs: bool = False, inner_thread_limit: int | None = 1, **kneighbors_kwargs) -> tuple[FeatureArrayType, FeatureArrayType]
kneighbors(X: FeatureArrayType, *, n_neighbors: int | None = None, return_distance: Literal[False] = False, skip_nodata: bool = True, nodata_input: NoDataType | MissingType = MISSING, nodata_output: float | int | None = None, ensure_min_samples: int = 1, allow_cast: bool = False, check_output_for_nodata: bool = True, keep_attrs: bool = False, inner_thread_limit: int | None = 1, **kneighbors_kwargs) -> FeatureArrayType
kneighbors(X: FeatureArrayType, *, n_neighbors: int | None = None, return_distance: bool = True, skip_nodata: bool = True, nodata_input: NoDataType | MissingType = MISSING, nodata_output: MaybeTuple[float | int] | None = None, ensure_min_samples: int = 1, allow_cast: bool = False, check_output_for_nodata: bool = True, keep_attrs: bool = False, inner_thread_limit: int | None = 1, **kneighbors_kwargs) -> FeatureArrayType | tuple[FeatureArrayType, FeatureArrayType]

Find the K-neighbors of each sample in a feature array.

Returns indices of and distances to the neighbors for each pixel.

Parameters:

Name Type Description Default
X Numpy or Xarray features

The n-dimensional input features. Array types should be in the shape (features, ...) while xr.Dataset should include features as variables. Features should correspond with those used to fit the estimator.

required
n_neighbors int

Number of neighbors required for each sample. The default is the value passed to the wrapped estimator's constructor.

None
return_distance bool

If True, return distances to the neighbors of each sample. If False, return indices only.

True
skip_nodata bool

If True, NoData and NaN values will be skipped during prediction. This speeds up processing of partially masked features, but may be incompatible if estimators expect a consistent number of input samples.

True
nodata_input float, sequence of floats, dict, or None

Values encoded as NoData in the input array to be masked in the output array. These can be defined with:

  • A single value broadcast to all features.
  • A sequence with one value for each feature.
  • A dict mapping from feature name or index to value.

A value of None disables masking for the selected feature. NaN is always treated as NoData and does not need to be specified. When nodata_input is not provided, it will be inferred if possible based on available metadata for the given array type, e.g. _FillValue attributes.

MISSING
nodata_output float or int or tuple

NoData samples in the input features will be replaced with this value in the output targets. If the value does not fit the array dtype returned by the estimator, an error will be raised unless allow_cast is True. If return_distance is True, you can provide a tuple of two values to use for distances and indexes, respectively. Defaults to np.nan for the distance array and -2147483648 for the neighbor array.

None
ensure_min_samples int

The minimum number of samples that should be passed to kneighbors. If the array is fully masked and skip_nodata=True, dummy values (0) will be inserted to ensure this number of samples. The minimum supported number of samples depends on the estimator used. No effect if the array contains enough unmasked samples or if skip_nodata=False.

1
allow_cast bool

If True and the estimator output dtype is incompatible with the chosen nodata_output value, the output will be cast to the correct dtype instead of raising an error.

False
check_output_for_nodata bool

If True and nodata_output is not np.nan, a warning will be raised if the selected nodata_output value is returned by the estimator, as this may indicate a valid sample being masked.

True
keep_attrs bool

If True and the input is an Xarray object, the output will keep all attributes of the input features, unless they're set by the estimator (e.g. _FillValue or long_name). Note that some attributes (e.g. scale_factor) may become inaccurate, which is why they are dropped by default. The history attribute will always be kept. No effect if the input is a Numpy array.

False
inner_thread_limit int or None

The maximum number of threads allowed per Dask worker. Higher values can result in nested parallelism and oversubscription, which may cause slowdowns, stalls, or system crashes. Use caution when increasing the limit or disabling it by setting to None.

1
**kneighbors_kwargs

Additional arguments passed to the estimator's kneighbors method.

{}

Returns:

Name Type Description
neigh_dist Numpy or Xarray features

Array representing the lengths to neighbors, present if return_distance=True. Array types will be in the shape (neighbor, ...) while xr.Dataset will store neighbors as variables.

neigh_ind Numpy or Xarray features

Array representing the nearest neighbor indices in the population matrix. Array types will be in the shape (neighbor, ...) while xr.Dataset will store neighbors as variables.

Source code in src/sklearn_raster/estimator.py
@requires_implementation
@requires_fitted
def kneighbors(
    self,
    X: FeatureArrayType,
    *,
    n_neighbors: int | None = None,
    return_distance: bool = True,
    skip_nodata: bool = True,
    nodata_input: NoDataType | MissingType = MissingType.MISSING,
    nodata_output: MaybeTuple[float | int] | None = None,
    ensure_min_samples: int = 1,
    allow_cast: bool = False,
    check_output_for_nodata: bool = True,
    keep_attrs: bool = False,
    inner_thread_limit: int | None = 1,
    **kneighbors_kwargs,
) -> FeatureArrayType | tuple[FeatureArrayType, FeatureArrayType]:
    """
    Find the K-neighbors of each sample in a feature array.

    Returns indices of and distances to the neighbors for each pixel.

    Parameters
    ----------
    X : Numpy or Xarray features
        The n-dimensional input features. Array types should be in the shape
        (features, ...) while xr.Dataset should include features as variables.
        Features should correspond with those used to fit the estimator.
    n_neighbors : int, optional
        Number of neighbors required for each sample. The default is the value
        passed to the wrapped estimator's constructor.
    return_distance : bool, default=True
        If True, return distances to the neighbors of each sample. If False, return
        indices only.
    skip_nodata : bool, default=True
        If True, NoData and NaN values will be skipped during prediction. This
        speeds up processing of partially masked features, but may be incompatible
        if estimators expect a consistent number of input samples.
    nodata_input : float, sequence of floats, dict, or None, optional
        Values encoded as NoData in the input array to be masked in the output
        array. These can be defined with:

        - A single value broadcast to all features.
        - A sequence with one value for each feature.
        - A dict mapping from feature name or index to value.

        A value of None disables masking for the selected feature. NaN is always
        treated as NoData and does not need to be specified. When `nodata_input` is
        not provided, it will be inferred if possible based on available metadata
        for the given array type, e.g. `_FillValue` attributes.
    nodata_output : float or int or tuple, optional
        NoData samples in the input features will be replaced with this value in the
        output targets. If the value does not fit the array dtype returned by the
        estimator, an error will be raised unless `allow_cast` is True. If
        `return_distance` is True, you can provide a tuple of two values to use
        for distances and indexes, respectively. Defaults to np.nan for the distance
        array and -2147483648 for the neighbor array.
    ensure_min_samples : int, default 1
        The minimum number of samples that should be passed to `kneighbors`. If the
        array is fully masked and `skip_nodata=True`, dummy values (0) will be
        inserted to ensure this number of samples. The minimum supported number of
        samples depends on the estimator used. No effect if the array contains
        enough unmasked samples or if `skip_nodata=False`.
    allow_cast : bool, default=False
        If True and the estimator output dtype is incompatible with the chosen
        `nodata_output` value, the output will be cast to the correct dtype instead
        of raising an error.
    check_output_for_nodata : bool, default True
        If True and `nodata_output` is not np.nan, a warning will be raised if the
        selected `nodata_output` value is returned by the estimator, as this may
        indicate a valid sample being masked.
    keep_attrs : bool, default=False
        If True and the input is an Xarray object, the output will keep all
        attributes of the input features, unless they're set by the estimator (e.g.
        `_FillValue` or `long_name`). Note that some attributes (e.g.
        `scale_factor`) may become inaccurate, which is why they are dropped by
        default. The `history` attribute will always be kept. No effect if the
        input is a Numpy array.
    inner_thread_limit : int or None, default=1
        The maximum number of threads allowed per Dask worker. Higher values can
        result in nested parallelism and oversubscription, which may cause
        slowdowns, stalls, or system crashes. Use caution when increasing the limit
        or disabling it by setting to `None`.
    **kneighbors_kwargs
        Additional arguments passed to the estimator's `kneighbors` method.

    Returns
    -------
    neigh_dist : Numpy or Xarray features
        Array representing the lengths to neighbors, present if
        return_distance=True. Array types will be in the shape (neighbor, ...) while
        xr.Dataset will store neighbors as variables.
    neigh_ind : Numpy or Xarray features
        Array representing the nearest neighbor indices in the population matrix.
        Array types will be in the shape (neighbor, ...) while xr.Dataset will store
        neighbors as variables.
    """
    if return_distance is False and isinstance(nodata_output, tuple | list):
        msg = "`nodata_output` must be a scalar when `return_distance` is False."
        raise ValueError(msg)

    features = FeatureArray.from_feature_array(X, nodata_input=nodata_input)
    self._check_feature_names(features.feature_names)
    k = n_neighbors or cast(
        "int", getattr(self.wrapped_estimator, "n_neighbors", 5)
    )

    neighbor_dim = Dimension(
        name="neighbor", size=k, coords=generate_sequential_names(k, "neighbor")
    )
    dist_output_meta = Output(dims=[neighbor_dim], dtype=np.float64)
    idx_output_meta = Output(dims=[neighbor_dim], dtype=np.int32)
    ufunc = FeaturewiseUfunc(
        suppress_feature_name_warnings(self.wrapped_estimator.kneighbors),
        outputs=[dist_output_meta, idx_output_meta]
        if return_distance
        else [idx_output_meta],
    )
    return ufunc(
        features,
        skip_nodata=skip_nodata,
        nodata_output=nodata_output,
        ensure_min_samples=ensure_min_samples,
        allow_cast=allow_cast,
        check_output_for_nodata=check_output_for_nodata,
        nan_fill=0.0,
        keep_attrs=keep_attrs,
        inner_thread_limit=inner_thread_limit,
        # Arguments below are passed through to `kneighbors`
        return_distance=return_distance,
        n_neighbors=k,
        **kneighbors_kwargs,
    )

predict

predict(X: FeatureArrayType, *, skip_nodata: bool = True, nodata_input: NoDataType | MissingType = MISSING, nodata_output: float | int = nan, ensure_min_samples: int = 1, allow_cast: bool = False, check_output_for_nodata: bool = True, keep_attrs: bool = False, inner_thread_limit: int | None = 1, **predict_kwargs) -> FeatureArrayType

Predict target(s) for n-dimensional X features.

Parameters:

Name Type Description Default
X Numpy or Xarray features

The n-dimensional input features. Array types should be in the shape (features, ...) while xr.Dataset should include features as variables. Features should correspond with those used to fit the estimator.

required
skip_nodata bool

If True, NoData and NaN values will be skipped during prediction. This speeds up processing of partially masked arrays, but may be incompatible if estimators expect a consistent number of input samples.

True
nodata_input float, sequence of floats, dict, or None

Values encoded as NoData in the input array to be masked in the output array. These can be defined with:

  • A single value broadcast to all features.
  • A sequence with one value for each feature.
  • A dict mapping from feature name or index to value.

A value of None disables masking for the selected feature. NaN is always treated as NoData and does not need to be specified. When nodata_input is not provided, it will be inferred if possible based on available metadata for the given array type, e.g. _FillValue attributes.

MISSING
nodata_output float or int

NoData samples in the input features will be replaced with this value in the output targets. If the value does not fit the array dtype returned by the estimator, an error will be raised unless allow_cast is True.

np.nan
ensure_min_samples int

The minimum number of samples that should be passed to predict. If the array is fully masked and skip_nodata=True, dummy values (0) will be inserted to ensure this number of samples. The minimum supported number of samples depends on the estimator used. No effect if the array contains enough unmasked samples or if skip_nodata=False.

1
allow_cast bool

If True and the estimator output dtype is incompatible with the chosen nodata_output value, the output will be cast to the correct dtype instead of raising an error.

False
check_output_for_nodata bool

If True and nodata_output is not np.nan, a warning will be raised if the selected nodata_output value is returned by the estimator, as this may indicate a valid sample being masked.

True
keep_attrs bool

If True and the input is an Xarray object, the output will keep all attributes of the input features, unless they're set by the estimator (e.g. _FillValue or long_name). Note that some attributes (e.g. scale_factor) may become inaccurate, which is why they are dropped by default. The history attribute will always be kept. No effect if the input is a Numpy array.

False
inner_thread_limit int or None

The maximum number of threads allowed per Dask worker. Higher values can result in nested parallelism and oversubscription, which may cause slowdowns, stalls, or system crashes. Use caution when increasing the limit or disabling it by setting to None.

1
**predict_kwargs

Additional arguments passed to the estimator's predict method.

{}

Returns:

Type Description
Numpy or Xarray features

The predicted values. Array types will be in the shape (targets, ...) while xr.Dataset will store targets as variables.

Source code in src/sklearn_raster/estimator.py
@requires_implementation
@requires_fitted
def predict(
    self,
    X: FeatureArrayType,
    *,
    skip_nodata: bool = True,
    nodata_input: NoDataType | MissingType = MissingType.MISSING,
    nodata_output: float | int = np.nan,
    ensure_min_samples: int = 1,
    allow_cast: bool = False,
    check_output_for_nodata: bool = True,
    keep_attrs: bool = False,
    inner_thread_limit: int | None = 1,
    **predict_kwargs,
) -> FeatureArrayType:
    """
    Predict target(s) for n-dimensional X features.

    Parameters
    ----------
    X : Numpy or Xarray features
        The n-dimensional input features. Array types should be in the shape
        (features, ...) while xr.Dataset should include features as variables.
        Features should correspond with those used to fit the estimator.
    skip_nodata : bool, default=True
        If True, NoData and NaN values will be skipped during prediction. This
        speeds up processing of partially masked arrays, but may be incompatible if
        estimators expect a consistent number of input samples.
    nodata_input : float, sequence of floats, dict, or None, optional
        Values encoded as NoData in the input array to be masked in the output
        array. These can be defined with:

        - A single value broadcast to all features.
        - A sequence with one value for each feature.
        - A dict mapping from feature name or index to value.

        A value of None disables masking for the selected feature. NaN is always
        treated as NoData and does not need to be specified. When `nodata_input` is
        not provided, it will be inferred if possible based on available metadata
        for the given array type, e.g. `_FillValue` attributes.
    nodata_output : float or int, default np.nan
        NoData samples in the input features will be replaced with this value in the
        output targets. If the value does not fit the array dtype returned by the
        estimator, an error will be raised unless `allow_cast` is True.
    ensure_min_samples : int, default 1
        The minimum number of samples that should be passed to `predict`. If the
        array is fully masked and `skip_nodata=True`, dummy values (0) will be
        inserted to ensure this number of samples. The minimum supported number of
        samples depends on the estimator used. No effect if the array contains
        enough unmasked samples or if `skip_nodata=False`.
    allow_cast : bool, default=False
        If True and the estimator output dtype is incompatible with the chosen
        `nodata_output` value, the output will be cast to the correct dtype instead
        of raising an error.
    check_output_for_nodata : bool, default True
        If True and `nodata_output` is not np.nan, a warning will be raised if the
        selected `nodata_output` value is returned by the estimator, as this may
        indicate a valid sample being masked.
    keep_attrs : bool, default=False
        If True and the input is an Xarray object, the output will keep all
        attributes of the input features, unless they're set by the estimator (e.g.
        `_FillValue` or `long_name`). Note that some attributes (e.g.
        `scale_factor`) may become inaccurate, which is why they are dropped by
        default. The `history` attribute will always be kept. No effect if the
        input is a Numpy array.
    inner_thread_limit : int or None, default=1
        The maximum number of threads allowed per Dask worker. Higher values can
        result in nested parallelism and oversubscription, which may cause
        slowdowns, stalls, or system crashes. Use caution when increasing the limit
        or disabling it by setting to `None`.
    **predict_kwargs
        Additional arguments passed to the estimator's `predict` method.

    Returns
    -------
    Numpy or Xarray features
        The predicted values. Array types will be in the shape (targets, ...) while
        xr.Dataset will store targets as variables.
    """
    features = FeatureArray.from_feature_array(X, nodata_input=nodata_input)
    self._check_feature_names(features.feature_names)

    # Any estimator with an undefined type should fall back to floating
    # point for safety.
    estimator_type = getattr(self.wrapped_estimator, "_estimator_type", "")
    output_dtype = ESTIMATOR_OUTPUT_DTYPES.get(estimator_type, np.float64)

    ufunc = FeaturewiseUfunc(
        suppress_feature_name_warnings(self.wrapped_estimator.predict),
        outputs=[
            Output.from_1d(
                name="target",
                size=self.n_targets_in_,
                coords=self.target_names_in_
                or generate_sequential_names(self.n_targets_in_, "target"),
                dtype=output_dtype,
            )
        ],
    )
    return ufunc(
        features,
        skip_nodata=skip_nodata,
        nodata_output=nodata_output,
        ensure_min_samples=ensure_min_samples,
        allow_cast=allow_cast,
        check_output_for_nodata=check_output_for_nodata,
        nan_fill=0.0,
        keep_attrs=keep_attrs,
        inner_thread_limit=inner_thread_limit,
        **predict_kwargs,
    )

predict_proba

predict_proba(X: FeatureArrayType, *, skip_nodata: bool = True, nodata_input: NoDataType | MissingType = MISSING, nodata_output: float | int = nan, ensure_min_samples: int = 1, allow_cast: bool = False, check_output_for_nodata: bool = True, keep_attrs: bool = False, inner_thread_limit: int | None = 1, **predict_proba_kwargs) -> FeatureArrayType

Predict class probabilities for n-dimensional X features.

Parameters:

Name Type Description Default
X Numpy or Xarray features

The n-dimensional input features. Array types should be in the shape (features, ...) while xr.Dataset should include features as variables. Features should correspond with those used to fit the estimator.

required
skip_nodata bool

If True, NoData and NaN values will be skipped during prediction. This speeds up processing of partially masked arrays, but may be incompatible if estimators expect a consistent number of input samples.

True
nodata_input float, sequence of floats, dict, or None

Values encoded as NoData in the input array to be masked in the output array. These can be defined with:

  • A single value broadcast to all features.
  • A sequence with one value for each feature.
  • A dict mapping from feature name or index to value.

A value of None disables masking for the selected feature. NaN is always treated as NoData and does not need to be specified. When nodata_input is not provided, it will be inferred if possible based on available metadata for the given array type, e.g. _FillValue attributes.

MISSING
nodata_output float or int

NoData samples in the input features will be replaced with this value in the output targets. If the value does not fit the array dtype returned by the estimator, an error will be raised unless allow_cast is True.

np.nan
ensure_min_samples int

The minimum number of samples that should be passed to predict. If the array is fully masked and skip_nodata=True, dummy values (0) will be inserted to ensure this number of samples. The minimum supported number of samples depends on the estimator used. No effect if the array contains enough unmasked samples or if skip_nodata=False.

1
allow_cast bool

If True and the estimator output dtype is incompatible with the chosen nodata_output value, the output will be cast to the correct dtype instead of raising an error.

False
check_output_for_nodata bool

If True and nodata_output is not np.nan, a warning will be raised if the selected nodata_output value is returned by the estimator, as this may indicate a valid sample being masked.

True
keep_attrs bool

If True and the input is an Xarray object, the output will keep all attributes of the input features, unless they're set by the estimator (e.g. _FillValue or long_name). Note that some attributes (e.g. scale_factor) may become inaccurate, which is why they are dropped by default. The history attribute will always be kept. No effect if the input is a Numpy array.

False
inner_thread_limit int or None

The maximum number of threads allowed per Dask worker. Higher values can result in nested parallelism and oversubscription, which may cause slowdowns, stalls, or system crashes. Use caution when increasing the limit or disabling it by setting to None.

1
**predict_proba_kwargs

Additional arguments passed to the estimator's predict_proba method.

{}

Returns:

Type Description
Numpy or Xarray features

The predicted class probabilities. Array types will be in the shape (classes, ...) while xr.Dataset will store classes as variables.

Source code in src/sklearn_raster/estimator.py
@requires_implementation
@requires_fitted
@requires_attributes("classes_")
def predict_proba(
    self,
    X: FeatureArrayType,
    *,
    skip_nodata: bool = True,
    nodata_input: NoDataType | MissingType = MissingType.MISSING,
    nodata_output: float | int = np.nan,
    ensure_min_samples: int = 1,
    allow_cast: bool = False,
    check_output_for_nodata: bool = True,
    keep_attrs: bool = False,
    inner_thread_limit: int | None = 1,
    **predict_proba_kwargs,
) -> FeatureArrayType:
    """
    Predict class probabilities for n-dimensional X features.

    Parameters
    ----------
    X : Numpy or Xarray features
        The n-dimensional input features. Array types should be in the shape
        (features, ...) while xr.Dataset should include features as variables.
        Features should correspond with those used to fit the estimator.
    skip_nodata : bool, default=True
        If True, NoData and NaN values will be skipped during prediction. This
        speeds up processing of partially masked arrays, but may be incompatible if
        estimators expect a consistent number of input samples.
    nodata_input : float, sequence of floats, dict, or None, optional
        Values encoded as NoData in the input array to be masked in the output
        array. These can be defined with:

        - A single value broadcast to all features.
        - A sequence with one value for each feature.
        - A dict mapping from feature name or index to value.

        A value of None disables masking for the selected feature. NaN is always
        treated as NoData and does not need to be specified. When `nodata_input` is
        not provided, it will be inferred if possible based on available metadata
        for the given array type, e.g. `_FillValue` attributes.
    nodata_output : float or int, default np.nan
        NoData samples in the input features will be replaced with this value in the
        output targets. If the value does not fit the array dtype returned by the
        estimator, an error will be raised unless `allow_cast` is True.
    ensure_min_samples : int, default 1
        The minimum number of samples that should be passed to `predict`. If the
        array is fully masked and `skip_nodata=True`, dummy values (0) will be
        inserted to ensure this number of samples. The minimum supported number of
        samples depends on the estimator used. No effect if the array contains
        enough unmasked samples or if `skip_nodata=False`.
    allow_cast : bool, default=False
        If True and the estimator output dtype is incompatible with the chosen
        `nodata_output` value, the output will be cast to the correct dtype instead
        of raising an error.
    check_output_for_nodata : bool, default True
        If True and `nodata_output` is not np.nan, a warning will be raised if the
        selected `nodata_output` value is returned by the estimator, as this may
        indicate a valid sample being masked.
    keep_attrs : bool, default=False
        If True and the input is an Xarray object, the output will keep all
        attributes of the input features, unless they're set by the estimator (e.g.
        `_FillValue` or `long_name`). Note that some attributes (e.g.
        `scale_factor`) may become inaccurate, which is why they are dropped by
        default. The `history` attribute will always be kept. No effect if the
        input is a Numpy array.
    inner_thread_limit : int or None, default=1
        The maximum number of threads allowed per Dask worker. Higher values can
        result in nested parallelism and oversubscription, which may cause
        slowdowns, stalls, or system crashes. Use caution when increasing the limit
        or disabling it by setting to `None`.
    **predict_proba_kwargs
        Additional arguments passed to the estimator's `predict_proba` method.

    Returns
    -------
    Numpy or Xarray features
        The predicted class probabilities. Array types will be in the shape
        (classes, ...) while xr.Dataset will store classes as variables.
    """
    features = FeatureArray.from_feature_array(X, nodata_input=nodata_input)
    self._check_feature_names(features.feature_names)

    if self.n_targets_in_ > 1:
        msg = (
            "`predict_proba` does not currently support multi-output "
            "classification."
        )
        raise NotImplementedError(msg)

    ufunc = FeaturewiseUfunc(
        suppress_feature_name_warnings(self.wrapped_estimator.predict_proba),
        outputs=[
            Output.from_1d(
                name="label",
                size=len(self.wrapped_estimator.classes_),
                coords=list(self.wrapped_estimator.classes_),
                dtype=np.float64,
            )
        ],
    )
    return ufunc(
        features,
        skip_nodata=skip_nodata,
        nodata_output=nodata_output,
        ensure_min_samples=ensure_min_samples,
        allow_cast=allow_cast,
        check_output_for_nodata=check_output_for_nodata,
        nan_fill=0.0,
        keep_attrs=keep_attrs,
        inner_thread_limit=inner_thread_limit,
        **predict_proba_kwargs,
    )

transform

transform(X: FeatureArrayType, *, skip_nodata: bool = True, nodata_input: NoDataType | MissingType = MISSING, nodata_output: float | int = nan, ensure_min_samples: int = 1, allow_cast: bool = False, check_output_for_nodata: bool = True, keep_attrs: bool = False, inner_thread_limit: int | None = 1, **transform_kwargs) -> FeatureArrayType

Apply the transformation to n-dimensional X features.

Parameters:

Name Type Description Default
X Numpy or Xarray features

The n-dimensional input features. Array types should be in the shape (features, ...) while xr.Dataset should include features as variables. Features should correspond with those used to fit the estimator.

required
skip_nodata bool

If True, NoData and NaN values will be skipped during prediction. This speeds up processing of partially masked features, but may be incompatible if estimators expect a consistent number of input samples.

True
nodata_input float, sequence of floats, dict, or None

Values encoded as NoData in the input array to be masked in the output array. These can be defined with:

  • A single value broadcast to all features.
  • A sequence with one value for each feature.
  • A dict mapping from feature name or index to value.

A value of None disables masking for the selected feature. NaN is always treated as NoData and does not need to be specified. When nodata_input is not provided, it will be inferred if possible based on available metadata for the given array type, e.g. _FillValue attributes.

MISSING
nodata_output float or int or tuple

NoData samples in the input features will be replaced with this value in the output features. If the value does not fit the array dtype returned by the estimator, an error will be raised unless allow_cast is True. Defaults to np.nan.

nan
ensure_min_samples int

The minimum number of samples that should be passed to transform. If the array is fully masked and skip_nodata=True, dummy values (0) will be inserted to ensure this number of samples. The minimum supported number of samples depends on the estimator used. No effect if the array contains enough unmasked samples or if skip_nodata=False.

1
allow_cast bool

If True and the estimator output dtype is incompatible with the chosen nodata_output value, the output will be cast to the correct dtype instead of raising an error.

False
check_output_for_nodata bool

If True and nodata_output is not np.nan, a warning will be raised if the selected nodata_output value is returned by the estimator, as this may indicate a valid sample being masked.

True
keep_attrs bool

If True and the input is an Xarray object, the output will keep all attributes of the input features, unless they're set by the estimator (e.g. _FillValue or long_name). Note that some attributes (e.g. scale_factor) may become inaccurate, which is why they are dropped by default. The history attribute will always be kept. No effect if the input is a Numpy array.

False
inner_thread_limit int or None

The maximum number of threads allowed per Dask worker. Higher values can result in nested parallelism and oversubscription, which may cause slowdowns, stalls, or system crashes. Use caution when increasing the limit or disabling it by setting to None.

1
**transform_kwargs

Additional arguments passed to the estimator's transform method.

{}

Returns:

Type Description
Numpy or Xarray features

The transformed features. Array types will be in the shape (features, ...) while xr.Dataset will store features as variables, with the feature names based on the estimator's get_feature_names_out method.

Source code in src/sklearn_raster/estimator.py
@requires_implementation
@requires_fitted
@requires_attributes("get_feature_names_out")
def transform(
    self,
    X: FeatureArrayType,
    *,
    skip_nodata: bool = True,
    nodata_input: NoDataType | MissingType = MissingType.MISSING,
    nodata_output: float | int = np.nan,
    ensure_min_samples: int = 1,
    allow_cast: bool = False,
    check_output_for_nodata: bool = True,
    keep_attrs: bool = False,
    inner_thread_limit: int | None = 1,
    **transform_kwargs,
) -> FeatureArrayType:
    """
    Apply the transformation to n-dimensional X features.

    Parameters
    ----------
    X : Numpy or Xarray features
        The n-dimensional input features. Array types should be in the shape
        (features, ...) while xr.Dataset should include features as variables.
        Features should correspond with those used to fit the estimator.
    skip_nodata : bool, default=True
        If True, NoData and NaN values will be skipped during prediction. This
        speeds up processing of partially masked features, but may be incompatible
        if estimators expect a consistent number of input samples.
    nodata_input : float, sequence of floats, dict, or None, optional
        Values encoded as NoData in the input array to be masked in the output
        array. These can be defined with:

        - A single value broadcast to all features.
        - A sequence with one value for each feature.
        - A dict mapping from feature name or index to value.

        A value of None disables masking for the selected feature. NaN is always
        treated as NoData and does not need to be specified. When `nodata_input` is
        not provided, it will be inferred if possible based on available metadata
        for the given array type, e.g. `_FillValue` attributes.
    nodata_output : float or int or tuple, optional
        NoData samples in the input features will be replaced with this value in the
        output features. If the value does not fit the array dtype returned by the
        estimator, an error will be raised unless `allow_cast` is True. Defaults to
        np.nan.
    ensure_min_samples : int, default 1
        The minimum number of samples that should be passed to `transform`. If the
        array is fully masked and `skip_nodata=True`, dummy values (0) will be
        inserted to ensure this number of samples. The minimum supported number of
        samples depends on the estimator used. No effect if the array contains
        enough unmasked samples or if `skip_nodata=False`.
    allow_cast : bool, default=False
        If True and the estimator output dtype is incompatible with the chosen
        `nodata_output` value, the output will be cast to the correct dtype instead
        of raising an error.
    check_output_for_nodata : bool, default True
        If True and `nodata_output` is not np.nan, a warning will be raised if the
        selected `nodata_output` value is returned by the estimator, as this may
        indicate a valid sample being masked.
    keep_attrs : bool, default=False
        If True and the input is an Xarray object, the output will keep all
        attributes of the input features, unless they're set by the estimator (e.g.
        `_FillValue` or `long_name`). Note that some attributes (e.g.
        `scale_factor`) may become inaccurate, which is why they are dropped by
        default. The `history` attribute will always be kept. No effect if the
        input is a Numpy array.
    inner_thread_limit : int or None, default=1
        The maximum number of threads allowed per Dask worker. Higher values can
        result in nested parallelism and oversubscription, which may cause
        slowdowns, stalls, or system crashes. Use caution when increasing the limit
        or disabling it by setting to `None`.
    **transform_kwargs
        Additional arguments passed to the estimator's `transform` method.

    Returns
    -------
    Numpy or Xarray features
        The transformed features. Array types will be in the shape (features, ...)
        while xr.Dataset will store features as variables, with the feature names
        based on the estimator's `get_feature_names_out` method.
    """
    features = FeatureArray.from_feature_array(X, nodata_input=nodata_input)
    feature_names = self.wrapped_estimator.get_feature_names_out()
    self._check_feature_names(features.feature_names)

    ufunc = FeaturewiseUfunc(
        suppress_feature_name_warnings(self.wrapped_estimator.transform),
        outputs=[
            Output.from_1d(
                name="feature",
                size=len(feature_names),
                coords=list(feature_names),
                dtype=np.float64,
            )
        ],
    )
    return ufunc(
        features,
        skip_nodata=skip_nodata,
        nodata_output=nodata_output,
        ensure_min_samples=ensure_min_samples,
        allow_cast=allow_cast,
        check_output_for_nodata=check_output_for_nodata,
        nan_fill=0.0,
        keep_attrs=keep_attrs,
        inner_thread_limit=inner_thread_limit,
        **transform_kwargs,
    )