ikpls.sklearn
This file contains the PLS class: a thin, scikit-learn-conformant
wrapper around ikpls’s NumPy PLS (ikpls.numpy.PLS), mirroring
sklearn.cross_decomposition.PLSRegression.
The wrapper performs ONLY input validation and plumbing; all PLS math is
delegated unchanged to the inner PLS, so the native fast API
(PLS.fit(X, Y, A) / PLS.predict returning all component counts /
PLS.cross_validate) is untouched. PLS exists to make the NumPy
IKPLS usable inside the scikit-learn ecosystem (Pipeline, cross_validate,
GridSearchCV).
PLS is conformant both as a regressor (predict / score) and
as a dimensionality-reducing transformer (transform / inverse_transform,
each supporting both X and Y), and exposes the standard PLSRegression
fitted attributes (x_weights_, y_weights_, x_loadings_,
y_loadings_, x_rotations_, y_rotations_, coef_, intercept_).
The vectorized
all-components prediction (shape (A, N, M)) remains available via
predict_all_components.
Author: Ole-Christian Galbo Engstrøm E-mail: ocge@foss.dk
Classes
|
scikit-learn-conformant transformer + regressor wrapping ikpls's PLS. |
- class ikpls.sklearn.PLS(n_components=1, algorithm=1, center_X=True, center_Y=True, scale_X=True, scale_Y=True, ddof=0, copy=True, dtype=<class 'numpy.float64'>)
Bases:
ClassNamePrefixFeaturesOutMixin,TransformerMixin,RegressorMixin,MultiOutputMixin,BaseEstimatorscikit-learn-conformant transformer + regressor wrapping ikpls’s PLS.
Mixin order mirrors sklearn’s own
_PLSbase (ClassNamePrefixFeaturesOutMixin, TransformerMixin, RegressorMixin, MultiOutputMixin, BaseEstimator):ClassNamePrefixFeaturesOutMixinprovidesget_feature_names_outfrom the fitted_n_features_outattribute (output names likepls0 .. pls{A-1}).TransformerMixinprovidesfit_transform(fit then transform) and sets thetransformer_tags.RegressorMixinprovides the regressor tags;scoreis overridden below for an explicit signature.MultiOutputMixinmarks the estimator as natively multi-output (target_tags.multi_output = True), matchingPLSRegression: PLS handles a 2DYwith multiple targets directly.BaseEstimatoris last, as required.
Parameters mirror
ikpls.numpy.PLSplusn_components(which maps to the innerA). The constructor stores parameters verbatim and performs no validation, as required by the sklearn estimator contract.- Parameters:
n_components (int, default=1) – Number of PLS components (latent variables). Maps to the inner
A.algorithm (int, default=1) – Improved Kernel PLS algorithm to use, either 1 or 2.
center_X (bool, default=True) – Whether to (training-set) center / scale the predictors / responses.
center_Y (bool, default=True) – Whether to (training-set) center / scale the predictors / responses.
scale_X (bool, default=True) – Whether to (training-set) center / scale the predictors / responses.
scale_Y (bool, default=True) – Whether to (training-set) center / scale the predictors / responses.
ddof (int, default=0) – Delta degrees of freedom for the (weighted) standard deviation used in scaling.
copy (bool, default=True) – Whether to copy the input arrays.
dtype (type, default=numpy.float64) – Floating point dtype used for the computations.
- x_weights_
The PLS weights for
X(innerPLS.W).- Type:
ndarray of shape (n_features, n_components)
- y_weights_
The PLS weights for
Y(innerPLS.C). In Improved Kernel PLS these equaly_loadings_, matchingsklearn.cross_decomposition.PLSRegression(whosey_weights_equals itsy_loadings_).- Type:
ndarray of shape (n_targets, n_components)
- x_loadings_
The PLS loadings for
X(innerPLS.P).- Type:
ndarray of shape (n_features, n_components)
- y_loadings_
The PLS loadings for
Y(innerPLS.Q).- Type:
ndarray of shape (n_targets, n_components)
- x_rotations_
The rotations mapping
Xdirectly to its scores (innerPLS.R).- Type:
ndarray of shape (n_features, n_components)
- y_rotations_
The rotations mapping
Ydirectly to its scores (innerPLS.R_Y). Exposed as a lazy property: it requires a pseudo-inverse that is computed (and cached) on first access rather than duringfit().- Type:
ndarray of shape (n_targets, n_components)
- coef_
Regression coefficients, matching
sklearn.cross_decomposition. PLSRegression.coef_. As in scikit-learn,predicteffectively centersX, sopredict(X) == (X - X_mean) @ coef_.T + intercept_(notX @ coef_.T + intercept_).- Type:
ndarray of shape (n_targets, n_features)
- intercept_
Intercept term. Following
sklearn.cross_decomposition.PLSRegression, this is the (weighted) mean ofYused for centering (zeros whencenter_Y=False).- Type:
ndarray of shape (n_targets,)
- max_stable_components_
Number of leading, numerically stable components determined during
fit()(from the innerikpls.numpy.PLS.max_stable_components). Equalsn_componentsunless a component is detected as unstable – when an X-weight norm underflows below machine epsilon (the X-Y cross-covariance is exhausted) or a component’s score normt^T tcollapses relative to the largest score norm seen so far (a null-space direction past the numerical rank ofX). Components past this count carry no predictive information: the coefficients are carried forward, sopredictwith more components returns the same result as withmax_stable_components_.- Type:
int
Notes
Improved Kernel PLS does not form a separate Y-weights matrix in its inner loop (it computes the Y loadings
y_loadings_directly). Followingsklearn.cross_decomposition.PLSRegression– whosey_weights_equals itsy_loadings_–y_weights_is exposed as an alias ofy_loadings_(innerPLS.C, which equals innerPLS.Q).For the fast native API – fitting once and predicting with every number of components
1..Ain a single call (shape(A, N, M)), and the built-in fastcross_validate– useikpls.numpy.PLSdirectly. This wrapper exposes the all-components prediction viapredict_all_components().Xscores andYscores can be obtained via the transform method.- fit(X: Any, y: Any | None, sample_weight: Any | None = None) PLS
Fit the PLS model.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Predictor variables.
y (array-like of shape (n_samples,) or (n_samples, n_targets)) – Response variables.
sample_weight (array-like of shape (n_samples,), optional) – Per-sample weights passed to the inner PLS.
- Returns:
self – The fitted estimator.
- Return type:
object
- fit_transform(X: Any, y: Any | None = None, **fit_params) Tuple[NDArray[floating], NDArray[floating]]
Fit the model, then return the training scores.
The default
TransformerMixin.fit_transformcallstransform(X)and thus returns only the X-scores. This override instead fits and returnstransform(X, y)– i.e. the(x_scores, y_scores)tuple, matchingikpls.numpy.PLS.fit_transformandsklearn.cross_decomposition.PLSRegression.fit_transform. It goes throughfit()(so a subclass overridingfitstill runs) and thentransform(), sofit_transformstays consistent withfit(...).transform(...).- Parameters:
X (array-like of shape (n_samples, n_features)) – Predictor variables.
y (array-like of shape (n_samples,) or (n_samples, n_targets)) – Response variables. Required (PLS is supervised).
**fit_params (dict) – Extra keyword arguments forwarded to
fit()(e.g.sample_weight).
- Returns:
(x_scores, y_scores) – The training X-scores and Y-scores, each of shape
(n_samples, n_components).- Return type:
tuple of ndarray
- predict(X: Any) NDArray[floating]
Predict using
n_componentscomponents.Returns an array of shape
(n_samples,)ifywas 1D at fit time, else(n_samples, n_targets).
- predict_all_components(X: Any) NDArray[floating]
Fast all-components prediction: returns shape
(A, N, M).Preserves ikpls’s vectorized feature of predicting with every number of components
1..Ain a single call.
- transform(X: Any, y: Any | None = None) NDArray[floating] | Tuple[NDArray[floating], NDArray[floating]]
Project
X(and optionallyY) onto the latent component space.Returns the X-scores
Tof shape(n_samples, n_components). Ifyis provided, also returns the Y-scores and yields(x_scores, y_scores), matching scikit-learn’sPLSRegression.transform(X, y). Delegates to the innerPLS.transform.- Parameters:
X (array-like of shape (n_samples, n_features)) – Predictor variables to project.
y (array-like of shape (n_samples,) or (n_samples, n_targets), optional) – Response variables to project. If given, Y-scores are also returned.
- Returns:
x_scores (ndarray of shape (n_samples, n_components)) – Returned when
yis None.(x_scores, y_scores) (tuple of ndarray) – Returned when
yis given;y_scoreshas shape(n_samples, n_components).
- inverse_transform(X: Any, y: Any | None = None) NDArray[floating] | Tuple[NDArray[floating], NDArray[floating]]
Map scores back to the original space.
Xis the X-scores (as returned bytransform()); the predictors are reconstructed via the X-loadings. Ify(the Y-scores) is given, the responses are also reconstructed and(X_hat, Y_hat)is returned, matching scikit-learn’sPLSRegression.inverse_transform(X, y). The round trip is exact only whenn_componentsequalsn_features(forX) /n_targets(forY); the sklearn transformer test-suite does not require an exact round trip for dimensionality-reducing transformers, so exposing this is safe.- Parameters:
X (array-like of shape (n_samples, n_components)) – X-scores produced by
transform().y (array-like of shape (n_samples, n_components), optional) – Y-scores produced by
transform().
- Returns:
X_original (ndarray of shape (n_samples, n_features_in_)) – Reconstructed predictors. Returned alone when
yis None.(X_original, Y_original) (tuple of ndarray) – Returned when
yis given;Y_originalhas shape(n_samples, n_targets).
- score(X: Any, y: Any, sample_weight: Any | None = None) float
Coefficient of determination R^2 of the prediction.
Predicts with
n_componentscomponents and scores againstywith scikit-learn’sr2_score(multioutput='uniform_average'), matching the regressorscorecontract, with optional per-samplesample_weight.- Parameters:
X (array-like of shape (n_samples, n_features)) – Test predictors.
y (array-like of shape (n_samples,) or (n_samples, n_targets)) – True responses for
X.sample_weight (array-like of shape (n_samples,), optional) – Per-sample weights.
- Returns:
score – The R^2 score.
- Return type:
float