a
    �ù»jøE  ã                
   @   sN  d Z ddlZddlZddlmZ ddlZddlmZm	Z	 ddl
mZ ddlmZ ddlmZmZ dd	lmZmZmZmZ dd
lmZmZ ddlmZmZmZ ddlmZmZ ddl m!Z!m"Z" g d¢Z#edgdgdœdd�dd„ ƒZ$edgddgeedddd�dgeedddd�dgdgdœdd�dddddœdd„ƒZ%G dd„ deeeƒZ&dS )z8Isotonic regression for obtaining monotonic fit to data.é    N)ÚReal)ÚinterpolateÚoptimize)Ú	spearmanr)Úmetadata_routingé   )Ú'_inplace_contiguous_isotonic_regressionÚ_make_unique)ÚBaseEstimatorÚRegressorMixinÚTransformerMixinÚ_fit_context)Úcheck_arrayÚcheck_consistent_length)ÚIntervalÚ
StrOptionsÚvalidate_params)Úparse_versionÚsp_base_version)Ú_check_sample_weightÚcheck_is_fitted)Úcheck_increasingÚisotonic_regressionÚIsotonicRegressionz
array-like)ÚxÚyT©Zprefer_skip_nested_validationc           	      C   s    t | |ƒ\}}|dk}|dvrœt| ƒdkrœdt d| d|  ¡ }dt t| ƒd ¡ }t |d|  ¡}t |d|  ¡}t |¡t |¡krœt 	d¡ |S )	a?  Determine whether y is monotonically correlated with x.

    y is found increasing or decreasing with respect to x based on a Spearman
    correlation test.

    Parameters
    ----------
    x : array-like of shape (n_samples,)
            Training data.

    y : array-like of shape (n_samples,)
        Training target.

    Returns
    -------
    increasing_bool : boolean
        Whether the relationship is increasing or decreasing.

    Notes
    -----
    The Spearman correlation coefficient is estimated from the data, and the
    sign of the resulting estimate is used as the result.

    In the event that the 95% confidence interval based on Fisher transform
    spans zero, a warning is raised.

    References
    ----------
    Fisher transformation. Wikipedia.
    https://en.wikipedia.org/wiki/Fisher_transformation

    Examples
    --------
    >>> from sklearn.isotonic import check_increasing
    >>> x, y = [1, 2, 3, 4, 5], [2, 4, 6, 8, 10]
    >>> check_increasing(x, y)
    np.True_
    >>> y = [10, 8, 6, 4, 2]
    >>> check_increasing(x, y)
    np.False_
    r   )g      ð¿ç      ð?é   g      à?r   r   g\�Âõ(\ÿ?zwConfidence interval of the Spearman correlation coefficient spans zero. Determination of ``increasing`` may be suspect.)
r   ÚlenÚmathÚlogÚsqrtÚtanhÚnpÚsignÚwarningsÚwarn)	r   r   ÚrhoÚ_Zincreasing_boolÚFZF_seZrho_0Zrho_1© r+   ú6E:\soccer\ml_env\Lib\site-packages\sklearn/isotonic.pyr      s    3ÿr   Úboth©ÚclosedÚboolean)r   Úsample_weightÚy_minÚy_maxÚ
increasing©r1   r2   r3   r4   c                C   sò   t | ddtjtjgd�} ttdƒkrHtj| ||d�}tj|j	| j
d�} nh|rZtjdd… ntjddd… }tj| | | j
d�} t|| | j
d	d
�}t || ¡}t| |ƒ | | } |dusÀ|durî|du rÐtj }|du rÞtj}t | ||| ¡ | S )a0  Solve the isotonic regression model.

    Read more in the :ref:`User Guide <isotonic>`.

    Parameters
    ----------
    y : array-like of shape (n_samples,)
        The data.

    sample_weight : array-like of shape (n_samples,), default=None
        Weights on each point of the regression.
        If None, weight is set to 1 (equal weights).

    y_min : float, default=None
        Lower bound on the lowest predicted value (the minimum value may
        still be higher). If not set, defaults to -inf.

    y_max : float, default=None
        Upper bound on the highest predicted value (the maximum may still be
        lower). If not set, defaults to +inf.

    increasing : bool, default=True
        Whether to compute ``y_`` is increasing (if set to True) or decreasing
        (if set to False).

    Returns
    -------
    y_ : ndarray of shape (n_samples,)
        Isotonic fit of y.

    References
    ----------
    "Active set algorithms for isotonic regression; A unifying framework"
    by Michael J. Best and Nilotpal Chakravarti, section 3.

    Examples
    --------
    >>> from sklearn.isotonic import isotonic_regression
    >>> isotonic_regression([5, 3, 1, 2, 8, 10, 7, 9, 6, 4])
    array([2.75   , 2.75   , 2.75   , 2.75   , 7.33...,
           7.33..., 7.33..., 7.33..., 7.33..., 7.33...])
    Fr   )Ú	ensure_2dÚ
