Skip to content
RgramRegressogram

Regressogram

See component workflows for rationale and worked analysis, the user guide for concepts, and result schemas for diagnostic tables.

rgram.Regressogram

[source]
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.

agg str 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.

ci tuple of aggregations or None, default=None

Explicit lower/upper descriptive summaries. No intervals are computed by default. Use predict_interval for pointwise bootstrap inference.

n_bins int, str or None, default=None

Count 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_width float or None, default=None

Explicit width in feature units; requires width binning and n_bins=None. The last bin may be shorter. Counts that exceed max_bins raise.

max_bins int, default=512

Allocation guard. Automatic rules are capped; larger explicit counts raise.

min_samples_bin int, default=5

Bounds 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.

cv int, splitter or iterable, default=5

Used only for n_bins='cv'. Integers use shuffled KFold.

bin_candidates sequence of int or None, default=None

Candidate counts for CV. Defaults to a bounded geometric grid.

random_state int or None, default=0

Seed 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_ bool

Whether observation weights were supplied during fit.

feature_names_in_ ndarray of shape (1,)

Training feature name, present only for named input.

data_summary_ dict

Data integrity, original dtype, fitted policy and computation summary.

n_features_in_ int

Always one.

n_samples_in_ int

Number of rows, including zero-weight rows.

selected_n_bins_ int, str or None

Count selected by internal CV, or original n_bins option without CV.

requested_n_bins_ int

Nominal 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_ int

Number of fitted cells (empty cells may exist).

bin_edges_ ndarray

Interior fitted boundaries for dist/width binning.

bin_width_ float or None

Width for width binning; None for other strategies.

bins_ polars.DataFrame

Occupied bin estimates and original observation counts.

cv_results_ dict

Error and coverage by candidate, available when n_bins='cv'.

See Also

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

[source]
rgram.Regressogram.fit(
    X,
    y,
    *,
    data=None,
    sample_weight=None,
)

Fit one numeric feature and one numeric response.

Parameters

X array-like of shape (n_samples,) or (n_samples, 1), or str

Numeric feature, or its column name when data is supplied.

y array-like of shape (n_samples,) or (n_samples, 1), or str

Numeric response, or its column name when data is supplied.

data pandas.DataFrame, polars.DataFrame or polars.LazyFrame, default=None

Source for named columns. Pandas columns are converted internally to Polars. Selected columns are snapshotted once; indices are ignored.

sample_weight array-like of shape (n_samples,), default=None

Finite nonnegative influence weights with positive total mass.

Returns

self estimator

Fitted estimator, with independent training snapshots.

Raises

ValueError

For incompatible shapes, unequal lengths, missing/non-finite values, invalid settings, or unsupported weighting conventions.

TypeError

For 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

[source]
rgram.Regressogram.fit_predict(
    X,
    y,
    *,
    data=None,
    sample_weight=None,
)

Fit and evaluate at the original training feature values.

Parameters

X array-like or str

One training feature, or its column name when data is supplied.

y array-like or str

Aligned numeric response, or its column name when data is supplied.

data pandas.DataFrame, polars.DataFrame or polars.LazyFrame, default=None

Source for named columns.

sample_weight array-like of shape (n_samples,), default=None

Observation influence weights; see fit.

Returns

prediction ndarray 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

[inherited API]
rgram.Regressogram.get_metadata_routing()

Get metadata routing of this object.

Please check metadata routing guide on how the routing mechanism works.

Returns

routing MetadataRequest

A sklearn.utils.metadata_routing.MetadataRequest encapsulating routing information.

get_params

[inherited API]
rgram.Regressogram.get_params(deep=True)

Get parameters for this estimator.

Parameters

deep bool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns

params dict

Parameter names mapped to their values.

predict

[source]
rgram.Regressogram.predict(X)

Evaluate the fitted bin summary at each query.

Parameters

X array-like of shape (n_queries,) or (n_queries, 1)

Query feature values. Named inputs must match the fitted feature.

Returns

prediction ndarray of shape (n_queries,)

One estimate per query, in input order. Unsupported estimates are NaN unless the configured support policy raises.

Raises

sklearn.exceptions.NotFittedError

If no successful fit is available.

ValueError

For invalid queries, feature-name mismatch, or strict policies.

See Also

predict_diagnostics

[source]
rgram.Regressogram.predict_diagnostics(X)

Return bin assignment and support information for each query.

Parameters

X array-like of shape (n_queries,) or (n_queries, 1)

One query feature, with fitted feature name if named.

Returns

diagnostics polars.DataFrame

Columns: 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

[source]
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

X array-like of shape (n_queries,) or (n_queries, 1)

Query locations; order and duplicates are preserved.

confidence_level float, default=0.95

Nominal interval level strictly between zero and one.

n_resamples int, default=200

Bootstrap refits, at least two. More draws improve Monte Carlo stability.

random_state int or None, default=None

Seed 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.

groups array-like of shape (n_samples_in_,) or None, default=None

Nonmissing group labels, required only for group resampling. At least two distinct groups are required.

block_size int or None, default=None

Block length from 2 to n_samples_in_ - 1, required only for blocks.

min_valid_fraction float, default=1.0

Fraction 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

interval polars.DataFrame

Columns: x, prediction, lower, upper, n_valid, bootstrap_coverage. Insufficiently supported bounds are NaN. Queries are never dropped.

Raises

sklearn.exceptions.NotFittedError

If no successful fit is available.

ValueError

For 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

[source]
rgram.Regressogram.regression_diagnostics(X, y)

Inspect observed values, fitted values, and residuals in input order.

Parameters

X array-like of shape (n_samples,) or (n_samples, 1)

One evaluation feature. Named inputs must match the fitted feature.

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

Observed response, aligned with x. May be training or held-out data.

Returns

diagnostics polars.DataFrame

Columns: x, observed, prediction, residual (observed minus prediction), supported (finite prediction). Unsupported rows remain present.

Raises

sklearn.exceptions.NotFittedError

If no successful fit is available.

ValueError

For invalid, misaligned inputs or strict prediction policies.

score

[inherited API]
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

X array-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), where n_samples_fitted is the number of samples used in the fitting for the estimator.

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

True values for X.

sample_weight array-like of shape (n_samples,), default=None

Sample weights.

Returns

score float

\(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

[inherited API]
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 to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • 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

data str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for data parameter in fit.

sample_weight str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for sample_weight parameter in fit.

Returns

self object

The updated object.

set_params

[inherited API]
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

**params dict

Estimator parameters.

Returns

self estimator instance

Estimator instance.

set_score_request

[inherited API]
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 to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • 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_weight str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for sample_weight parameter in score.

Returns

self object

The updated object.

Implementation source: rgram.py.