scikit-learn on xarray (xrops.learn)¶
The stack has one scikit-learn bridge: pipekit-array's Estimator, with to_rows / from_rows, which chooses samples by dim name on any carrier (geostack OP-O3).
On a single DataArray in a pipeline, use it directly.
xrops.learn adds what is xarray's own.
XarrayEstimator puts a Dataset's variables side by side as one feature table, each on its own grid, and fits a DataTree per node or pooled over its nodes.
Importing xrops.learn registers the .sklearn accessor on DataArray, Dataset and DataTree.
scikit-learn is imported when an estimator is fitted, so install the xrtoolz-ops[sklearn] extra.
XarrayEstimator
¶
XarrayEstimator(estimator: Any, *, sample_dims: Hashable | Sequence[Hashable], feature_dim: str | None = None, nan_policy: NanPolicy = 'propagate', method: str = 'transform', tree_mode: TreeMode = 'per_node')
Bases: Operator
A scikit-learn-style estimator fitted and applied on xarray objects.
The sample dims are chosen by name; every other dim of a variable is a feature. A Dataset's variables are put side by side as the columns of one table, so each may have its own feature grid. Outputs come back as:
- one value per sample (
predict): a DataArray over the sample dims; - the fitted features (a scaler,
inverse_transform): the input's variables on their own grids, as a DataArray or a Dataset; - a new output dim (PCA scores,
predict_proba): one DataArray withfeature_dimwhere the first variable's feature dims were.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
Any
|
Any object with scikit-learn's |
required |
sample_dims
|
Hashable | Sequence[Hashable]
|
The dim (or dims) whose entries are samples. |
required |
feature_dim
|
str | None
|
The name of a new output dim, for estimators whose
output columns are not the input's features ( |
None
|
nan_policy
|
NanPolicy
|
|
'propagate'
|
method
|
str
|
What calling the operator runs once fitted:
|
'transform'
|
tree_mode
|
TreeMode
|
What fitting on a DataTree means: |
'per_node'
|
Attributes:
| Name | Type | Description |
|---|---|---|
estimator_ |
Any
|
The fitted scikit-learn estimator ( |
estimators_ |
dict[str, XarrayEstimator] | None
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
An unknown |
Example
Decompose a (time, lat, lon) cube with PCA and recover the grid:
>>> import numpy as np
>>> import xarray as xr
>>> from sklearn.decomposition import PCA
>>> rng = np.random.default_rng(0)
>>> da = xr.DataArray(rng.normal(size=(8, 3, 4)), dims=("time", "lat", "lon"))
>>> est = XarrayEstimator(PCA(3), sample_dims="time", feature_dim="component")
>>> scores = est.fit(da).transform(da)
>>> scores.dims, scores.shape
(('time', 'component'), (8, 3))
>>> est.inverse_transform(scores).dims
('time', 'lat', 'lon')
>>> est.estimator_.components_.shape
(3, 12)
Scale every variable of a Dataset on its own grid:
>>> from sklearn.preprocessing import StandardScaler
>>> ds = xr.Dataset({"u": da, "v": da.isel(lat=0)})
>>> scaler = XarrayEstimator(StandardScaler(), sample_dims="time")
>>> out = scaler.fit(ds).transform(ds)
>>> {name: out[name].dims for name in out.data_vars}
{'u': ('time', 'lat', 'lon'), 'v': ('time', 'lon')}
Source code in packages/xrtoolz-ops/src/xrops/learn/_src/estimator.py
fit
¶
Learn the estimator from x (and y, for a supervised one).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
DataArray | Dataset | DataTree
|
A DataArray, Dataset or DataTree with the sample dims. |
required |
y
|
Any
|
Targets: a DataArray over the sample dims (plus at most one
target dim); for a DataTree, a DataTree with one variable
per node or |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
This operator, fitted. |
Raises:
| Type | Description |
|---|---|
ValueError
|
A variable lacks a sample dim, or ( |
Source code in packages/xrtoolz-ops/src/xrops/learn/_src/estimator.py
transform
¶
The estimator's transform of x, rebuilt as xarray.
predict
¶
One prediction per sample: a DataArray over the sample dims.
predict_proba
¶
Class probabilities per sample, along feature_dim ("class").
inverse_transform
¶
Map transform's output back to the fitted variables and grids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
DataArray | Dataset | DataTree
|
|
required |
Returns:
| Type | Description |
|---|---|
Any
|
The fitted variables on their grids; features dropped by |
Any
|
|
Source code in packages/xrtoolz-ops/src/xrops/learn/_src/estimator.py
fit_transform
¶
fit(x, y) then transform(x).
This is transform of the fitted estimator, not scikit-learn's
fit_transform; the two differ for estimators that refit inside
transform (NMF solves for W again, so its scores move by about
1e-3).