Regressogram¶
See component workflows for rationale and worked analysis, the user guide for concepts, and result schemas for diagnostic tables.
rgram.Regressogram¶
class rgram.Regressogram(
*,
binning='dist',
agg='mean',
ci=None,
n_bins=None,
bin_width=None,
max_bins=512,
min_samples_bin=5,
cv=5,
bin_candidates=None,
random_state=0,
extrapolation='clip',
unsupported='nan',
)Binned response summaries for one numeric feature and target.
Parameters¶
binning{'dist', 'width', 'none', 'int'}, default='dist'Binning strategy.
aggstr or callable, default='mean'Named reduction, Polars expression callable, or array_aggregation adapter. Every bin must produce one real numeric scalar; weights are never ignored.
cituple of aggregations or None, default=NoneExplicit lower/upper descriptive summaries. No intervals are computed by default. Use predict_interval for pointwise bootstrap inference.
n_binsint, str or None, default=NoneCount or selection rule for both dist and width. None means 'auto'. Rules: auto, cv, fd, scott, sturges, sqrt, rice. Dist auto uses a bounded cube-root count; width auto combines FD and Sturges. CV minimizes held-out regression MSE and requires full prediction support in every fold.
bin_widthfloat or None, default=NoneExplicit width in feature units; requires width binning and n_bins=None. The last bin may be shorter. Counts that exceed max_bins raise.
max_binsint, default=512Allocation guard. Automatic rules are capped; larger explicit counts raise.
min_samples_binint, default=5Bounds the default dist-auto count and generated CV candidates by n // value. This is a target occupancy, not a guarantee with ties or explicit counts.
cvint, splitter or iterable, default=5Used only for n_bins='cv'. Integers use shuffled KFold.
bin_candidatessequence of int or None, default=NoneCandidate counts for CV. Defaults to a bounded geometric grid.
random_stateint or None, default=0Seed for default CV splitting.
extrapolation{'clip', 'nan', 'raise'}, default='clip'Outside the training range, map to edge bins (with a warning), leave unsupported, or raise. Query values are never modified.
unsupported{'nan', 'raise'}, default='nan'Preserve missing estimates as NaN with a warning, or raise.
Attributes¶
X_ndarray of shape (n_samples,)Independent snapshot of original training features in row order.
y_ndarray of shape (n_samples,)Independent snapshot of original training responses in row order.
sample_weight_ndarray of shape (n_samples,)Original supplied weights, or ones if absent. Independent snapshot.
sample_weight_provided_boolWhether observation weights were supplied during fit.
feature_names_in_ndarray of shape (1,)Training feature name, present only for named input.
data_summary_dictData integrity, original dtype, fitted policy and computation summary.
n_features_in_intAlways one.
n_samples_in_intNumber of rows, including zero-weight rows.
selected_n_bins_int, str or NoneCount selected by internal CV, or original n_bins option without CV.
requested_n_bins_intNominal cell count after rule/cap selection but before tied boundaries are merged. Present for dist/width only. Sample/constant-x constraints can reduce an explicit request before this attribute is assigned.
n_bins_intNumber of fitted cells (empty cells may exist).
bin_edges_ndarrayInterior fitted boundaries for dist/width binning.
bin_width_float or NoneWidth for width binning; None for other strategies.
bins_polars.DataFrameOccupied bin estimates and original observation counts.
cv_results_dictError and coverage by candidate, available when n_bins='cv'.
See Also¶
- KernelSmoother: Alternative univariate response summary.
Examples¶
>>> from rgram import Regressogram
>>> model = Regressogram(n_bins=2).fit([0., 1., 2., 3.], [1., 3., 5., 7.])
>>> model.predict([0.5, 2.5])
array([2., 6.])
Methods¶
| Method | Purpose |
|---|---|
| fit | Fit one numeric feature and one numeric response. |
| fit_predict | Fit and evaluate at the original training feature values. |
| get_metadata_routing | Get metadata routing of this object. |
| get_params | Get parameters for this estimator. |
| predict | Evaluate the fitted bin summary at each query. |
| predict_diagnostics | Return bin assignment and support information for each query. |
| predict_interval | Compute pointwise paired-bootstrap confidence intervals for the curve. |
| regression_diagnostics | Inspect observed values, fitted values, and residuals in input order. |
| score | Return :ref:coefficient of determination <r2_score> on test data. |
| set_fit_request | Configure whether metadata should be requested to be passed to the fit method. |
| set_params | Set the parameters of this estimator. |
| set_score_request | Configure whether metadata should be requested to be passed to the score method. |
fit¶
rgram.Regressogram.fit(
X,
y,
*,
data=None,
sample_weight=None,
)Fit one numeric feature and one numeric response.
Parameters¶
Xarray-like of shape (n_samples,) or (n_samples, 1), or strNumeric feature, or its column name when data is supplied.
yarray-like of shape (n_samples,) or (n_samples, 1), or strNumeric response, or its column name when data is supplied.
datapandas.DataFrame, polars.DataFrame or polars.LazyFrame, default=NoneSource for named columns. Pandas columns are converted internally to Polars. Selected columns are snapshotted once; indices are ignored.
sample_weightarray-like of shape (n_samples,), default=NoneFinite nonnegative influence weights with positive total mass.
Returns¶
selfestimatorFitted estimator, with independent training snapshots.
Raises¶
ValueErrorFor incompatible shapes, unequal lengths, missing/non-finite values, invalid settings, or unsupported weighting conventions.
TypeErrorFor nonnumeric/complex input or invalid callback/data types.
Notes¶
Rows and duplicates are preserved. Unsorted input emits an advisory warning. A failed refit invalidates prediction access. Zero-weight rows still participate in feature-based bin or bandwidth selection. Normal fitting does not run CV; Regressogram(n_bins='cv') explicitly requests it.
Examples¶
>>> import numpy as np
>>> from rgram import Regressogram
>>> X = np.arange(10.0).reshape(-1, 1)
>>> model = Regressogram().fit(X, X[:, 0])
>>> model.predict(X).shape
(10,)
fit_predict¶
rgram.Regressogram.fit_predict(
X,
y,
*,
data=None,
sample_weight=None,
)Fit and evaluate at the original training feature values.
Parameters¶
Xarray-like or strOne training feature, or its column name when data is supplied.
yarray-like or strAligned numeric response, or its column name when data is supplied.
datapandas.DataFrame, polars.DataFrame or polars.LazyFrame, default=NoneSource for named columns.
sample_weightarray-like of shape (n_samples,), default=NoneObservation influence weights; see fit.
Returns¶
predictionndarray of shape (n_samples,)Predictions at original training rows, preserving their order.
Notes¶
Training predictions describe the fit, not held-out performance. Fit followed by predict evaluates new queries; predict_interval returns bootstrap bounds, and predict_diagnostics exposes descriptive endpoints.
get_metadata_routing¶
rgram.Regressogram.get_metadata_routing()Get metadata routing of this object.
Please check metadata routing guide on how the routing mechanism works.
Returns¶
routingMetadataRequestA
sklearn.utils.metadata_routing.MetadataRequestencapsulating routing information.
get_params¶
rgram.Regressogram.get_params(deep=True)Get parameters for this estimator.
Parameters¶
deepbool, default=TrueIf True, will return the parameters for this estimator and contained subobjects that are estimators.
Returns¶
paramsdictParameter names mapped to their values.
predict¶
rgram.Regressogram.predict(X)Evaluate the fitted bin summary at each query.
Parameters¶
Xarray-like of shape (n_queries,) or (n_queries, 1)Query feature values. Named inputs must match the fitted feature.
Returns¶
predictionndarray of shape (n_queries,)One estimate per query, in input order. Unsupported estimates are NaN unless the configured support policy raises.
Raises¶
sklearn.exceptions.NotFittedErrorIf no successful fit is available.
ValueErrorFor invalid queries, feature-name mismatch, or strict policies.
See Also¶
- predict_interval: Pointwise bootstrap confidence intervals.
- predict_diagnostics: Bin summaries, support and descriptive endpoints.
predict_diagnostics¶
rgram.Regressogram.predict_diagnostics(X)Return bin assignment and support information for each query.
Parameters¶
Xarray-like of shape (n_queries,) or (n_queries, 1)One query feature, with fitted feature name if named.
Returns¶
diagnosticspolars.DataFrameColumns: x, prediction, rgram_bin, n_samples, weight_sum, n_positive_weight, supported, in_training_range. With ci configured, summary_lower and summary_upper expose descriptive bin endpoints, not bootstrap confidence bounds. Each row corresponds to the query at the same position. Missing bin information is null; unsupported predictions are NaN unless a strict policy raises.
predict_interval¶
rgram.Regressogram.predict_interval(
X,
*,
confidence_level=0.95,
n_resamples=200,
random_state=None,
method='percentile',
resampling='iid',
groups=None,
block_size=None,
min_valid_fraction=1.0,
)Compute pointwise paired-bootstrap confidence intervals for the curve.
Parameters¶
Xarray-like of shape (n_queries,) or (n_queries, 1)Query locations; order and duplicates are preserved.
confidence_levelfloat, default=0.95Nominal interval level strictly between zero and one.
n_resamplesint, default=200Bootstrap refits, at least two. More draws improve Monte Carlo stability.
random_stateint or None, default=NoneSeed for resampling, independent of any estimator CV seed.
method{'percentile', 'basic'}, default='percentile'Bootstrap quantiles, or quantiles reflected around the original estimate.
resampling{'iid', 'groups', 'blocks'}, default='iid'Resample paired independent rows, whole independent groups, or contiguous moving blocks in original training order. No sorting occurs.
groupsarray-like of shape (n_samples_in_,) or None, default=NoneNonmissing group labels, required only for group resampling. At least two distinct groups are required.
block_sizeint or None, default=NoneBlock length from 2 to
n_samples_in_- 1, required only for blocks.min_valid_fractionfloat, default=1.0Fraction of draws that must support each query, in (0, 1]. At least two valid draws are always required. Lower fractions condition on valid draws.
Returns¶
intervalpolars.DataFrameColumns: x, prediction, lower, upper, n_valid, bootstrap_coverage. Insufficiently supported bounds are NaN. Queries are never dropped.
Raises¶
sklearn.exceptions.NotFittedErrorIf no successful fit is available.
ValueErrorFor invalid options, fewer than two training rows, invalid group/block inputs, or errors from the estimator's strict fit/prediction policies.
Notes¶
These are curve intervals, not prediction intervals or simultaneous bands. IID draws assume independent random-design rows. Group and block draws require appropriate independent groups or ordered dependence. Smoothing settings are held fixed; bin boundaries are relearned. Selection uncertainty and smoothing bias are not corrected. Memory includes n_resamples * n_queries draw values. A draw with no positive observation weight counts as unsupported. Other fit errors propagate. Explicit neighbor-only algorithms can reject unsorted draws.
regression_diagnostics¶
rgram.Regressogram.regression_diagnostics(X, y)Inspect observed values, fitted values, and residuals in input order.
Parameters¶
Xarray-like of shape (n_samples,) or (n_samples, 1)One evaluation feature. Named inputs must match the fitted feature.
yarray-like of shape (n_samples,) or (n_samples, 1)Observed response, aligned with x. May be training or held-out data.
Returns¶
diagnosticspolars.DataFrameColumns: x, observed, prediction, residual (observed minus prediction), supported (finite prediction). Unsupported rows remain present.
Raises¶
sklearn.exceptions.NotFittedErrorIf no successful fit is available.
ValueErrorFor invalid, misaligned inputs or strict prediction policies.
score¶
rgram.Regressogram.score(
X,
y,
sample_weight=None,
)Return coefficient of determination on test data.
The coefficient of determination, \(R^2\), is defined as
\((1 - \frac{u}{v})\), where \(u\) is the residual
sum of squares ((y_true - y_pred)** 2).sum() and \(v\)
is the total sum of squares ((y_true - y_true.mean()) ** 2).sum().
The best possible score is 1.0 and it can be negative (because the
model can be arbitrarily worse). A constant model that always predicts
the expected value of y, disregarding the input features, would get
a \(R^2\) score of 0.0.
Parameters¶
Xarray-like of shape (n_samples, n_features)Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape
(n_samples, n_samples_fitted), wheren_samples_fittedis the number of samples used in the fitting for the estimator.yarray-like of shape (n_samples,) or (n_samples, n_outputs)True values for
X.sample_weightarray-like of shape (n_samples,), default=NoneSample weights.
Returns¶
scorefloat\(R^2\) of
self.predict(X)w.r.t.y.
Notes¶
The \(R^2\) score used when calling score on a regressor uses
multioutput='uniform_average' from version 0.23 to keep consistent
with default value of sklearn.metrics.r2_score.
This influences the score method of all the multioutput
regressors (except for
sklearn.multioutput.MultiOutputRegressor).
set_fit_request¶
rgram.Regressogram.set_fit_request(
*,
data='$UNCHANGED$',
sample_weight='$UNCHANGED$',
)Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a :term:meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config).
Please check the metadata routing guide on how the routing
mechanism works.
The options for each parameter are:
-
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided. -
False: metadata is not requested and the meta-estimator will not pass it tofit. -
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it. -
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters¶
datastr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGEDMetadata routing for
dataparameter infit.sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGEDMetadata routing for
sample_weightparameter infit.
Returns¶
selfobjectThe updated object.
set_params¶
rgram.Regressogram.set_params(**params)Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as sklearn.pipeline.Pipeline). The latter have
parameters of the form <component>__<parameter> so that it's
possible to update each component of a nested object.
Parameters¶
**paramsdictEstimator parameters.
Returns¶
selfestimator instanceEstimator instance.
set_score_request¶
rgram.Regressogram.set_score_request(*, sample_weight='$UNCHANGED$')Configure whether metadata should be requested to be passed to the score method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a :term:meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config).
Please check the metadata routing guide on how the routing
mechanism works.
The options for each parameter are:
-
True: metadata is requested, and passed toscoreif provided. The request is ignored if metadata is not provided. -
False: metadata is not requested and the meta-estimator will not pass it toscore. -
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it. -
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters¶
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGEDMetadata routing for
sample_weightparameter inscore.
Returns¶
selfobjectThe updated object.
Implementation source: rgram.py.