
\c           @  s  d  Z  d d l m Z d d l m Z d d l Z d d l 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 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 m Z d	 d l m Z d	 d l m  Z  i e! d 6Z" e# e# d d d e$ e j% e j&  j' e$ d e$ e! e! d  Z( d e e f d     YZ) d e) f d     YZ* e! d  Z+ e# e$ d e! e$ e$ d e j% e j&  j' e! d 	 Z, d e) f d     YZ- d e- f d      YZ. d! e* f d"     YZ/ d S(#   st   
Least Angle Regression algorithm. See the documentation on the
Generalized Linear Model for a complete discussion.
i(   t   print_function(   t   logN(   t   linalgt   interpolate(   t   get_lapack_funcsi   (   t   LinearModeli   (   t   RegressorMixin(   t
   arrayfuncst   as_float_arrayt	   check_X_yt
   deprecated(   t   check_cv(   t   ConvergenceWarning(   t   Parallelt   delayed(   t   xrange(   t   string_typest   check_finitei  i    t   larc   A   
   C  s  | d k r% | r% t  j d t  n  |  j d } | j } t | |  } | r t j | d | f  } t j | d  } nD t j |  t j |  } } t j d g  t j d g  } } d \ } } t	   t j
 |  } } t j | d t j } t } t j | | f d |  j } t j d |  f  \ } } t d |  f  \ }  | d k sl| t k rd } | r|  j d
  }  qn t | t  r| d k s| t k r| t k s|  j d |  j d k rt j |  j |   } qd } n |	 r| j   } n  | d k r4t j |  j |  }! n | j   }! |
 r|
 d k r_t d  qt j j d  t j j   n  t j t j  j  }" t j t j  j! }# xt rc|! j r| rt j" |!  }$ n t j" t j# |!   }$ |! |$ }% | r|% }& qt j$ |%  }& n d }& | rg| | t j% f } | | } | | d t j% f } | | d } n  |& | | d <| d | |# k rt# | d |  |# k r| d k r| d | | d | d }' | |' | | | (n  | | d <n  | r| | | <n  Pn  | | k s| | k r#Pn  | se| rEt j& |%  | | <n t j' |%  | | <| |$ | }( }) | |! |$ |! d  \ |! |$ <|! d <| |( | |) | |) <| |( <|! }* |! d }! | d k rE| |  j |) |  j |(  \ |  j |) <|  j |( <| |  j |  d }+ t j |  j | |  j |  j  | | d |  f <n | | |( | |)  \ | |( <| |) <| | d d  |( f | d d  |) f  \ | d d  |( f <| d d  |) f <| | | f }+ | | d |  f | | d |  f <| rIt j( | d |  d |  f | | d |  f d d d d d t t) n  t j | | d |  f | | d |  f  }, t* t j+ t j# |+ |,   |  }- |- | | | f <|- d k  rt  j d | | | |- f t,  |* }! d |! d <| |! |$ |! d  \ |! |$ <|! d <qn  | j- | |  | d 7} |
 d k ret d | | d d | |& f  qen  | d k r| d k r| d | d k  rt  j d | | | | f t,  Pn  |  | d |  d |  f | |  d t \ }. }/ |. j d k r|. d k rd |. d <d }0 nd t j+ t j. |. | |    }0 t j/ |0  s	d }1 | d |  d |  f j   }2 x t j/ |0  s	|2 j0 d d | d  c d |1 | 7<|  |2 | |  d t \ }. }/ t* t j. |. | |   |  }3 d t j+ |3  }0 |1 d 7}1 qvWn  |. |0 9}. | d k r^	t j |  j |  j |.  }4 t j |  j | |4  }5 n+ t j | d |  | d  f j |.  }5 t1 j2 |& |! |0 |5 |"  }6 | r	t |6 |& |0  }7 n5 t1 j2 |& |! |0 |5 |"  }8 t |6 |8 |& |0  }7 t } | | |. |" }9 t1 j2 |9  }: |: |7 k  r
