`L i9ddlZddlZddlmZmZmZmZddlm Z ddl m Z ddl m Z ddlmZmZmZddlmZmZmZmZdd lmZdd lmZdd lmZd gZGd d eeZy)N) BaseEstimatorRegressorMixin _fit_contextclone)NotFittedError)LinearRegression)FunctionTransformer)Bunch_safe_indexing check_array)MetadataRouter MethodMapping_routing_enabledprocess_routing) HasMethods)get_tags)check_is_fittedTransformedTargetRegressorceZdZUdZeddgdgeddgedgedgdgdZeed< ddddd d d Z d Z e d dZ dZ fdZedZdZddZxZS)ra 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 :class:`~sklearn.preprocessing.QuantileTransformer` or as a function and its inverse such as `np.log` and `np.exp`. The computation during :meth:`fit` is:: regressor.fit(X, func(y)) or:: regressor.fit(X, transformer.transform(y)) The computation during :meth:`predict` is:: inverse_func(regressor.predict(X)) or:: transformer.inverse_transform(regressor.predict(X)) Read more in the :ref:`User Guide `. .. versionadded:: 0.20 Parameters ---------- regressor : object, default=None Regressor object such as derived from :class:`~sklearn.base.RegressorMixin`. This regressor will automatically be cloned each time prior to fitting. If `regressor is None`, :class:`~sklearn.linear_model.LinearRegression` is created and used. transformer : object, default=None Estimator object such as derived from :class:`~sklearn.base.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, default=None Function to apply to `y` before passing to :meth:`fit`. Cannot be set at the same time as `transformer`. If `func is None`, the function used will be the identity function. If `func` is set, `inverse_func` also needs to be provided. The function needs to return a 2-dimensional array. inverse_func : function, default=None Function to apply to the prediction of the regressor. Cannot be set at the same time as `transformer`. The inverse function is used to return predictions to the same space of the original training labels. If `inverse_func` is set, `func` also needs to be provided. The inverse function needs to return a 2-dimensional array. 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 :meth:`fit` and :meth:`predict`. n_features_in_ : int Number of features seen during :term:`fit`. Only defined if the underlying regressor exposes such an attribute when fit. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 See Also -------- sklearn.preprocessing.FunctionTransformer : Construct a transformer from an arbitrary callable. 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`. 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.]) For a more detailed example use case refer to :ref:`sphx_glr_auto_examples_compose_plot_transformed_target.py`. fitpredictN transformboolean regressor transformerfunc inverse_func check_inverse_parameter_constraintsT)rrrr cJ||_||_||_||_||_yNr)selfrrrrr s ]/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/compose/_target.py__init__z#TransformedTargetRegressor.__init__s*#& (*c ||j#|j |j td|jt |j|_n|j |j|j4|j(|jdnd\}}td|d|d|dt |j|jd |j |_|j jd |j j||jrtddtd |jddz}t||}|j j|}tj ||j j#|st%j&dt(yyy)zCheck transformer and fit transformer. Create the default transformer, fit it and make additional inverse check on a subset (optional). NzE'transformer' and functions 'func'/'inverse_func' cannot both be set.)rr)rrzWhen 'z' is provided, 'z' must also be provided. If zU is supposed to be the default, you need to explicitly pass it the identity function.T)rrvalidater default)rr zThe provided functions or transformer are not strictly inverse of each other. If you are sure you want to proceed regardless, set 'check_inverse=False')rrr ValueErrorr transformer_r r set_outputrslicemaxshaper rnpallcloseinverse_transformwarningswarn UserWarning)r$y lacking_paramexisting_param idx_selectedy_sely_sel_ts r%_fit_transformerz+TransformedTargetRegressor._fit_transformers    ' II !T%6%6%BW    ) %d&6&6 7D  %$*;*;*C !d&7&7&Cyy(-1. ~ !^,,<]OL((57MM !4YY!.."00 !D     ( (9 ( = a    tSAGGAJ"4D-EFL"1l3E''11%8G;;ud&7&7&I&I'&RS 6  T r'F)prefer_skip_nested_validationc |#td|jjdt|dddddd}|j|_|jdk(r|j d d}n|}|j||jj|}|jd k(r3|jddk(r!|j dk(r|jd }|jd |_ trt|d fi|}nt!t!|}|jj"||fi|j$j"t'|jdr|jj(|_|S)aFit the model according to the given training data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. **fit_params : dict - If `enable_metadata_routing=False` (default): Parameters directly passed to the `fit` method of the underlying regressor. - If `enable_metadata_routing=True`: Parameters safely routed to the `fit` method of the underlying regressor. .. versionchanged:: 1.6 See :ref:`Metadata Routing User Guide ` for more details. Returns ------- self : object Fitted estimator. zThis z= estimator requires y to be passed, but the target y is None.r9FTnumeric) input_name accept_sparseensure_all_finite ensure_2ddtypeallow_ndr+raxis) get_cloner)rrfeature_names_in_)r- __class____name__r ndim _training_dimreshaper?r.rr2squeeze_get_regressor regressor_rrr rrhasattrrN)r$Xr9 fit_paramsy_2dy_trans routed_paramss r%rzTransformedTargetRegressor.fitsp@ 9//01EE   " VV 66Q;99R#DD d###--d3 <<1 q!1Q!64;M;MQR;Roo1o-G---=  +D%F:FM!Ej,ABMAwF-*A*A*E*EF 4??$7 8%)__%F%FD " r'c t|trt|dfi|}ntt|}|jj |fi|j j }|jdk(r,|jj|jdd}n|jj|}|jdk(r3|jdk(r$|jddk(r|jd}|S)aPredict using the base regressor, applying inverse. The regressor is used to predict and the `inverse_func` or `inverse_transform` is applied before returning the prediction. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Samples. **predict_params : dict of str -> object - If `enable_metadata_routing=False` (default): Parameters directly passed to the `predict` method of the underlying regressor. - If `enable_metadata_routing=True`: Parameters safely routed to the `predict` method of the underlying regressor. .. versionchanged:: 1.6 See :ref:`Metadata Routing User Guide ` for more details. Returns ------- y_hat : ndarray of shape (n_samples,) Predicted values. r)rrMr+rIrrJ)rrrr rVrrrQr.r5rSrRr2rT)r$rXpredict_paramsr\pred pred_transs r%rz"TransformedTargetRegressor.predict,s6   +D)N~NM!E.,IJM&t&&qLM,C,C,K,KL 99>**<` on how the routing mechanism works. .. versionadded:: 1.6 Returns ------- routing : MetadataRouter A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating routing information. )ownerr)callercalleer)rmethod_mapping)rrOrPaddrUr)r$routers r%get_metadata_routingz/TransformedTargetRegressor.get_metadata_routingss] dnn&=&=>BB))+(? SeS , S )S 4 C   r'ct|j tS|rt|jS|jSr#)rr r)r$rLs r%rUz)TransformedTargetRegressor._get_regressors/ >> !#% %(1uT^^$Et~~Er'r#)F)rP __module__ __qualname____doc__rcallabler!dict__annotations__r&r?rrrrcpropertyrnrwrU __classcell__)rOs@r%rrsm`!%!34d;";/64 !4(# $D +  +9v&+J JX-^ . .,Fr')r6numpyr3baserrrr exceptionsr linear_modelr preprocessingr utilsr r r utils._metadata_requestsrrrrutils._param_validationr utils._tagsrutils.validationr__all__rr'r%rsQEE'+/66 1". ' (sFsFr'