input_nameÚdtypez1.12.0)r   Úweightsr4   ©r8   NéÿÿÿÿT)r8   Úcopy)r   r$   Úfloat64Úfloat32r   r   r   r   Úasarrayr   r8   Zs_Úarrayr   Zascontiguousarrayr   ÚinfÚclip)r   r1   r2   r3   r4   ÚresÚorderr+   r+   r,   r   f   s&    7ÿ"
r   c                       sü   e Zd ZU dZdejiZdejiZee	dddd�dgee	dddd�dgde
dhƒge
h d£ƒgd	œZeed
< ddddd	œdd„Zdd„ Zdd„ Zd&dd„Zedd�d'dd„ƒZdd„ Zdd„ Zdd„ Zd(dd„Z‡ fd d!„Z‡ fd"d#„Z‡ fd$d%„Z‡  ZS ))r   aË  Isotonic regression model.

    Read more in the :ref:`User Guide <isotonic>`.

    .. versionadded:: 0.13

    Parameters
    ----------
    y_min : float, default=None
        Lower bound on the lowest predicted value (the minimum value may
        still be higher). If not set, defaults to -inf.

    y_max : float, default=None
        Upper bound on the highest predicted value (the maximum may still be
        lower). If not set, defaults to +inf.

    increasing : bool or 'auto', default=True
        Determines whether the predictions should be constrained to increase
        or decrease with `X`. 'auto' will decide based on the Spearman
        correlation estimate's sign.

    out_of_bounds : {'nan', 'clip', 'raise'}, default='nan'
        Handles how `X` values outside of the training domain are handled
        during prediction.

        - 'nan', predictions will be NaN.
        - 'clip', predictions will be set to the value corresponding to
          the nearest train interval endpoint.
        - 'raise', a `ValueError` is raised.

    Attributes
    ----------
    X_min_ : float
        Minimum value of input array `X_` for left bound.

    X_max_ : float
        Maximum value of input array `X_` for right bound.

    X_thresholds_ : ndarray of shape (n_thresholds,)
        Unique ascending `X` values used to interpolate
        the y = f(X) monotonic function.

        .. versionadded:: 0.24

    y_thresholds_ : ndarray of shape (n_thresholds,)
        De-duplicated `y` values suitable to interpolate the y = f(X)
        monotonic function.

        .. versionadded:: 0.24

    f_ : function
        The stepwise interpolating function that covers the input domain ``X``.

    increasing_ : bool
        Inferred value for ``increasing``.

    See Also
    --------
    sklearn.linear_model.LinearRegression : Ordinary least squares Linear
        Regression.
    sklearn.ensemble.HistGradientBoostingRegressor : Gradient boosting that
        is a non-parametric model accepting monotonicity constraints.
    isotonic_regression : Function to solve the isotonic regression model.

    Notes
    -----
    Ties are broken using the secondary method from de Leeuw, 1977.

    References
    ----------
    Isotonic Median Regression: A Linear Programming Approach
    Nilotpal Chakravarti
    Mathematics of Operations Research
    Vol. 14, No. 2 (May, 1989), pp. 303-308

    Isotone Optimization in R : Pool-Adjacent-Violators
    Algorithm (PAVA) and Active Set Methods
    de Leeuw, Hornik, Mair
    Journal of Statistical Software 2009

    Correctness of Kruskal's algorithms for monotone regression with ties
    de Leeuw, Psychometrica, 1977

    Examples
    --------
    >>> from sklearn.datasets import make_regression
    >>> from sklearn.isotonic import IsotonicRegression
    >>> X, y = make_regression(n_samples=10, n_features=1, random_state=41)
    >>> iso_reg = IsotonicRegression().fit(X, y)
    >>> iso_reg.predict([.1, .2])
    array([1.8628..., 3.7256...])
    ÚTNr-   r.   r0   Úauto>   rB   ÚnanÚraise©r2   r3   r4   Úout_of_boundsÚ_parameter_constraintsTrG   c                C   s   || _ || _|| _|| _d S ©NrI   )Úselfr2   r3   r4   rJ   r+   r+   r,   Ú__init__   s    zIsotonicRegression.__init__c                 C   s2   |j dks.|j dkr"|jd dks.d}t|ƒ‚d S )Nr   é   zKIsotonic regression input X should be a 1d array or 2d array with 1 feature)ÚndimÚshapeÚ
