Estimator API¶
The pyrox_nn.api subpackage exposes sklearn-style immutable estimator facades. Each estimator wraps a pyrox_nn model + the inference runners in pyrox.inference behind a one-call fit/predict ergonomic.
Base contracts¶
EstimatorBase
¶
Bases: Module
Immutable configuration for a probabilistic regression model.
Attributes:
| Name | Type | Description |
|---|---|---|
feature_cols |
tuple[str, ...]
|
Names of the input columns, in the order they should be packed into the design matrix. |
target_col |
str
|
Name of the target column. |
Source code in packages/pyrox-nn/src/pyrox_nn/api/_estimator.py
fit(df: pd.DataFrame, *, seed: PRNGKeyArray | int) -> FittedEstimator
¶
Fit and return a new FittedEstimator.
Subclasses override; EstimatorBase.fit raises.
Source code in packages/pyrox-nn/src/pyrox_nn/api/_estimator.py
FittedEstimator
¶
Bases: Module
Output of EstimatorBase.fit.
Subclasses store fitted parameters as equinox.Module
fields and implement predict. The base class enforces only
the immutable-PyTree contract.
Source code in packages/pyrox-nn/src/pyrox_nn/api/_estimator.py
predict(df: pd.DataFrame, *, quantiles: Sequence[float] | None = None) -> Float[Array, ' N'] | tuple[Float[Array, ' N'], tuple[Float[Array, ' N'], ...]]
¶
Predict targets for df.
Subclasses override; FittedEstimator.predict raises.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Inputs (must contain |
required |
quantiles
|
Sequence[float] | None
|
If given, return |
None
|
Source code in packages/pyrox-nn/src/pyrox_nn/api/_estimator.py
Bayesian Neural Field family¶
BNFEstimator
¶
Bases: EstimatorBase
MAP-fit Bayesian Neural Field estimator.
Composes the BNF layer (pyrox_nn.BayesianNeuralField) with
pandas-side preprocessing (pyrox_nn.preprocessing.fit_spatiotemporal)
and an ensemble-MAP inference loop
(pyrox.inference.ensemble_map).
Attributes:
| Name | Type | Description |
|---|---|---|
feature_cols |
tuple[str, ...]
|
Input columns (first one is time). |
target_col |
str
|
Target column. |
width |
int
|
Hidden MLP width. |
depth |
int
|
Hidden MLP depth. |
observation_model |
ObservationModel
|
|
seasonality_periods |
tuple[float, ...]
|
Periods for seasonal features. Empty ⇒ no seasonal features. |
num_seasonal_harmonics |
tuple[int, ...]
|
Harmonics per period. |
fourier_degrees |
tuple[int, ...]
|
Per-input dyadic Fourier degrees. Length must
match |
interactions |
tuple[tuple[int, int], ...]
|
Pair-index list for interaction features. |
encoder |
Callable[[Array], Array] | None
|
Optional single-example encoder |
encoder_cols |
tuple[int, ...] | None
|
Indices into |
timetype |
Literal['int', 'datetime']
|
|
freq |
str | None
|
Optional unit string for |
noise |
NoiseModel
|
|
sigma_obs |
float
|
Observation noise std \(\sigma_0\) when |
sigma_col |
str | None
|
Optional column of per-row noise stds \(\sigma_i > 0\), in target units. Each row's likelihood is \(\mathcal N(f(x_i), \sigma_i^2 + \sigma_0^2)\). The target is not rescaled by the estimator, so \(\sigma_i\) is used as given. |
ensemble_size |
int
|
Number of MAP ensemble members. |
num_epochs |
int
|
SGD-MAP iterations per member. |
learning_rate |
float
|
Adam learning rate. |
prior_weight |
float
|
|
Source code in packages/pyrox-nn/src/pyrox_nn/api/_bnf.py
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 | |
BNFEstimatorMLE
¶
Bases: BNFEstimator
BNF estimator with prior_weight=0 (MLE).
Source code in packages/pyrox-nn/src/pyrox_nn/api/_bnf.py
BNFEstimatorVI
¶
Bases: BNFEstimator
BNF estimator using mean-field VI via ensemble_vi.
Source code in packages/pyrox-nn/src/pyrox_nn/api/_bnf.py
FittedBNF
¶
Bases: FittedEstimator
Output of BNFEstimator.fit.
Attributes:
| Name | Type | Description |
|---|---|---|
config |
EstimatorBase
|
The |
fit_bundle |
SpatiotemporalFit
|
Pandas-side preprocessing record. |
params |
Any
|
Stacked per-ensemble-member parameter dict (each leaf
has a leading |
losses |
Float[Array, 'E T']
|
Per-member loss history, shape |
bnf_template |
BayesianNeuralField
|
The |
Source code in packages/pyrox-nn/src/pyrox_nn/api/_bnf.py
predict(df: pd.DataFrame, *, quantiles: Sequence[float] | None = None, predict_seed: int = 0, num_posterior_samples: int = 32) -> Float[Array, ' N'] | tuple[Float[Array, ' N'], tuple[Float[Array, ' N'], ...]]
¶
Posterior-predictive mean (and optional quantiles).
For MAP fits the per-member predictions are point estimates;
for VI fits we draw num_posterior_samples weight samples
per member from the variational guide.
The quantiles are those of the latent field plus the noise scale
\(\sigma_0\) (the fixed sigma_obs, or each member's or draw's
learned value): an equal-weight mixture of
\(\mathcal N(f_m(x), \sigma_{0,m}^2)\). Per-row \(\sigma_i\) from
sigma_col are not known at new points, so they are not added;
add \(\sigma_i^2\) yourself where you know it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Inputs. |
required |
quantiles
|
Sequence[float] | None
|
Optional levels. Returns |
None
|
predict_seed
|
int
|
PRNG seed for VI posterior sampling and quantile MC. |
0
|
num_posterior_samples
|
int
|
Per-member posterior draws used for VI predictive moments and quantile MC. |
32
|
Source code in packages/pyrox-nn/src/pyrox_nn/api/_bnf.py
Neural fields on arrays and xarray¶
NeuralFieldEstimator fits any Bayesian neural field, a callable that maps
(encoded) coordinates to a field while registering its weights as NumPyro
sites (BayesianSIREN, SphericalHarmonicFeatures, BayesianNeuralField,
…), with pyrox.inference.ensemble_map or ensemble_vi. It takes plain
arrays with optional per-row noise and a validity mask, so padded batches
fit exactly like their valid rows, or an xarray Dataset (fit_xarray,
pip install pyrox-nn[xarray]) whose missing cells are masked; datetimes
become days since the first timestamp (or time_origin=), and
FittedNeuralField.predict_xarray maps a Dataset's grid the same way.
Under MAP, pyrox_param sites and constrained latents (e.g. a LogNormal
prior) are optimised in unconstrained space against the constrained-space
density (no Jacobian), and
fields that draw numpyro.prng_key() are rejected (use inference="vi"). The BNF
estimators above are this estimator on a BayesianNeuralField.
import geonnax
from pyrox_nn import BayesianSIREN
from pyrox_nn.api import NeuralFieldEstimator
est = NeuralFieldEstimator(
model_fn=lambda: BayesianSIREN.init(441, 128, 1, depth=4, first_omega=1.0),
encoder=geonnax.SphericalHarmonicEncoder(l_max=20, input_mode="lonlat"),
noise="learned", ensemble_size=8, num_epochs=2000,
)
fitted = est.fit(X, y, sigma=sig, valid=mask, seed=0) # X (N, 2) lon/lat in radians
mean, (q05, q95) = fitted.predict(X_new, quantiles=(0.05, 0.95))
NeuralFieldEstimator
¶
Bases: Module
Fit any Bayesian neural field with ensemble MAP or VI.
The field is built by model_fn(): a callable mapping a batch of
(encoded) coordinates (N, D_enc) to the field (N,) or
(N, 1) while registering its weights as NumPyro sample sites,
usually a PyroxModule such as pyrox_nn.BayesianSIREN,
pyrox_nn.SphericalHarmonicFeatures or
pyrox_nn.BayesianNeuralField. Each ensemble member maximises (MAP) or
approximates (VI) the posterior of
where \(\gamma\) is encoder (identity when None), \(\sigma_i\) the
optional per-row noise passed to fit and \(\sigma_0\) set by
noise. Rows with valid[i] = False contribute nothing to the log
joint or its gradient, so padded batches fit exactly like their valid
rows alone.
Sites: the field's own, plus log_sigma_obs with
noise="learned"; the likelihood site y and the deterministic
sites f (and log_sigma_f with noise="heteroscedastic").
Attributes:
| Name | Type | Description |
|---|---|---|
model_fn |
Callable[[], Callable[[Array], Any]]
|
Zero-argument factory returning the field. Called once per
|
encoder |
Callable[[Array], Array] | None
|
Optional deterministic single-row encoder
\(\gamma: (D,) \to (D_\mathrm{enc},)\) applied to every row before
the field (vmapped), e.g.
|
noise |
NoiseModel
|
|
sigma_obs |
float
|
\(\sigma_0\) for |
ensemble_size |
int
|
Number of ensemble members \(E\). |
inference |
InferenceKind
|
|
num_epochs |
int
|
Optimiser steps per member (full batch). |
learning_rate |
float
|
Adam learning rate. |
prior_weight |
float
|
|
guide_factory |
Callable[[Callable], Any] | None
|
VI guide constructor taking the model function;
|
Examples:
>>> import jax.numpy as jnp
>>> import geonnax.encoders
>>> from pyrox_nn import BayesianSIREN
>>> from pyrox_nn.api import NeuralFieldEstimator
>>> enc = geonnax.encoders.SphericalHarmonicEncoder(
... l_max=3, input_mode="lonlat"
... )
>>> est = NeuralFieldEstimator(
... model_fn=lambda: BayesianSIREN.init(16, 32, 1, depth=3),
... encoder=enc, ensemble_size=2, num_epochs=10,
... )
>>> lonlat = jnp.stack([jnp.linspace(-3, 3, 20), jnp.zeros(20)], -1)
>>> fitted = est.fit(lonlat, jnp.sin(lonlat[:, 0]), seed=0)
>>> mean, (lo, hi) = fitted.predict(lonlat, quantiles=(0.05, 0.95))
>>> mean.shape, lo.shape
((20,), (20,))
Source code in packages/pyrox-nn/src/pyrox_nn/api/_field.py
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 | |
fit(X: Float[ArrayLike, 'N D'], y: Float[ArrayLike, ' N'], *, sigma: Float[ArrayLike, ' N'] | None = None, valid: ArrayLike | None = None, seed: PRNGKeyArray | int) -> FittedNeuralField
¶
Fit the ensemble on arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Float[ArrayLike, 'N D']
|
Coordinates of shape |
required |
y
|
Float[ArrayLike, ' N']
|
Targets of shape |
required |
sigma
|
Float[ArrayLike, ' N'] | None
|
Optional per-row noise stds \(\sigma_i\) of shape |
None
|
valid
|
ArrayLike | None
|
Optional boolean mask of shape |
None
|
seed
|
PRNGKeyArray | int
|
PRNG key or integer seed. |
required |
Returns:
| Type | Description |
|---|---|
FittedNeuralField
|
The fitted ensemble. |
Raises:
| Type | Description |
|---|---|
ValueError
|
On a bad configuration, mismatched shapes, a mask with no valid row, or non-finite values (or \(\sigma_i \le 0\)) on a valid row. |
Source code in packages/pyrox-nn/src/pyrox_nn/api/_field.py
fit_xarray(ds: Any, *, coords: Sequence[str], target: str, sigma: str | None = None, time_origin: Any = None, seed: PRNGKeyArray | int) -> FittedNeuralField
¶
Fit on an xarray Dataset (pip install pyrox-nn[xarray]).
Every variable named in coords, target and sigma (a
dimension, coordinate or data variable) is broadcast against the
others and flattened, in the target's dimension order, to one row
per grid point; coords become the columns of X in the order
given. Rows where any of them is missing (NaN, NaT) are masked out,
so a gappy grid needs no reshaping.
A datetime coordinate becomes float days since time_origin
(default: its earliest timestamp), so the column starts near 0
instead of at ~2·10⁴ days since 1970, which float32 would resolve
only to minutes and a SIREN would see as a huge frequency. A
timedelta coordinate becomes float days. The origins are stored on
the fit; FittedNeuralField.predict_xarray applies the same
mapping, and predict on arrays expects the same units.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Any
|
An |
required |
coords
|
Sequence[str]
|
Names of the input variables, e.g. |
required |
target
|
str
|
Name of the target variable. |
required |
sigma
|
str | None
|
Optional name of the per-row noise std variable. |
None
|
time_origin
|
Any
|
Optional reference time for every datetime
coordinate (anything |
None
|
seed
|
PRNGKeyArray | int
|
PRNG key or integer seed. |
required |
Returns:
| Type | Description |
|---|---|
FittedNeuralField
|
The fitted ensemble, which remembers |
FittedNeuralField
|
origins. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If xarray is not installed. |
ValueError
|
If a name is not a variable of |
Source code in packages/pyrox-nn/src/pyrox_nn/api/_field.py
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 | |
FittedNeuralField
¶
Bases: Module
Output of NeuralFieldEstimator.fit.
Attributes:
| Name | Type | Description |
|---|---|---|
config |
NeuralFieldEstimator
|
The |
field |
Any
|
The field returned by |
params |
Any
|
Stacked per-member parameters: a dict of the field's sites
with a leading |
losses |
Float[Array, 'E T']
|
Per-member loss history, shape |
has_sigma |
bool
|
Whether per-row \(\sigma_i\) were given at fit time. |
xarray_coords |
tuple[str, ...] | None
|
The |
time_origins |
tuple[str | None, ...] | None
|
Per coordinate, the reference time of a datetime
coordinate as an ISO string ( |
Source code in packages/pyrox-nn/src/pyrox_nn/api/_field.py
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 | |
predict(X: Float[ArrayLike, 'N D'], *, quantiles: Sequence[float] | None = None, predict_seed: int = 0, num_posterior_samples: int = 32) -> Prediction
¶
Posterior-predictive mean (and optional quantiles).
MAP members give one prediction each; VI members give
num_posterior_samples guide draws each. The quantiles are those
of the equal-weight mixture of \(\mathcal N(f_m(x), \sigma_{0,m}^2)\)
over members (or draws), estimated by Monte Carlo, with
\(\sigma_{0,m}\) the fixed sigma_obs, the member's learned value,
or its \(\sigma_m(x)\) when heteroscedastic. Per-row \(\sigma_i\) are not
known at new points, so they are not added.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Float[ArrayLike, 'N D']
|
Coordinates of shape |
required |
quantiles
|
Sequence[float] | None
|
Optional levels; then returns
|
None
|
predict_seed
|
int
|
PRNG seed for VI posterior draws and quantile MC. |
0
|
num_posterior_samples
|
int
|
Per-member draws for VI predictions and quantile MC. |
32
|
Returns:
| Type | Description |
|---|---|
Prediction
|
The mean of shape |
Source code in packages/pyrox-nn/src/pyrox_nn/api/_field.py
predict_xarray(ds: Any, *, quantiles: Sequence[float] | None = None, predict_seed: int = 0, num_posterior_samples: int = 32) -> Any
¶
Predict on the grid of an xarray Dataset, as fitted by fit_xarray.
The fitted coords are read from ds, broadcast against each
other and mapped to the fit's units (datetimes as days since the
stored origins); the result has their broadcast shape and
coordinates. A grid point with a missing coordinate predicts NaN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Any
|
An |
required |
quantiles
|
Sequence[float] | None
|
Optional levels, as in |
None
|
predict_seed
|
int
|
As in |
0
|
num_posterior_samples
|
int
|
As in |
32
|
Returns:
| Type | Description |
|---|---|
Any
|
The mean as an |
Any
|
with one |
Raises:
| Type | Description |
|---|---|
ValueError
|
If this fit did not come from |