
    0Ph0                         d dl mZmZ d dlZd dlmZ ddl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 dd
lmZmZ ddlmZ ddZ G d dee	e          ZdS )    )IntegralRealN)optimize   )BaseEstimatorRegressorMixin_fit_context)axis0_safe_slice)Interval)safe_sparse_dot)_check_optimize_result)_check_sample_weightvalidate_data   )LinearModelc                 P   |j         \  }}|dz   | j         d         k    }|r| d         }	| d         }
| d|         } t          j        |          }|t          ||           z
  }|r||	z  }t          j        |          }|||
z  k    }||         }t          j        |          }|j         d         |z
  }||         }t          j        |          }d|z  t          j        ||z            z  |
|z  |dz  z  z
  }||          }||          |z  }t          j        |j        |          }||
z  }|rt          j        |dz             }nt          j        |dz             }t          || |           }d|
z  t          ||          z  |d|<   t          j
        |          }||         dk     }d||<   t          |||          }||         |z  }|d|xx         d|z  t          ||          z  z  cc<   |d|xx         |dz  | z  z  cc<   ||d<   |dxx         ||dz  z  z  cc<   |dxx         ||
z  z  cc<   |rEd	t          j        |          z  |
z  |d<   |dxx         d|z  t          j        |          z  z  cc<   ||
z  |z   |z   }||t          j        | |           z  z  }||fS )
a  Returns the Huber loss and the gradient.

    Parameters
    ----------
    w : ndarray, shape (n_features + 1,) or (n_features + 2,)
        Feature vector.
        w[:n_features] gives the coefficients
        w[-1] gives the scale factor and if the intercept is fit w[-2]
        gives the intercept factor.

    X : ndarray of shape (n_samples, n_features)
        Input data.

    y : ndarray of shape (n_samples,)
        Target vector.

    epsilon : float
        Robustness of the Huber estimator.

    alpha : float
        Regularization parameter.

    sample_weight : ndarray of shape (n_samples,), default=None
        Weight assigned to each sample.

    Returns
    -------
    loss : float
        Huber loss.

    gradient : ndarray, shape (len(w))
        Returns the derivative of the Huber loss with respect to each
        coefficient, intercept and the scale as a vector.
    r   r   Ng       @r   g      g       )shapenpsumr   abscount_nonzerodotTzerosr
   	ones_like) wXyepsilonalphasample_weight_
n_featuresfit_intercept	interceptsigma	n_sampleslinear_lossabs_linear_lossoutliers_maskoutliersnum_outliersn_non_outliersoutliers_swn_sw_outliersoutlier_lossnon_outliersweighted_non_outliersweighted_losssquared_lossgradX_non_outlierssigned_outlierssigned_outliers_mask
X_outlierssw_outlierslosss                                    [/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/linear_model/_huber.py_huber_loss_and_gradientr?      s>   F GMAzNagaj0M bE	bEE	+:+A}%%I oa+++K !y f[))O#go5M }-H#M22LWQZ,.N  .KF;''Mg{X5666
-
'1*
,	-  ~.L)=.9LHF02LAAM 5(L (x
Q''x
Q'' 'q=..IIINeo&;^LLL 	*
 l8,,O&}59,0O()!!]LAAJ.@K*w/+z*R*RSS 	*q( DHHHH
**HHHHHHu$$HHH  8"&!6777%?RRC'MBF;$7$777u|+l:DEBF1aLL  D:    c                        e Zd ZU dZ eeddd          g eeddd          g eeddd          gdgdg eeddd          gd	Zee	d
<   ddddddd	dZ
 ed          dd            Z fdZ xZS )HuberRegressora  L2-regularized linear regression model that is robust to outliers.

    The Huber Regressor optimizes the squared loss for the samples where
    ``|(y - Xw - c) / sigma| < epsilon`` and the absolute loss for the samples
    where ``|(y - Xw - c) / sigma| > epsilon``, where the model coefficients
    ``w``, the intercept ``c`` and the scale ``sigma`` are parameters
    to be optimized. The parameter `sigma` makes sure that if `y` is scaled up
    or down by a certain factor, one does not need to rescale `epsilon` to
    achieve the same robustness. Note that this does not take into account
    the fact that the different features of `X` may be of different scales.

    The Huber loss function has the advantage of not being heavily influenced
    by the outliers while not completely ignoring their effect.

    Read more in the :ref:`User Guide <huber_regression>`

    .. versionadded:: 0.18

    Parameters
    ----------
    epsilon : float, default=1.35
        The parameter epsilon controls the number of samples that should be
        classified as outliers. The smaller the epsilon, the more robust it is
        to outliers. Epsilon must be in the range `[1, inf)`.

    max_iter : int, default=100
        Maximum number of iterations that
        ``scipy.optimize.minimize(method="L-BFGS-B")`` should run for.

    alpha : float, default=0.0001
        Strength of the squared L2 regularization. Note that the penalty is
        equal to ``alpha * ||w||^2``.
        Must be in the range `[0, inf)`.

    warm_start : bool, default=False
        This is useful if the stored attributes of a previously used model
        has to be reused. If set to False, then the coefficients will
        be rewritten for every call to fit.
        See :term:`the Glossary <warm_start>`.

    fit_intercept : bool, default=True
        Whether or not to fit the intercept. This can be set to False
        if the data is already centered around the origin.

    tol : float, default=1e-05
        The iteration will stop when
        ``max{|proj g_i | i = 1, ..., n}`` <= ``tol``
        where pg_i is the i-th component of the projected gradient.

    Attributes
    ----------
    coef_ : array, shape (n_features,)
        Features got by optimizing the L2-regularized Huber loss.

    intercept_ : float
        Bias.

    scale_ : float
        The value by which ``|y - Xw - c|`` is scaled down.

    n_features_in_ : int
        Number of features seen during :term:`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

    n_iter_ : int
        Number of iterations that
        ``scipy.optimize.minimize(method="L-BFGS-B")`` has run for.

        .. versionchanged:: 0.20

            In SciPy <= 1.0.0 the number of lbfgs iterations may exceed
            ``max_iter``. ``n_iter_`` will now report at most ``max_iter``.

    outliers_ : array, shape (n_samples,)
        A boolean mask which is set to True where the samples are identified
        as outliers.

    See Also
    --------
    RANSACRegressor : RANSAC (RANdom SAmple Consensus) algorithm.
    TheilSenRegressor : Theil-Sen Estimator robust multivariate regression model.
    SGDRegressor : Fitted by minimizing a regularized empirical loss with SGD.

    References
    ----------
    .. [1] Peter J. Huber, Elvezio M. Ronchetti, Robust Statistics
           Concomitant scale estimates, p. 172
    .. [2] Art B. Owen (2006), `A robust hybrid of lasso and ridge regression.
           <https://artowen.su.domains/reports/hhu.pdf>`_

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.linear_model import HuberRegressor, LinearRegression
    >>> from sklearn.datasets import make_regression
    >>> rng = np.random.RandomState(0)
    >>> X, y, coef = make_regression(
    ...     n_samples=200, n_features=2, noise=4.0, coef=True, random_state=0)
    >>> X[:4] = rng.uniform(10, 20, (4, 2))
    >>> y[:4] = rng.uniform(10, 20, 4)
    >>> huber = HuberRegressor().fit(X, y)
    >>> huber.score(X, y)
    -7.284...
    >>> huber.predict(X[:1,])
    array([806.7200...])
    >>> linear = LinearRegression().fit(X, y)
    >>> print("True coefficients:", coef)
    True coefficients: [20.4923...  34.1698...]
    >>> print("Huber coefficients:", huber.coef_)
    Huber coefficients: [17.7906... 31.0106...]
    >>> print("Linear Regression coefficients:", linear.coef_)
    Linear Regression coefficients: [-1.9221...  7.0226...]
    g      ?Nleft)closedr   boolean        r!   max_iterr"   