ValueError)rM   ÚXÚmsgr+   r+   r,   Ú_check_input_data_shape&  s    "ÿz*IsotonicRegression._check_input_data_shapec                    s>   | j dk}tˆ ƒdkr&‡ fdd„| _ntj|ˆ d|d�| _dS )zBuild the f_ interp1d function.rH   r   c                    s   ˆ   | j¡S rL   )ÚrepeatrQ   )r   ©r   r+   r,   Ú<lambda>4  ó    z-IsotonicRegression._build_f.<locals>.<lambda>Zlinear)ÚkindÚbounds_errorN)rJ   r   Úf_r   Zinterp1d)rM   rS   r   r[   r+   rW   r,   Ú_build_f.  s    
ÿzIsotonicRegression._build_fc           
   	      sV  |   |¡ | d¡}| jdkr,t||ƒ| _n| j| _t|||jd�}|dk}|| || ||   }}}t ||f¡‰ ‡ fdd„|||fD ƒ\}}}t	|||ƒ\}}}|}t
||| j| j| jd�}t |¡t |¡ | _| _|�rJtjt|ƒftd�}	t t |dd… |d	d
… ¡t |dd… |dd	… ¡¡|	dd…< ||	 ||	 fS ||fS d	S )z Build the y_ IsotonicRegression.r;   rF   r:   r   c                    s   g | ]}|ˆ  ‘qS r+   r+   )Ú.0r@   ©rD   r+   r,   Ú
<listcomp>L  rY   z/IsotonicRegression._build_y.<locals>.<listcomp>r5   r   NéþÿÿÿrO   )rU   Úreshaper4   r   Zincreasing_r   r8   r$   Zlexsortr	   r   r2   r3   ÚminÚmaxÚX_min_ÚX_max_Zonesr   ÚboolÚ
logical_orÚ	not_equal)
rM   rS   r   r1   Ztrim_duplicatesÚmaskZunique_XZunique_yZunique_sample_weightZ	keep_datar+   r_   r,   Ú_build_y:  s6    


û	4ÿzIsotonicRegression._build_yr   c                 C   s~   t ddd�}t|fdtjtjgdœ|¤Ž}t|fd|jdœ|¤Ž}t|||ƒ |  |||¡\}}|| | _| _	|  
||¡ | S )aæ  Fit the model using X, y as training data.

        Parameters
        ----------
        X : array-like of shape (n_samples,) or (n_samples, 1)
            Training data.

            .. versionchanged:: 0.24
               Also accepts 2d array with 1 feature.

        y : array-like of shape (n_samples,)
            Training target.

        sample_weight : array-like of shape (n_samples,), default=None
            Weights. If set to None, all weights will be set to 1 (equal
            weights).

        Returns
        -------
        self : object
            Returns an instance of self.

        Notes
        -----
        X is stored for future use, as :meth:`transform` needs X to interpolate
        new input data.
        F)Zaccept_sparser6   rS   )r7   r8   r   )Údictr   r$   r=   r>   r8   r   rk   ÚX_thresholds_Úy_thresholds_r]   )rM   rS   r   r1   Zcheck_paramsr+   r+   r,   Úfitk  s    ÿÿÿzIsotonicRegression.fitc                 C   sr   t | dƒr| jj}ntj}t||dd�}|  |¡ | d¡}| jdkrXt 	|| j
