a
    �ù»jy:  ã                   @   s¸   d dl Z d dlZddlmZmZmZmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZmZmZ ddlmZmZmZmZ dd	lmZ dd
lmZ ddlmZ dgZG dd„ deeƒZdS )é    Né   )ÚBaseEstimatorÚRegressorMixinÚ_fit_contextÚclone)ÚNotFittedError)ÚLinearRegression)ÚFunctionTransformer)ÚBunchÚ_safe_indexingÚcheck_array)ÚMetadataRouterÚMethodMappingÚ_routing_enabledÚprocess_routing)Ú
HasMethods)Úget_tags)Úcheck_is_fittedÚTransformedTargetRegressorc                       s®   e Zd ZU dZeddgƒdgedƒdgedgedgdgdœZeed< ddddd	d
œdd„Z	dd„ Z
edd�dd„ ƒZdd„ Z‡ fdd„Zedd„ ƒZdd„ Zddd„Z‡  ZS )r   a  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 <transformed_target_regressor>`.

    .. 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`.
    ÚfitÚpredictNÚ	transformÚboolean©Ú	regressorÚtransformerÚfuncÚinverse_funcÚcheck_inverseÚ_parameter_constraintsT)r   r   r   r   c                C   s"   || _ || _|| _|| _|| _d S ©Nr   )Úselfr   r   r   r   r   © r"   ú=E:\soccer\ml_env\Lib\site-packages\sklearn/compose/_target.pyÚ__init__’   s
    	z#TransformedTargetRegressor.__init__c                 C   s,  | j dur(| jdus| jdur(tdƒ‚n˜| j dur@t| j ƒ| _n€| jdurT| jdu sh| jdu rš| jdurš| jdu rvdnd\}}td|› d|› d|› d�ƒ‚t| j| jd	| jd
�| _| jjdd� | j 	|¡ | j�r(t
ddtd|jd d ƒƒ}t||ƒ}| j |¡}t || j |¡¡�s(t dt¡ dS )z¢Check 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.)r   r   )r   r   zWhen '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)r   r   Úvalidater   Údefault)r   é   r   é
   z—The provided functions or transformer are not strictly inverse of each other. If you are sure you want to proceed regardless, set 'check_inverse=False')r   r   r   Ú
ValueErrorr   Útransformer_r	   r   Z
set_outputr   ÚsliceÚmaxÚshaper   r   ÚnpZallcloseÚinverse_transformÚwarningsÚwarnÚUserWarning)r!   ÚyZlacking_paramZexisting_paramZidx_selectedZy_selZy_sel_tr"   r"   r#   Ú_fit_transformer¡   sR    
ÿÿÿ
ÿÿÿýÿÿü	
ùz+TransformedTargetRegressor._fit_transformerF)Zprefer_skip_nested_validationc              	   K   sü   |du rt d| jj› d�ƒ‚t|ddddddd�}|j| _|jd	krR| d
d	¡}n|}|  |¡ | j 	|¡}|jdkr�|j
d	 d	kr�|jd	d�}| jdd�| _tƒ r¸t| dfi |¤Ž}ntt|d�d�}| jj||fi |jj¤Ž t| jdƒrø| jj| _| S )a˜  Fit 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 <metadata_routing>` for
                more details.

        Returns
        -------
        self : object
            Fitted estimator.
        NzThis z= estimator requires y to be passed, but the target y is None.r3   FTÚnumeric)Z
input_nameZaccept_sparseZensure_all_finiteZ	ensure_2dZdtypeZallow_ndr'   éÿÿÿÿr   ©Zaxis)Ú	get_cloner   )r   ©r   Úfeature_names_in_)r)   Ú	__class__Ú__name__r   ÚndimÚ_training_dimÚreshaper4   r*   r   r-   ÚsqueezeÚ_get_regressorÚ
regressor_r   r   r
   r   r   Úhasattrr:   )r!   ÚXr3   Z
fit_paramsZy_2dZy_transÚrouted_paramsr"   r"   r#   r   Ü   s:     ÿù


zTransformedTargetRegressor.fitc                 K   s¨   t | ƒ tƒ r"t| dfi |¤Ž}ntt|d�d�}| jj|fi |jj¤Ž}|jdkrj| j 	| 
dd¡¡}n| j 	|¡}| jdkr¤|jdkr¤|jd dkr¤|jdd�}|S )a¥  Predict 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 <metadata_routing>`
                for more details.

        Returns
        -------
        y_hat : ndarray of shape (n_samples,)
            Predicted values.
        r   )r   r9   r'   r6   r   r7   )r   r   r   r
   rB   r   r   r=   r*   r/   r?   r>   r-   r@   )r!   rD   Zpredict_paramsrE   ÚpredZ
pred_transr"   r"   r#   r   ,  s     
ÿþýz"TransformedTargetRegressor.predictc                    s>   |   ¡ }tƒ  ¡ }d|j_t|ƒjj|j_t|ƒjj	|j_	|S )NT)
rA   ÚsuperÚ__sklearn_tags__Zregressor_tagsZ
poor_scorer   Z
input_tagsÚsparseZtarget_tagsZmulti_output)r!   r   Útags©r;   r"   r#   rH   [  s    
z+TransformedTargetRegressor.__sklearn_tags__c              
   C   sN   zt | ƒ W n8 tyD } z td | jj¡ƒ|‚W Y d}~n
d}~0 0 | jjS )z+Number of features seen during :term:`fit`.z*{} object has no n_features_in_ attribute.N)r   r   ÚAttributeErrorÚformatr;   r<   rB   Ún_features_in_)r!   Znfer"   r"   r#   rN   c  s    ÿÿüz)TransformedTargetRegressor.n_features_in_c                 C   s6   t | jjd�j|  ¡ tƒ jddd�jddd�d�}|S )aj  Get metadata routing of this object.

        Please check :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        .. versionadded:: 1.6

        Returns
        -------
        routing : MetadataRouter
            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
            routing information.
        )Úownerr   )ZcallerZcalleer   )r   Zmethod_mapping)r   r;   r<   ÚaddrA   r   )r!   Zrouterr"   r"   r#   Úget_metadata_routings  s    ÿþþz/TransformedTargetRegressor.get_metadata_routingc                 C   s$   | j d u rtƒ S |rt| j ƒS | j S r    )r   r   r   )r!   r8   r"   r"   r#   rA   ‰  s    
z)TransformedTargetRegressor._get_regressor)N)F)r<   Ú
__module__Ú__qualname__Ú__doc__r   Úcallabler   ÚdictÚ__annotations__r$   r4   r   r   r   rH   ÚpropertyrN   rQ   rA   Ú__classcell__r"   r"   rK   r#   r      s2   
p
û
 þù;þ
L/
)r0   Únumpyr.   Úbaser   r   r   r   Ú
exceptionsr   Zlinear_modelr   Zpreprocessingr	   Úutilsr
   r   r   Zutils._metadata_requestsr   r   r   r   Zutils._param_validationr   Zutils._tagsr   Zutils.validationr   Ú__all__r   r"   r"   r"   r#   Ú<module>   s   