t j3 |9 |: k  d d d d  }; | |; | |; <| d k rw
|: }7 n  t } n  | d 7} | r,| | j d k r~ ~ ~ ~ d t* d | |  }< t j4 | | |< | f  } d | |< )t j4 | | |<  } d | |< )n  | | } | | d } n# | } | d | d <t j5 |  } | | |7 |. | | <|! |7 |5 8}! | r| d k rg  |; D]. }= t1 j6 | d |  d |  f |=  ^ q| d 8} |; | }( }) g  |; D] }= | j7 |=  ^ q}> | d k rx |; D]~ }= xu t8 |= |  D]d }1 | |  j |1 |  j |1 d  \ |  j |1 <|  j |1 d <| |1 d | |1 | |1 <| |1 d <q Wq
W| t j |  d d  d |  f | |  }? t j |  j | |?  }@ t j9 |@ |! f }! nx |; D] }= x t8 |= |  D] }1 | |1 d | |1 | |1 <| |1 d <| | |1 | |1 d  \ | |1 <| |1 d <| | d d  |1 f | d d  |1 d f  \ | d d  |1 f <| d d  |1 d f <qWqW| t j |  |  }? t j |  j |> |?  }@ t j9 |@ |! f }! t j: | |;  } t j- | d  } |
 d k r`t d | d |> | t# |@  f  q`qqW| r| | d  } | | d  } | r| | | j | f S| | | j f Sn# | r| | | | f S| | | f Sd S(   s  Compute Least Angle Regression or Lasso path using LARS algorithm [1]

    The optimization objective for the case method='lasso' is::

    (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1

    in the case of method='lars', the objective function is only known in
    the form of an implicit equation (see discussion in [1])

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

    Parameters
    -----------
    X : array, shape: (n_samples, n_features)
        Input data.

    y : array, shape: (n_samples)
        Input targets.

    Xy : array-like, shape (n_samples,) or (n_samples, n_targets),             optional
        Xy = np.dot(X.T, y) that can be precomputed. It is useful
        only when the Gram matrix is precomputed.

    Gram : None, 'auto', array, shape: (n_features, n_features), optional
        Precomputed Gram matrix (X' * X), if ``'auto'``, the Gram
        matrix is precomputed from the given X, if there are more samples
        than features.

    max_iter : integer, optional (default=500)
        Maximum number of iterations to perform, set to infinity for no limit.

    alpha_min : float, optional (default=0)
        Minimum correlation along the path. It corresponds to the
        regularization parameter alpha parameter in the Lasso.

    method : {'lar', 'lasso'}, optional (default='lar')
        Specifies the returned model. Select ``'lar'`` for Least Angle
        Regression, ``'lasso'`` for the Lasso.

    copy_X : bool, optional (default=True)
        If ``False``, ``X`` is overwritten.

    eps : float, optional (default=``np.finfo(np.float).eps``)
        The machine-precision regularization in the computation of the
        Cholesky diagonal factors. Increase this for very ill-conditioned
        systems.

    copy_Gram : bool, optional (default=True)
        If ``False``, ``Gram`` is overwritten.

    verbose : int (default=0)
        Controls output verbosity.

    return_path : bool, optional (default=True)
        If ``return_path==True`` returns the entire path, else returns only the
        last point of the path.

    return_n_iter : bool, optional (default=False)
        Whether to return the number of iterations.

    positive : boolean (default=False)
        Restrict coefficients to be >= 0.
        This option is only allowed with method 'lasso'. Note that the model
        coefficients will not converge to the ordinary-least-squares solution
        for small values of alpha. Only coefficients up to the smallest alpha
        value (``alphas_[alphas_ > 0.].min()`` when fit_path=True) reached by
        the stepwise Lars-Lasso algorithm are typically in congruence with the
        solution of the coordinate descent lasso_path function.

    Returns
    --------
    alphas : array, shape: [n_alphas + 1]
        Maximum of covariances (in absolute value) at each iteration.
        ``n_alphas`` is either ``max_iter``, ``n_features`` or the
        number of nodes in the path with ``alpha >= alpha_min``, whichever
        is smaller.

    active : array, shape [n_alphas]
        Indices of active variables at the end of the path.

    coefs : array, shape (n_features, n_alphas + 1)
        Coefficients along the path

    n_iter : int
        Number of iterations run. Returned only if return_n_iter is set
        to True.

    See also
    --------
    lasso_path
    LassoLars
    Lars
    LassoLarsCV
    LarsCV
    sklearn.decomposition.sparse_encode

    References
    ----------
    .. [1] "Least Angle Regression", Effron et al.
           http://statweb.stanford.edu/~tibs/ftp/lars.pdf

    .. [2] `Wikipedia entry on the Least-angle regression
           <https://en.wikipedia.org/wiki/Least-angle_regression>`_

    .. [3] `Wikipedia entry on the Lasso
           <https://en.wikipedia.org/wiki/Lasso_(statistics)>`_

    R   s|   positive option is broken for Least Angle Regression (LAR). Use method="lasso". This option will be removed in version 0.22.i   g        i    t   dtypet   swapt   nrm2t   potrst   Ft   autos(   Step		Added		Dropped		Active set size		Ct   .i   Nt   transt   lowert   overwrite_bgHz>s   Regressors in active set degenerate. Dropping a regressor, after %i iterations, i.e. alpha=%.3e, with an active set of %i regressors, and the smallest cholesky pivot element being %.3e. Reduce max_iter or increase eps parameters.s   %s		%s		%s		%s		%sit    t   lassos   Early stopping the lars path, as the residues are small and the current value of alpha is no longer well controlled. %i iterations, alpha=%.3e, previous alpha=%.3e, with an active set of %i regressors..g      ?(   i    i    (   R   R   (   R   (;   t   warningst   warnt   DeprecationWarningt   shapet   sizet   mint   npt   zerost   arrayt   listt   aranget   emptyt   int8t   FalseR   R   t   get_blas_funcsR   t   Nonet   copyt
   isinstanceR   t   Truet   dott   Tt   printt   syst   stdoutt   writet   flusht   finfot   float32t   tinyt   epst   argmaxt   abst   fabst   newaxist	   ones_liket   signt   solve_triangulart   solve_triangular_argst   maxt   sqrtR   t   appendt   sumt   isfinitet   flatR   t   min_post   wheret   resizet
   zeros_liket   cholesky_deletet   popt   ranget   r_t   delete(A   t   Xt   yt   Xyt   Gramt   max_itert	   alpha_mint   methodt   copy_XR<   t	   copy_Gramt   verboset   return_patht   return_n_itert   positivet
   n_featurest	   n_samplest   max_featurest   coefst   alphast   coeft	   prev_coeft   alphat
   prev_alphat   n_itert   n_activet   activet   indicest   sign_activet   dropt   LR   R   t   solve_choleskyt   Covt   tiny32t   equality_tolerancet   C_idxt   C_t   Ct   sst   mt   nt   Cov_not_shortenedt   ct   vt   diagt   least_squarest   infot   AAt   it   L_t   tmpt   eq_dirt   corr_eq_dirt   g1t   gamma_t   g2t   zt   z_post   idxt   add_featurest   iit   drop_idxt   residualt   temp(    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyt	   lars_path!   s   r	
	%'&			
	
%
16%U&
2%
	
%
,	

	$"(	
"	&		

6
"9-0%-O	t   Larsc        
   B  sn   e  Z d  Z d Z e e e d d e j e j  j	 e e e d 	 Z
 e d    Z d d  Z d d  Z RS(	   s  Least Angle Regression model a.k.a. LAR

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

    Parameters
    ----------
    fit_intercept : boolean
        Whether to calculate the intercept for this model. If set
        to false, no intercept will be used in calculations
        (e.g. data is expected to be already centered).

    verbose : boolean or integer, optional
        Sets the verbosity amount

    normalize : boolean, optional, default True
        This parameter is ignored when ``fit_intercept`` is set to False.
        If True, the regressors X will be normalized before regression by
        subtracting the mean and dividing by the l2-norm.
        If you wish to standardize, please use
        :class:`sklearn.preprocessing.StandardScaler` before calling ``fit``
        on an estimator with ``normalize=False``.

    precompute : True | False | 'auto' | array-like
        Whether to use a precomputed Gram matrix to speed up
        calculations. If set to ``'auto'`` let us decide. The Gram
        matrix can also be passed as argument.

    n_nonzero_coefs : int, optional
        Target number of non-zero coefficients. Use ``np.inf`` for no limit.

    eps : float, optional
        The machine-precision regularization in the computation of the
        Cholesky diagonal factors. Increase this for very ill-conditioned
        systems. Unlike the ``tol`` parameter in some iterative
        optimization-based algorithms, this parameter does not control
        the tolerance of the optimization.

    copy_X : boolean, optional, default True
        If ``True``, X will be copied; else, it may be overwritten.

    fit_path : boolean
        If True the full path is stored in the ``coef_path_`` attribute.
        If you compute the solution for a large problem or many targets,
        setting ``fit_path`` to ``False`` will lead to a speedup, especially
        with a small alpha.

    positive : boolean (default=False)
        Restrict coefficients to be >= 0. Be aware that you might want to
        remove fit_intercept which is set True by default.

        .. deprecated:: 0.20

            The option is broken and deprecated. It will be removed in v0.22.

    Attributes
    ----------
    alphas_ : array, shape (n_alphas + 1,) | list of n_targets such arrays
        Maximum of covariances (in absolute value) at each iteration.         ``n_alphas`` is either ``n_nonzero_coefs`` or ``n_features``,         whichever is smaller.

    active_ : list, length = n_alphas | list of n_targets such lists
        Indices of active variables at the end of the path.

    coef_path_ : array, shape (n_features, n_alphas + 1)         | list of n_targets such arrays
        The varying values of the coefficients along the path. It is not
        present if the ``fit_path`` parameter is ``False``.

    coef_ : array, shape (n_features,) or (n_targets, n_features)
        Parameter vector (w in the formulation formula).

    intercept_ : float | array, shape (n_targets,)
        Independent term in decision function.

    n_iter_ : array-like or int
        The number of iterations taken by lars_path to find the
        grid of alphas for each target.

    Examples
    --------
    >>> from sklearn import linear_model
    >>> reg = linear_model.Lars(n_nonzero_coefs=1)
    >>> reg.fit([[-1, 1], [0, 0], [1, 1]], [-1.1111, 0, -1.1111])
    ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    Lars(copy_X=True, eps=..., fit_intercept=True, fit_path=True,
       n_nonzero_coefs=1, normalize=True, positive=False, precompute='auto',
       verbose=False)
    >>> print(reg.coef_) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    [ 0. -1.11...]

    See also
    --------
    lars_path, LarsCV
    sklearn.decomposition.sparse_encode

    R   R   i  c
   
      C  sU   | |  _  | |  _ | |  _ | |  _ | |  _ |	 |  _ | |  _ | |  _ | |  _ d  S(   N(	   t   fit_interceptR]   t	   normalizet
   precomputet   n_nonzero_coefsR`   R<   R[   t   fit_path(
   t   selfR   R]   R   R   R   R<   R[   R   R`   (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyt   __init__S  s    								c         C  s}   t  |  d  ry |  t k sa |  d k rB | j d | j d k sa |  d k ry | j d d k ry t j | j |  }  n  |  S(   Nt	   __array__R   i    i   (   t   hasattrR1   R"   R%   R2   R3   (   R   RT   RU   (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyt	   _get_grama  s    &c         C  s  | j  d } |  j | | |  j |  j |  j  \ } } } }	 }
 | j d k rk | d d  t j f } n  | j  d } |  j |  j	 | |  } g  |  _
 g  |  _ t j | | f  |  _ | rlg  |  _ g  |  _ x(t |  D]} | d k r d n | d d  | f } t | | d d  | f d | d | d |  j d t d | d |  j d	 t d
 |  j d  d | d |  j d t d t d |  j \ } } } } |  j
 j |  |  j j |  |  j j |  |  j j |  | d d  d f |  j | <q W| d k rg  |  j
 |  j |  j |  j f D] } | d
 ^ q(\ |  _
 |  _ |  _ |  _ |  j d
 |  _ qn$x t |  D] } | d k rd n | d d  | f } t | | d d  | f d | d | d |  j d t d | d |  j d	 t d
 |  j d  d | d |  j d t d t d |  j \ } } |  j | <} |  j
 j |  |  j j |  qyW| d k r|  j
 d
 |  _
 |  j d
 |  _ n  |  j | |	 |
  |  S(   s=   Auxiliary method to fit the model using X, y as training datai   NRW   RV   R[   R\   RY   RZ   R]   i    RX   R<   R^   R_   R`   i(   R"   t   _preprocess_dataR   R   R[   t   ndimR%   R@   R   R   t   alphas_t   n_iter_R*   t   coef_t   active_t
   coef_path_R   R.   R   R1   RZ   RE   R]   R<   R`   RG   R,   t   _set_intercept(   R   RT   RU   RX   Rh   R   RV   Ra   t   X_offsett   y_offsett   X_scalet	   n_targetsRW   t   kt   this_XyRe   Rl   t	   coef_pathR   t   at   _(    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyt   _fitk  sZ    -				(.!8(.c         C  s   t  | | d t d t \ } } t |  d d  } t |  d  rT d } |  j } n	 |  j } |  j | | d | d | d |  j d | |  S(	   sI  Fit the model using X, y as training data.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training data.

        y : array-like, shape (n_samples,) or (n_samples, n_targets)
            Target values.

        Xy : array-like, shape (n_samples,) or (n_samples, n_targets),                 optional
            Xy = np.dot(X.T, y) that can be precomputed. It is useful
            only when the Gram matrix is precomputed.

        Returns
        -------
        self : object
            returns an instance of self.
        t	   y_numerict   multi_outputRh   g        R   RX   R   RV   (   R	   R1   t   getattrR   R   RX   R   R   (   R   RT   RU   RV   Rh   RX   (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyt   fit  s    !	$N(   t   __name__t
   __module__t   __doc__RZ   R1   R,   R%   R9   t   floatR<   R   t   staticmethodR   R.   R   R   (    (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyR     s   a	
:t	   LassoLarsc           B  sJ   e  Z d  Z d Z d e e e d d e j e j  j	 e e e d 
 Z
 RS(   s  Lasso model fit with Least Angle Regression a.k.a. Lars

    It is a Linear Model trained with an L1 prior as regularizer.

    The optimization objective for Lasso is::

    (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1

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

    Parameters
    ----------
    alpha : float
        Constant that multiplies the penalty term. Defaults to 1.0.
        ``alpha = 0`` is equivalent to an ordinary least square, solved
        by :class:`LinearRegression`. For numerical reasons, using
        ``alpha = 0`` with the LassoLars object is not advised and you
        should prefer the LinearRegression object.

    fit_intercept : boolean
        whether to calculate the intercept for this model. If set
        to false, no intercept will be used in calculations
        (e.g. data is expected to be already centered).

    verbose : boolean or integer, optional
        Sets the verbosity amount

    normalize : boolean, optional, default True
        This parameter is ignored when ``fit_intercept`` is set to False.
        If True, the regressors X will be normalized before regression by
        subtracting the mean and dividing by the l2-norm.
        If you wish to standardize, please use
        :class:`sklearn.preprocessing.StandardScaler` before calling ``fit``
        on an estimator with ``normalize=False``.

    precompute : True | False | 'auto' | array-like
        Whether to use a precomputed Gram matrix to speed up
        calculations. If set to ``'auto'`` let us decide. The Gram
        matrix can also be passed as argument.

    max_iter : integer, optional
        Maximum number of iterations to perform.

    eps : float, optional
        The machine-precision regularization in the computation of the
        Cholesky diagonal factors. Increase this for very ill-conditioned
        systems. Unlike the ``tol`` parameter in some iterative
        optimization-based algorithms, this parameter does not control
        the tolerance of the optimization.

    copy_X : boolean, optional, default True
        If True, X will be copied; else, it may be overwritten.

    fit_path : boolean
        If ``True`` the full path is stored in the ``coef_path_`` attribute.
        If you compute the solution for a large problem or many targets,
        setting ``fit_path`` to ``False`` will lead to a speedup, especially
        with a small alpha.

    positive : boolean (default=False)
        Restrict coefficients to be >= 0. Be aware that you might want to
        remove fit_intercept which is set True by default.
        Under the positive restriction the model coefficients will not converge
        to the ordinary-least-squares solution for small values of alpha.
        Only coefficients up to the smallest alpha value (``alphas_[alphas_ >
        0.].min()`` when fit_path=True) reached by the stepwise Lars-Lasso
        algorithm are typically in congruence with the solution of the
        coordinate descent Lasso estimator.

    Attributes
    ----------
    alphas_ : array, shape (n_alphas + 1,) | list of n_targets such arrays
        Maximum of covariances (in absolute value) at each iteration.         ``n_alphas`` is either ``max_iter``, ``n_features``, or the number of         nodes in the path with correlation greater than ``alpha``, whichever         is smaller.

    active_ : list, length = n_alphas | list of n_targets such lists
        Indices of active variables at the end of the path.

    coef_path_ : array, shape (n_features, n_alphas + 1) or list
        If a list is passed it's expected to be one of n_targets such arrays.
        The varying values of the coefficients along the path. It is not
        present if the ``fit_path`` parameter is ``False``.

    coef_ : array, shape (n_features,) or (n_targets, n_features)
        Parameter vector (w in the formulation formula).

    intercept_ : float | array, shape (n_targets,)
        Independent term in decision function.

    n_iter_ : array-like or int.
        The number of iterations taken by lars_path to find the
        grid of alphas for each target.

    Examples
    --------
    >>> from sklearn import linear_model
    >>> reg = linear_model.LassoLars(alpha=0.01)
    >>> reg.fit([[-1, 1], [0, 0], [1, 1]], [-1, 0, -1])
    ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    LassoLars(alpha=0.01, copy_X=True, eps=..., fit_intercept=True,
         fit_path=True, max_iter=500, normalize=True, positive=False,
         precompute='auto', verbose=False)
    >>> print(reg.coef_) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    [ 0.         -0.963257...]

    See also
    --------
    lars_path
    lasso_path
    Lasso
    LassoCV
    LassoLarsCV
    LassoLarsIC
    sklearn.decomposition.sparse_encode

    R   g      ?R   i  c         C  s^   | |  _  | |  _ | |  _ | |  _ | |  _ |
 |  _ | |  _ | |  _ | |  _ |	 |  _	 d  S(   N(
   Rh   R   RX   R]   R   R`   R   R[   R<   R   (   R   Rh   R   R]   R   R   RX   R<   R[   R   R`   (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyR   B  s    									(   R   R   R   RZ   R1   R,   R%   R9   R   R<   R   (    (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyR     s   v		c         C  s!   | s |  j  j r |  j   S|  S(   N(   t   flagst	   writeableR/   (   R'   R/   (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyt   _check_copy_and_writeableU  s    
t   larsc         C  s  t  |  |  }  t  | |  } t  | |  } t  | |  } | r |  j d d  } |  | 8}  | | 8} | j d d  } t | d t } | | 8} t | d t } | | 8} n  |	 rt j t j |  d d d  } t j |  } |  d d  | f c | | :<n  t |  | d | d t d t d	 | d
 t	 d | d  d |
 d | d | \ } } } |	 r| | c | | d d  t j
 f :<n  t j | |  | d d  t j
 f } | | | | j f S(   s  Compute the residues on left-out data for a full LARS path

    Parameters
    -----------
    X_train : array, shape (n_samples, n_features)
        The data to fit the LARS on

    y_train : array, shape (n_samples)
        The target variable to fit LARS on

    X_test : array, shape (n_samples, n_features)
        The data to compute the residues on

    y_test : array, shape (n_samples)
        The target variable to compute the residues on

    Gram : None, 'auto', array, shape: (n_features, n_features), optional
        Precomputed Gram matrix (X' * X), if ``'auto'``, the Gram
        matrix is precomputed from the given X, if there are more samples
        than features

    copy : boolean, optional
        Whether X_train, X_test, y_train and y_test should be copied;
        if False, they may be overwritten.

    method : 'lar' | 'lasso'
        Specifies the returned model. Select ``'lar'`` for Least Angle
        Regression, ``'lasso'`` for the Lasso.

    verbose : integer, optional
        Sets the amount of verbosity

    fit_intercept : boolean
        whether to calculate the intercept for this model. If set
        to false, no intercept will be used in calculations
        (e.g. data is expected to be already centered).

    positive : boolean (default=False)
        Restrict coefficients to be >= 0. Be aware that you might want to
        remove fit_intercept which is set True by default.
        See reservations for using this option in combination with method
        'lasso' for expected small values of alpha in the doc of LassoLarsCV
        and LassoLarsIC.

    normalize : boolean, optional, default True
        This parameter is ignored when ``fit_intercept`` is set to False.
        If True, the regressors X will be normalized before regression by
        subtracting the mean and dividing by the l2-norm.
        If you wish to standardize, please use
        :class:`sklearn.preprocessing.StandardScaler` before calling ``fit``
        on an estimator with ``normalize=False``.

    max_iter : integer, optional
        Maximum number of iterations to perform.

    eps : float, optional
        The machine-precision regularization in the computation of the
        Cholesky diagonal factors. Increase this for very ill-conditioned
        systems. Unlike the ``tol`` parameter in some iterative
        optimization-based algorithms, this parameter does not control
        the tolerance of the optimization.


    Returns
    --------
    alphas : array, shape (n_alphas,)
        Maximum of covariances (in absolute value) at each iteration.
        ``n_alphas`` is either ``max_iter`` or ``n_features``, whichever
        is smaller.

    active : list
        Indices of active variables at the end of the path.

    coefs : array, shape (n_features, n_alphas)
        Coefficients along the path

    residues : array, shape (n_alphas, n_samples)
        Residues of the prediction on the test data
    t   axisi    R/   i   NRW   R[   R\   RZ   R]   i   RX   R<   R`   (   R   t   meanR   R,   R%   RF   RH   t   flatnonzeroR   RE   R@   R2   R3   (   t   X_traint   y_traint   X_testt   y_testRW   R/   RZ   R]   R   R   RX   R<   R`   t   X_meant   y_meant   normst   nonzerosRe   Rl   Rd   t   residues(    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyt   _lars_path_residues[  s2    S


"#%*)t   LarsCVc           B  sq   e  Z d  Z d Z e e d e d d d d
 e j e j	  j
 e e d  Z d   Z e e d  d	     Z RS(   s  Cross-validated Least Angle Regression model.

    See glossary entry for :term:`cross-validation estimator`.

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

    Parameters
    ----------
    fit_intercept : boolean
        whether to calculate the intercept for this model. If set
        to false, no intercept will be used in calculations
        (e.g. data is expected to be already centered).

    verbose : boolean or integer, optional
        Sets the verbosity amount

    max_iter : integer, optional
        Maximum number of iterations to perform.

    normalize : boolean, optional, default True
        This parameter is ignored when ``fit_intercept`` is set to False.
        If True, the regressors X will be normalized before regression by
        subtracting the mean and dividing by the l2-norm.
        If you wish to standardize, please use
        :class:`sklearn.preprocessing.StandardScaler` before calling ``fit``
        on an estimator with ``normalize=False``.

    precompute : True | False | 'auto' | array-like
        Whether to use a precomputed Gram matrix to speed up
        calculations. If set to ``'auto'`` let us decide. The Gram matrix
        cannot be passed as argument since we will use only subsets of X.

    cv : int, cross-validation generator or an iterable, optional
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - None, to use the default 3-fold cross-validation,
        - integer, to specify the number of folds.
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For integer/None inputs, :class:`KFold` is used.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. versionchanged:: 0.20
            ``cv`` default value if None will change from 3-fold to 5-fold
            in v0.22.

    max_n_alphas : integer, optional
        The maximum number of points on the path used to compute the
        residuals in the cross-validation

    n_jobs : int or None, optional (default=None)
        Number of CPUs to use during the cross validation.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    eps : float, optional
        The machine-precision regularization in the computation of the
        Cholesky diagonal factors. Increase this for very ill-conditioned
        systems.

    copy_X : boolean, optional, default True
        If ``True``, X will be copied; else, it may be overwritten.

    positive : boolean (default=False)
        Restrict coefficients to be >= 0. Be aware that you might want to
        remove fit_intercept which is set True by default.

        .. deprecated:: 0.20
            The option is broken and deprecated. It will be removed in v0.22.

    Attributes
    ----------
    coef_ : array, shape (n_features,)
        parameter vector (w in the formulation formula)

    intercept_ : float
        independent term in decision function

    coef_path_ : array, shape (n_features, n_alphas)
        the varying values of the coefficients along the path

    alpha_ : float
        the estimated regularization parameter alpha

    alphas_ : array, shape (n_alphas,)
        the different values of alpha along the path

    cv_alphas_ : array, shape (n_cv_alphas,)
        all the values of alpha along the path for the different folds

    mse_path_ : array, shape (n_folds, n_cv_alphas)
        the mean square error on left-out for each fold along the path
        (alpha values given by ``cv_alphas``)

    n_iter_ : array-like or int
        the number of iterations run by Lars with the optimal alpha.

    Examples
    --------
    >>> from sklearn.linear_model import LarsCV
    >>> from sklearn.datasets import make_regression
    >>> X, y = make_regression(n_samples=200, noise=4.0, random_state=0)
    >>> reg = LarsCV(cv=5).fit(X, y)
    >>> reg.score(X, y) # doctest: +ELLIPSIS
    0.9996...
    >>> reg.alpha_
    0.0254...
    >>> reg.predict(X[:1,])
    array([154.0842...])

    See also
    --------
    lars_path, LassoLars, LassoLarsCV
    R   i  R   R    i  c         C  sq   | |  _  | |  _ | |  _ | |  _ t t |   j d | d | d | d | d d d |	 d |
 d	 t d
 |  	d  S(   NR   R]   R   R   R   i  R<   R[   R   R`   (   RX   t   cvt   max_n_alphast   n_jobst   superR   R   R1   (   R   R   R]   RX   R   R   R   R   R   R<   R[   R`   (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyR   G  s    				c           s9  t    d t \   t  d  j  t  d  j  t  j d t }  j   t   d  r t	 j
 d  j j  d   n  t d  j d  j       f d	   | j    D  } t j t t |    d
  } t j |  } t t d t t |  t  j     } | d d |  } t j t |  t |  f  } x-t |  D]\ } \ }	 }
 } } |	 d d d  }	 | d d d  } |	 d
 d
 k rt j d
 |	 f }	 t j | d
 t j f | f } n  |	 d | d k rGt j |	 | d f }	 t j | | d t j f f } n  t j  |	 | d d
 |  } | d C} t j! | d d | d d  | f <quWt j" t j# |  d d } | | } | | } t j$ | j! d d   } | | } |  _% |  _& |  _'  j(   d  j) d | d d d t  S(   sR  Fit the model using X, y as training data.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training data.

        y : array-like, shape (n_samples,)
            Target values.

        Returns
        -------
        self : object
            returns an instance of self.
        R   R/   t
   classifierR   sX   Parameter 'precompute' cannot be an array in %s. Automatically switch to 'auto' instead.R   R   R]   c         3  s   |  ] \ } } t  t   |  |  |  | d    d t d  j d t d  j d  d  j d  j d  j d	  j	 d
  j
 	Vq d S(   RW   R/   RZ   R]   i    i   R   R   RX   R<   R`   N(   R   R   R,   RZ   RE   R]   R   R   RX   R<   R`   (   t   .0t   traint   test(   RW   RT   R   RU   (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pys	   <genexpr>v  s   i    i   NiR   i   RX   Rh   RV   R   (+   R	   R1   R   R[   R   R   R,   R   R   R   R    t	   __class__R   R   R   R]   t   splitR%   t   concatenateR(   t   zipt   uniquet   intRE   t   lenR   R   R*   t	   enumerateRR   R@   R   t   interp1dR   t   allRI   t   argmint   alpha_t
   cv_alphas_t	   mse_path_R   RX   R.   (   R   RT   RU   R   t   cv_pathst
   all_alphast   stridet   mse_patht   indexRe   Rl   Rd   R   t   this_residuest   maskt   i_best_alphat
   best_alpha(    (   RW   RT   R   RU   s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyR   V  sT    			.!%##	
)


			sY   Attribute alpha is deprecated in 0.19 and will be removed in 0.21. See ``alpha_`` insteadc         C  s   |  j  S(   N(   R   (   R   (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyRh     s    N(   R   R   R   RZ   R1   R,   R.   R%   R9   R   R<   R   R   t   propertyR
   Rh   (    (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyR     s   w			Pt   LassoLarsCVc           B  sM   e  Z d  Z d Z e e d e d d d d e j e j	  j
 e e d  Z RS(   s  Cross-validated Lasso, using the LARS algorithm.

    See glossary entry for :term:`cross-validation estimator`.

    The optimization objective for Lasso is::

    (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1

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

    Parameters
    ----------
    fit_intercept : boolean
        whether to calculate the intercept for this model. If set
        to false, no intercept will be used in calculations
        (e.g. data is expected to be already centered).

    verbose : boolean or integer, optional
        Sets the verbosity amount

    max_iter : integer, optional
        Maximum number of iterations to perform.

    normalize : boolean, optional, default True
        This parameter is ignored when ``fit_intercept`` is set to False.
        If True, the regressors X will be normalized before regression by
        subtracting the mean and dividing by the l2-norm.
        If you wish to standardize, please use
        :class:`sklearn.preprocessing.StandardScaler` before calling ``fit``
        on an estimator with ``normalize=False``.

    precompute : True | False | 'auto'
        Whether to use a precomputed Gram matrix to speed up
        calculations. If set to ``'auto'`` let us decide. The Gram matrix
        cannot be passed as argument since we will use only subsets of X.

    cv : int, cross-validation generator or an iterable, optional
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - None, to use the default 3-fold cross-validation,
        - integer, to specify the number of folds.
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For integer/None inputs, :class:`KFold` is used.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. versionchanged:: 0.20
            ``cv`` default value if None will change from 3-fold to 5-fold
            in v0.22.

    max_n_alphas : integer, optional
        The maximum number of points on the path used to compute the
        residuals in the cross-validation

    n_jobs : int or None, optional (default=None)
        Number of CPUs to use during the cross validation.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    eps : float, optional
        The machine-precision regularization in the computation of the
        Cholesky diagonal factors. Increase this for very ill-conditioned
        systems.

    copy_X : boolean, optional, default True
        If True, X will be copied; else, it may be overwritten.

    positive : boolean (default=False)
        Restrict coefficients to be >= 0. Be aware that you might want to
        remove fit_intercept which is set True by default.
        Under the positive restriction the model coefficients do not converge
        to the ordinary-least-squares solution for small values of alpha.
        Only coefficients up to the smallest alpha value (``alphas_[alphas_ >
        0.].min()`` when fit_path=True) reached by the stepwise Lars-Lasso
        algorithm are typically in congruence with the solution of the
        coordinate descent Lasso estimator.
        As a consequence using LassoLarsCV only makes sense for problems where
        a sparse solution is expected and/or reached.

    Attributes
    ----------
    coef_ : array, shape (n_features,)
        parameter vector (w in the formulation formula)

    intercept_ : float
        independent term in decision function.

    coef_path_ : array, shape (n_features, n_alphas)
        the varying values of the coefficients along the path

    alpha_ : float
        the estimated regularization parameter alpha

    alphas_ : array, shape (n_alphas,)
        the different values of alpha along the path

    cv_alphas_ : array, shape (n_cv_alphas,)
        all the values of alpha along the path for the different folds

    mse_path_ : array, shape (n_folds, n_cv_alphas)
        the mean square error on left-out for each fold along the path
        (alpha values given by ``cv_alphas``)

    n_iter_ : array-like or int
        the number of iterations run by Lars with the optimal alpha.

    Examples
    --------
    >>> from sklearn.linear_model import LassoLarsCV
    >>> from sklearn.datasets import make_regression
    >>> X, y = make_regression(noise=4.0, random_state=0)
    >>> reg = LassoLarsCV(cv=5).fit(X, y)
    >>> reg.score(X, y) # doctest: +ELLIPSIS
    0.9992...
    >>> reg.alpha_
    0.0484...
    >>> reg.predict(X[:1,])
    array([-77.8723...])

    Notes
    -----

    The object solves the same problem as the LassoCV object. However,
    unlike the LassoCV, it find the relevant alphas values by itself.
    In general, because of this property, it will be more stable.
    However, it is more fragile to heavily multicollinear datasets.

    It is more efficient than the LassoCV if only a small number of
    features are selected compared to the total number, for instance if
    there are very few samples compared to the number of features.

    See also
    --------
    lars_path, LassoLars, LarsCV, LassoCV
    R   i  R   R    i  c         C  sg   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ |	 |  _ |
 |  _	 | |  _
 d  S(   N(   R   R]   RX   R   R   R   R   R   R<   R[   R`   (   R   R   R]   RX   R   R   R   R   R   R<   R[   R`   (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyR   >  s    										N(   R   R   R   RZ   R1   R,   R.   R%   R9   R   R<   R   (    (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyR     s   		t   LassoLarsICc        
   B  sM   e  Z d  Z d e e e d d e j e j  j e e d 	 Z	 e d  Z
 RS(   s  Lasso model fit with Lars using BIC or AIC for model selection

    The optimization objective for Lasso is::

    (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1

    AIC is the Akaike information criterion and BIC is the Bayes
    Information criterion. Such criteria are useful to select the value
    of the regularization parameter by making a trade-off between the
    goodness of fit and the complexity of the model. A good model should
    explain well the data while being simple.

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

    Parameters
    ----------
    criterion : 'bic' | 'aic'
        The type of criterion to use.

    fit_intercept : boolean
        whether to calculate the intercept for this model. If set
        to false, no intercept will be used in calculations
        (e.g. data is expected to be already centered).

    verbose : boolean or integer, optional
        Sets the verbosity amount

    normalize : boolean, optional, default True
        This parameter is ignored when ``fit_intercept`` is set to False.
        If True, the regressors X will be normalized before regression by
        subtracting the mean and dividing by the l2-norm.
        If you wish to standardize, please use
        :class:`sklearn.preprocessing.StandardScaler` before calling ``fit``
        on an estimator with ``normalize=False``.

    precompute : True | False | 'auto' | array-like
        Whether to use a precomputed Gram matrix to speed up
        calculations. If set to ``'auto'`` let us decide. The Gram
        matrix can also be passed as argument.

    max_iter : integer, optional
        Maximum number of iterations to perform. Can be used for
        early stopping.

    eps : float, optional
        The machine-precision regularization in the computation of the
        Cholesky diagonal factors. Increase this for very ill-conditioned
        systems. Unlike the ``tol`` parameter in some iterative
        optimization-based algorithms, this parameter does not control
        the tolerance of the optimization.

    copy_X : boolean, optional, default True
        If True, X will be copied; else, it may be overwritten.

    positive : boolean (default=False)
        Restrict coefficients to be >= 0. Be aware that you might want to
        remove fit_intercept which is set True by default.
        Under the positive restriction the model coefficients do not converge
        to the ordinary-least-squares solution for small values of alpha.
        Only coefficients up to the smallest alpha value (``alphas_[alphas_ >
        0.].min()`` when fit_path=True) reached by the stepwise Lars-Lasso
        algorithm are typically in congruence with the solution of the
        coordinate descent Lasso estimator.
        As a consequence using LassoLarsIC only makes sense for problems where
        a sparse solution is expected and/or reached.


    Attributes
    ----------
    coef_ : array, shape (n_features,)
        parameter vector (w in the formulation formula)

    intercept_ : float
        independent term in decision function.

    alpha_ : float
        the alpha parameter chosen by the information criterion

    n_iter_ : int
        number of iterations run by lars_path to find the grid of
        alphas.

    criterion_ : array, shape (n_alphas,)
        The value of the information criteria ('aic', 'bic') across all
        alphas. The alpha which has the smallest information criterion is
        chosen. This value is larger by a factor of ``n_samples`` compared to
        Eqns. 2.15 and 2.16 in (Zou et al, 2007).


    Examples
    --------
    >>> from sklearn import linear_model
    >>> reg = linear_model.LassoLarsIC(criterion='bic')
    >>> reg.fit([[-1, 1], [0, 0], [1, 1]], [-1.1111, 0, -1.1111])
    ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    LassoLarsIC(copy_X=True, criterion='bic', eps=..., fit_intercept=True,
          max_iter=500, normalize=True, positive=False, precompute='auto',
          verbose=False)
    >>> print(reg.coef_) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    [ 0.  -1.11...]

    Notes
    -----
    The estimation of the number of degrees of freedom is given by:

    "On the degrees of freedom of the lasso"
    Hui Zou, Trevor Hastie, and Robert Tibshirani
    Ann. Statist. Volume 35, Number 5 (2007), 2173-2192.

    https://en.wikipedia.org/wiki/Akaike_information_criterion
    https://en.wikipedia.org/wiki/Bayesian_information_criterion

    See also
    --------
    lars_path, LassoLars, LassoLarsCV
    t   aicR   i  c
   
      C  s^   | |  _  | |  _ |	 |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ t	 |  _
 d  S(   N(   t	   criterionR   R`   RX   R]   R   R[   R   R<   R1   R   (
   R   R   R   R]   R   R   RX   R<   R[   R`   (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyR     s    									c         C  su  t  | | d t \ } } t j | | |  j |  j |  j  \ } } } } } |  j } |  j } t	 | | d | d | d t d d d d d	 |  j
 d
 | d |  j d t d |  j 
\ }	 }
 } |  _ | j d } |  j d k r d } n* |  j d k rt |  } n t d   | d d  t j f t j | |  } t j | d d d } t j |  } t j | j d d t j } xi t | j  D]X \ } } t j |  t j | j  j k } t j |  sqn  t j |  | | <qW|	 |  _  t j d  j } | | | | | | |  _! t j" |  j!  } |	 | |  _# | d d  | f |  _$ |  j% | | |  |  S(   s  Fit the model using X, y as training data.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            training data.

        y : array-like, shape (n_samples,)
            target values. Will be cast to X's dtype if necessary

        copy_X : boolean, optional, default True
            If ``True``, X will be copied; else, it may be overwritten.

        Returns
        -------
        self : object
            returns an instance of self.
        R   RW   R[   R\   RY   g        RZ   R   R]   RX   R<   R_   R`   i    R   i   t   bics%   criterion should be either bic or aicNR   i   R   t   float64(&   R	   R1   R   R   R   R   R[   RX   R   R   R]   R<   R`   R   R"   R   R   t
   ValueErrorR%   R@   R2   R   t   varR&   R   R   R3   R>   R9   R   t   anyRH   R   t
   criterion_R   R   R   R   (   R   RT   RU   R[   t   Xmeant   ymeant   XstdRX   RW   R   R   R   Rb   t   Kt   Rt   mean_squared_errort   sigma2t   dfR   Rf   R   t   eps64t   n_best(    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyR     sB    -		!*	)$	(   R   R   R   R1   R,   R%   R9   R   R<   R   R   (    (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyR   Q  s
   t		!(0   R   t
   __future__R    t   mathR   R5   R   t   numpyR%   t   scipyR   R   t   scipy.linalg.lapackR   t   baseR   R   t   utilsR   R   R	   R
   t   model_selectionR   t
   exceptionsR   t   utils._joblibR   R   t   externals.six.movesR   t   externals.sixR   R,   RD   R.   R1   R9   R   R<   R   R   R   R   R   R   R   R   (    (    (    s?   lib/python2.7/site-packages/sklearn/linear_model/least_angle.pyt   <module>   s@   "			 		n