Meta-estimator to regress on a transformed target.
Useful for applying a non-linear transformation to the target ``y`` in regression problems. This transformation can be given as a Transformer such as the QuantileTransformer or as a function and its inverse such as ``log`` and ``exp``.
The computation during ``fit`` is::
regressor.fit(X, func(y))
or::
regressor.fit(X, transformer.transform(y))
The computation during ``predict`` is::
inverse_func(regressor.predict(X))
or::
transformer.inverse_transform(regressor.predict(X))
Read more in the :ref:`User Guide <transformed_target_regressor>`.
Parameters ---------- regressor : object, default=LinearRegression() Regressor object such as derived from ``RegressorMixin``. This regressor will automatically be cloned each time prior to fitting.
transformer : object, default=None Estimator object such as derived from ``TransformerMixin``. Cannot be set at the same time as ``func`` and ``inverse_func``. If ``transformer`` is ``None`` as well as ``func`` and ``inverse_func``, the transformer will be an identity transformer. Note that the transformer will be cloned during fitting. Also, the transformer is restricting ``y`` to be a numpy array.
func : function, optional Function to apply to ``y`` before passing to ``fit``. Cannot be set at the same time as ``transformer``. The function needs to return a 2-dimensional array. If ``func`` is ``None``, the function used will be the identity function.
inverse_func : function, optional Function to apply to the prediction of the regressor. Cannot be set at the same time as ``transformer`` as well. The function needs to return a 2-dimensional array. The inverse function is used to return predictions to the same space of the original training labels.
check_inverse : bool, default=True Whether to check that ``transform`` followed by ``inverse_transform`` or ``func`` followed by ``inverse_func`` leads to the original targets.
Attributes ---------- regressor_ : object Fitted regressor.
transformer_ : object Transformer used in ``fit`` and ``predict``.
Examples -------- >>> import numpy as np >>> from sklearn.linear_model import LinearRegression >>> from sklearn.compose import TransformedTargetRegressor >>> tt = TransformedTargetRegressor(regressor=LinearRegression(), ... func=np.log, inverse_func=np.exp) >>> X = np.arange(4).reshape(-1, 1) >>> y = np.exp(2 * X).ravel() >>> tt.fit(X, y) TransformedTargetRegressor(...) >>> tt.score(X, y) 1.0 >>> tt.regressor_.coef_ array(2.
)
Notes ----- Internally, the target ``y`` is always converted into a 2-dimensional array to be used by scikit-learn transformers. At the time of prediction, the output will be reshaped to a have the same number of dimensions as ``y``.
See :ref:`examples/compose/plot_transformed_target.py <sphx_glr_auto_examples_compose_plot_transformed_target.py>`.