ó
\c           @   s´   d  d l  Z d  d l m Z m Z d d l 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 d d  Z d e e e f d     YZ d S(   i˙˙˙˙N(   t   optimizet   sparsei   (   t   BaseEstimatort   RegressorMixini   (   t   LinearModel(   t	   check_X_y(   t   check_consistent_length(   t   axis0_safe_slice(   t   safe_sparse_dotc   !      C   sč  t  j |  } | j \ } } | d |  j d k }	 |	 rH |  d }
 n  |  d } |  |  }  t j |  } | t | |   } |	 r | |
 8} n  t j |  } | | | k } | | } t j |  } | j d | } | | } t j |  } d | t j | |  | | | d } | | } | | | } t j | j	 |  } | | } |	 rst j
 | d  } n t j
 | d  } t | | |  } d | t | |  | | *t j |  } | | d k  } d | | <t | | |  } | | | } | | c  d | t | |  8*| | c  | d |  7*| | d <| d c | | d 8<| d c | | 8<|	 r˛d t j |  | | d <| d c d | t j |  8<n  | | | | }  |  | t j |  |   7}  |  | f S(	   sy  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, shape (n_samples, n_features)
        Input data.

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

    epsilon : float
        Robustness of the Huber estimator.

    alpha : float
        Regularization parameter.

    sample_weight : ndarray, shape (n_samples,), optional
        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.
    i   i    iţ˙˙˙i˙˙˙˙g       @i   g      đżg       Ŕ(   R   t   issparset   shapet   npt   sumR   t   abst   count_nonzerot   dott   Tt   zerosR   t	   ones_like(!   t   wt   Xt   yt   epsilont   alphat   sample_weightt   X_is_sparset   _t
   n_featurest   fit_interceptt	   interceptt   sigmat	   n_samplest   linear_losst   abs_linear_losst   outliers_maskt   outlierst   num_outlierst   n_non_outlierst   outliers_swt   n_sw_outlierst   outlier_losst   non_outlierst   weighted_non_outlierst   weighted_losst   squared_losst   gradt   X_non_outlierst   signed_outlierst   signed_outliers_maskt
   X_outlierst   sw_outlierst   loss(    (    s9   lib/python2.7/site-packages/sklearn/linear_model/huber.pyt   _huber_loss_and_gradient   s\    #






$t   HuberRegressorc           B   s5   e  Z d  Z d d d e e d d  Z d d  Z RS(   sł  Linear regression model that is robust to outliers.

    The Huber Regressor optimizes the squared loss for the samples where
    ``|(y - X'w) / sigma| < epsilon`` and the absolute loss for the samples
    where ``|(y - X'w) / sigma| > epsilon``, where w and 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.

    This makes sure that the loss function is not 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, greater than 1.0, 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.

    max_iter : int, default 100
        Maximum number of iterations that scipy.optimize.fmin_l_bfgs_b
        should run for.

    alpha : float, default 0.0001
        Regularization parameter.

    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-5
        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 Huber loss.

    intercept_ : float
        Bias.

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

    n_iter_ : int
        Number of iterations that fmin_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.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.linear_model import HuberRegressor, LinearRegression
    >>> from sklearn.datasets import make_regression
    >>> np.random.seed(0)
    >>> X, y, coef = make_regression(
    ...     n_samples=200, n_features=2, noise=4.0, coef=True, random_state=0)
    >>> X[:4] = np.random.uniform(10, 20, (4, 2))
    >>> y[:4] = np.random.uniform(10, 20, 4)
    >>> huber = HuberRegressor().fit(X, y)
    >>> huber.score(X, y) # doctest: +ELLIPSIS
    -7.284608623514573
    >>> 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...]

    References
    ----------
    .. [1] Peter J. Huber, Elvezio M. Ronchetti, Robust Statistics
           Concomitant scale estimates, pg 172
    .. [2] Art B. Owen (2006), A robust hybrid of lasso and ridge regression.
           http://statweb.stanford.edu/~owen/reports/hhu.pdf
    gő?id   g-Cëâ6?gńhăľřä>c         C   s:   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ d  S(   N(   R   t   max_iterR   t
   warm_startR   t   tol(   t   selfR   R6   R   R7   R   R8   (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/huber.pyt   __init__â   s    					c   	      C   s  t  | | d t d d g d t \ } } | d k	 rU t j |  } t | |  n t j |  } |  j d k  r t	 d |  j   n  |  j
 rČ t |  d  rČ t j |  j |  j |  j g f  } nJ |  j rî t j | j d d	  } n t j | j d d  } d | d
 <t j t j t j g | j d d f  } t j t j  j d | d
 d <t j t | d | | |  j |  j | f d |  j d |  j d | d d \ } } } | d d	 k răt	 d | d j d    n  t | d |  j  |  _  | d
 |  _ |  j r"| d |  _ n	 d |  _ | | j d  |  _ t j! | t" | |  j  |  j  } | |  j |  j k |  _# |  S(   s  Fit the model according to the given training data.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training vector, where n_samples in 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
        t   copyt   accept_sparset   csrt	   y_numericg      đ?s6   epsilon should be greater than or equal to 1.0, got %ft   coef_i   i   i˙˙˙˙i    i
   t   argst   maxitert   pgtolt   boundst   iprintt   warnflagsE   HuberRegressor convergence failed: l-BFGS-b solver terminated with %st   taskt   asciit   nitiţ˙˙˙g        N($   R   t   Falset   Truet   NoneR   t   arrayR   R   R   t
   ValueErrorR7   t   hasattrt   concatenateR?   t
   intercept_t   scale_R   R   R
   t   tilet   inft   finfot   float64t   epsR    t   fmin_l_bfgs_bR4   R   R6   R8   t   decodet   mint   n_iter_R   R   t	   outliers_(	   R9   R   R   R   t
   parametersRC   t   ft   dict_t   residual(    (    s9   lib/python2.7/site-packages/sklearn/linear_model/huber.pyt   fitë   sJ    '!	
,!			 N(   t   __name__t
   __module__t   __doc__RI   RJ   R:   RK   R`   (    (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/huber.pyR5   }   s   c	(   t   numpyR   t   scipyR    R   t   baseR   R   R   t   utilsR   R   R   t   utils.extmathR   RK   R4   R5   (    (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/huber.pyt   <module>   s   m