SplineTransformer (original) (raw)

class sklearn.preprocessing.SplineTransformer(n_knots=5, degree=3, *, knots='uniform', extrapolation='constant', include_bias=True, order='C', sparse_output=False)[source]#

Generate univariate B-spline bases for features.

Generate a new feature matrix consisting ofn_splines=n_knots + degree - 1 (n_knots - 1 forextrapolation="periodic") spline basis functions (B-splines) of polynomial order=`degree` for each feature.

In order to learn more about the SplineTransformer class go to:Time-related feature engineering

Read more in the User Guide.

Added in version 1.0.

Parameters:

n_knotsint, default=5

Number of knots of the splines if knots equals one of {‘uniform’, ‘quantile’}. Must be larger or equal 2. Ignored if knotsis array-like.

degreeint, default=3

The polynomial degree of the spline basis. Must be a non-negative integer.

knots{‘uniform’, ‘quantile’} or array-like of shape (n_knots, n_features), default=’uniform’

Set knot positions such that first knot <= features <= last knot.

extrapolation{‘error’, ‘constant’, ‘linear’, ‘continue’, ‘periodic’}, default=’constant’

If ‘error’, values outside the min and max values of the training features raises a ValueError. If ‘constant’, the value of the splines at minimum and maximum value of the features is used as constant extrapolation. If ‘linear’, a linear extrapolation is used. If ‘continue’, the splines are extrapolated as is, i.e. optionextrapolate=True in scipy.interpolate.BSpline. If ‘periodic’, periodic splines with a periodicity equal to the distance between the first and last knot are used. Periodic splines enforce equal function values and derivatives at the first and last knot. For example, this makes it possible to avoid introducing an arbitrary jump between Dec 31st and Jan 1st in spline features derived from a naturally periodic “day-of-year” input feature. In this case it is recommended to manually set the knot values to control the period.

include_biasbool, default=True

If False, then the last spline element inside the data range of a feature is dropped. As B-splines sum to one over the spline basis functions for each data point, they implicitly include a bias term, i.e. a column of ones. It acts as an intercept term in a linear models.

order{‘C’, ‘F’}, default=’C’

Order of output array in the dense case. 'F' order is faster to compute, but may slow down subsequent estimators.

sparse_outputbool, default=False

Will return sparse CSR matrix if set True else will return an array. This option is only available with scipy>=1.8.

Added in version 1.2.

Attributes:

**bsplines_**list of shape (n_features,)

List of BSplines objects, one for each feature.

**n_features_in_**int

The total number of input features.

**feature_names_in_**ndarray of shape (n_features_in_,)

Names of features seen during fit. Defined only when Xhas feature names that are all strings.

Added in version 1.0.

**n_features_out_**int

The total number of output features, which is computed asn_features * n_splines, where n_splines is the number of bases elements of the B-splines,n_knots + degree - 1 for non-periodic splines andn_knots - 1 for periodic ones. If include_bias=False, then it is onlyn_features * (n_splines - 1).

Notes

High degrees and a high number of knots can cause overfitting.

See examples/linear_model/plot_polynomial_interpolation.py.

Examples

import numpy as np from sklearn.preprocessing import SplineTransformer X = np.arange(6).reshape(6, 1) spline = SplineTransformer(degree=2, n_knots=3) spline.fit_transform(X) array([[0.5 , 0.5 , 0. , 0. ], [0.18, 0.74, 0.08, 0. ], [0.02, 0.66, 0.32, 0. ], [0. , 0.32, 0.66, 0.02], [0. , 0.08, 0.74, 0.18], [0. , 0. , 0.5 , 0.5 ]])

fit(X, y=None, sample_weight=None)[source]#

Compute knot positions of splines.

Parameters:

Xarray-like of shape (n_samples, n_features)

The data.

yNone

Ignored.

sample_weightarray-like of shape (n_samples,), default = None

Individual weights for each sample. Used to calculate quantiles ifknots="quantile". For knots="uniform", zero weighted observations are ignored for finding the min and max of X.

Returns:

selfobject

Fitted transformer.

fit_transform(X, y=None, **fit_params)[source]#

Fit to data, then transform it.

Fits transformer to X and y with optional parameters fit_paramsand returns a transformed version of X.

Parameters:

Xarray-like of shape (n_samples, n_features)

Input samples.

yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).

**fit_paramsdict

Additional fit parameters.

Returns:

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_feature_names_out(input_features=None)[source]#

Get output feature names for transformation.

Parameters:

input_featuresarray-like of str or None, default=None

Input features.

Returns:

feature_names_outndarray of str objects

Transformed feature names.

get_metadata_routing()[source]#

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:

routingMetadataRequest

A MetadataRequest encapsulating routing information.

get_params(deep=True)[source]#

Get parameters for this estimator.

Parameters:

deepbool, default=True

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

Returns:

paramsdict

Parameter names mapped to their values.

set_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$') → SplineTransformer[source]#

Request metadata passed to the fit method.

Note that this method is only relevant ifenable_metadata_routing=True (see sklearn.set_config). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

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.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside aPipeline. Otherwise it has no effect.

Parameters:

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

Metadata routing for sample_weight parameter in fit.

Returns:

selfobject

The updated object.

set_output(*, transform=None)[source]#

Set output container.

See Introducing the set_output APIfor an example on how to use the API.

Parameters:

transform{“default”, “pandas”, “polars”}, default=None

Configure output of transform and fit_transform.

Added in version 1.4: "polars" option was added.

Returns:

selfestimator instance

Estimator instance.

set_params(**params)[source]#

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:

**paramsdict

Estimator parameters.

Returns:

selfestimator instance

Estimator instance.

transform(X)[source]#

Transform each feature data to B-splines.

Parameters:

Xarray-like of shape (n_samples, n_features)

The data to transform.

Returns:

XBS{ndarray, sparse matrix} of shape (n_samples, n_features * n_splines)

The matrix of features, where n_splines is the number of bases elements of the B-splines, n_knots + degree - 1.