| j¡}|  |¡}| |j¡}|S )a‡  `_transform` is called by both `transform` and `predict` methods.

        Since `transform` is wrapped to output arrays of specific types (e.g.
        NumPy arrays, pandas DataFrame), we cannot make `predict` call `transform`
        directly.

        The above behaviour could be changed in the future, if we decide to output
        other type of arrays when calling `predict`.
        rm   F)r8   r6   r;   rB   )Úhasattrrm   r8   r$   r=   r   rU   rb   rJ   rB   re   rf   r\   Zastype)rM   rE   r8   rC   r+   r+   r,   Ú
_transform�  s    






zIsotonicRegression._transformc                 C   s
   |   |¡S )a†  Transform new data by linear interpolation.

        Parameters
        ----------
        T : array-like of shape (n_samples,) or (n_samples, 1)
            Data to transform.

            .. versionchanged:: 0.24
               Also accepts 2d array with 1 feature.

        Returns
        -------
        y_pred : ndarray of shape (n_samples,)
            The transformed data.
        ©rq   ©rM   rE   r+   r+   r,   Ú	transform»  s    zIsotonicRegression.transformc                 C   s
   |   |¡S )a%  Predict new data by linear interpolation.

        Parameters
        ----------
        T : array-like of shape (n_samples,) or (n_samples, 1)
            Data to transform.

        Returns
        -------
        y_pred : ndarray of shape (n_samples,)
            Transformed data.
        rr   rs   r+   r+   r,   ÚpredictÍ  s    zIsotonicRegression.predictc                 C   s,   t | dƒ | jj ¡ }tj|› d�gtd�S )aK  Get output feature names for transformation.

        Parameters
        ----------
        input_features : array-like of str or None, default=None
            Ignored.

        Returns
        -------
        feature_names_out : ndarray of str objects
            An ndarray with one string i.e. ["isotonicregression0"].
        r\   Ú0r:   )r   Ú	__class__Ú__name__Úlowerr$   r?   Úobject)rM   Zinput_featuresÚ
class_namer+   r+   r,   Úget_feature_names_outà  s    
z(IsotonicRegression.get_feature_names_outc                    s   t ƒ  ¡ }| dd¡ |S )z0Pickle-protocol - return state of the estimator.r\   N)ÚsuperÚ__getstate__Úpop©rM   Ústate©rw   r+   r,   r~   ñ  s    
zIsotonicRegression.__getstate__c                    s4   t ƒ  |¡ t| dƒr0t| dƒr0|  | j| j¡ dS )znPickle-protocol - set state of the estimator.

        We need to rebuild the interpolation function.
        rm   rn   N)r}   Ú__setstate__rp   r]   rm   rn   r€   r‚   r+   r,   rƒ   ø  s    zIsotonicRegression.__setstate__c                    s   t ƒ  ¡ }d|j_d|j_|S )NTF)r}   Ú__sklearn_tags__Z
input_tagsZone_d_arrayZtwo_d_array)rM   Útagsr‚   r+   r,   r„     s    
z#IsotonicRegression.__sklearn_tags__)T)N)N)rx   Ú
__module__Ú__qualname__Ú__doc__r   ZUNUSEDZ._IsotonicRegression__metadata_request__predictZ0_IsotonicRegression__metadata_request__transformr   r   r   rK   rl   Ú__annotations__rN   rU   r]   rk   r   ro   rq   rt   ru   r|   r~   rƒ   r„   Ú__classcell__r+   r+   r‚   r,   r   ·   s*   
^

ü
11
	r   )'rˆ   r    r&   Únumbersr   Únumpyr$   Zscipyr   r   Zscipy.statsr   Zsklearn.utilsr   Z	_isotonicr   r	   Úbaser
   r   r   r   Úutilsr   r   Zutils._param_validationr   r   r   Zutils.fixesr   r   Zutils.validationr   r   Ú__all__r   r   r   r+   r+   r+   r,   Ú<module>   sB   þû
EûøÿG