warm_startr&   tol_parameter_constraintsg?d   g-C6?FTgh㈵>c                Z    || _         || _        || _        || _        || _        || _        d S NrG   )selfr!   rH   r"   rI   r&   rJ   s          r>   __init__zHuberRegressor.__init__  s3      
$*r@   )prefer_skip_nested_validationc                    t          | ||ddgdt          j        t          j        g          \  }}t	          ||          }| j        r8t          | d          r(t          j        | j        | j	        | j
        gf          }nQ| j        r#t          j        |j        d         dz             }n"t          j        |j        d         dz             }d|d<   t          j        t          j         t          j        g|j        d	         df          }t          j        t          j                  j        d
z  |d         d	<   t%          j        t(          |dd||| j        | j        |f| j        | j        dd|          }|j        }|j        dk    rt7          d|j        z            t;          d|| j                  | _        |d         | _
        | j        r|d         | _	        nd| _	        |d|j        d                  | _        t          j        |tA          || j                  z
  | j	        z
            }|| j
        | j        z  k    | _!        | S )a5  Fit the model according to the given training data.

        Parameters
        ----------
        X : array-like, 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, shape (n_samples,)
            Target vector relative to X.

        sample_weight : array-like, shape (n_samples,)
            Weight given to each sample.

        Returns
        -------
        self : object
            Fitted `HuberRegressor` estimator.
        FcsrT)copyaccept_sparse	y_numericdtypecoef_r   r   r   r   
   zL-BFGS-B)maxitergtoliprint)methodjacargsoptionsboundszEHuberRegressor convergence failed: l-BFGS-b solver terminated with %slbfgsr   rF   N)"r   r   float64float32r   rI   hasattrconcatenaterX   
intercept_scale_r&   r   r   tileinffinfoepsr   minimizer?   r!   r"   rH   rJ   xstatus
ValueErrormessager   n_iter_r   r   	outliers_)rO   r   r    r#   
parametersra   opt_resresiduals           r>   fitzHuberRegressor.fit  s5   *  ':rz*
 
 
1 -]A>>? 		wtW55 		dot{5S(TUUJJ! 6Xagaj1n55

Xagaj1n55
 JrN
 26'26*Z-=a-@!,DEE,,025r
1#$Qdj-@ $tx2NN
 
 
 Y
>QW/"   .gwNN n 	"(nDOO!DO!'!*-
6!oa<<<tNOO!DK$,$>>r@   c                 `    t                                                      }d|j        _        |S )NT)super__sklearn_tags__
input_tagssparse)rO   tags	__class__s     r>   rz   zHuberRegressor.__sklearn_tags__c  s'    ww''))!%r@   rN   )__name__
__module____qualname____doc__r   r   r   rK   dict__annotations__rP   r	   rw   rz   __classcell__)r~   s   @r>   rB   rB      s5        w wt HT3V<<<=Xh4???@(4D8889 k#sD8889$ $D        " \555L L L 65L\        r@   rB   rN   )numbersr   r   numpyr   scipyr   baser   r   r	   utils._maskr
   utils._param_validationr   utils.extmathr   utils.optimizer   utils.validationr   r   _baser   r?   rB    r@   r>   <module>r      s(   # " " " " " " "           > > > > > > > > > > * * * * * * . . . . . . + + + + + + 3 3 3 3 3 3 B B B B B B B B      k k k k\f f f f f[.- f f f f fr@   