ó
‡ˆ\c           @  sÎ   d  Z  d d l m Z d d l m Z d d l 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 d	 d l m Z d e e f d „  ƒ  YZ d e e f d „  ƒ  YZ d S(   s   
Various bayesian regression
iÿÿÿÿ(   t   print_function(   t   logN(   t   linalg(   t   pinvhi   (   t   LinearModelt   _rescale_datai   (   t   RegressorMixin(   t   fast_logdet(   t	   check_X_yt   BayesianRidgec           B  sP   e  Z d  Z d d d d d d e e e e e d „ Z d d „ Z e d „ Z RS(   s&  Bayesian ridge regression

    Fit a Bayesian ridge model and optimize the regularization parameters
    lambda (precision of the weights) and alpha (precision of the noise).

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

    Parameters
    ----------
    n_iter : int, optional
        Maximum number of iterations.  Default is 300.

    tol : float, optional
        Stop the algorithm if w has converged. Default is 1.e-3.

    alpha_1 : float, optional
        Hyper-parameter : shape parameter for the Gamma distribution prior
        over the alpha parameter. Default is 1.e-6

    alpha_2 : float, optional
        Hyper-parameter : inverse scale parameter (rate parameter) for the
        Gamma distribution prior over the alpha parameter.
        Default is 1.e-6.

    lambda_1 : float, optional
        Hyper-parameter : shape parameter for the Gamma distribution prior
        over the lambda parameter. Default is 1.e-6.

    lambda_2 : float, optional
        Hyper-parameter : inverse scale parameter (rate parameter) for the
        Gamma distribution prior over the lambda parameter.
        Default is 1.e-6

    compute_score : boolean, optional
        If True, compute the objective function at each step of the model.
        Default is False

    fit_intercept : boolean, optional
        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).
        Default is True.

    normalize : boolean, optional, default False
        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``.

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

    verbose : boolean, optional, default False
        Verbose mode when fitting the model.


    Attributes
    ----------
    coef_ : array, shape = (n_features)
        Coefficients of the regression model (mean of distribution)

    alpha_ : float
       estimated precision of the noise.

    lambda_ : float
       estimated precision of the weights.

    sigma_ : array, shape = (n_features, n_features)
        estimated variance-covariance matrix of the weights

    scores_ : float
        if computed, value of the objective function (to be maximized)

    Examples
    --------
    >>> from sklearn import linear_model
    >>> clf = linear_model.BayesianRidge()
    >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2])
    ... # doctest: +NORMALIZE_WHITESPACE
    BayesianRidge(alpha_1=1e-06, alpha_2=1e-06, compute_score=False,
            copy_X=True, fit_intercept=True, lambda_1=1e-06, lambda_2=1e-06,
            n_iter=300, normalize=False, tol=0.001, verbose=False)
    >>> clf.predict([[1, 1]])
    array([1.])

    Notes
    -----
    For an example, see :ref:`examples/linear_model/plot_bayesian_ridge.py
    <sphx_glr_auto_examples_linear_model_plot_bayesian_ridge.py>`.

    References
    ----------
    D. J. C. MacKay, Bayesian Interpolation, Computation and Neural Systems,
    Vol. 4, No. 3, 1992.

    R. Salakhutdinov, Lecture notes on Statistical Machine Learning,
    http://www.utstat.toronto.edu/~rsalakhu/sta4273/notes/Lecture2.pdf#page=15
    Their beta is our ``self.alpha_``
    Their alpha is our ``self.lambda_``
    i,  gü©ñÒMbP?gíµ ÷Æ°>c         C  sg   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ |	 |  _ |
 |  _	 | |  _
 d  S(   N(   t   n_itert   tolt   alpha_1t   alpha_2t   lambda_1t   lambda_2t   compute_scoret   fit_interceptt	   normalizet   copy_Xt   verbose(   t   selfR
   R   R   R   R   R   R   R   R   R   R   (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/bayes.pyt   __init__   s    										c      	   C  s«  t  | | d t j d t ƒ\ } } |  j | | |  j |  j |  j d | ƒ\ } } } } } | d k	 r„ t	 | | | ƒ \ } } n  | |  _
 | |  _ | j \ } } t j t j ƒ j }	 d t j | ƒ |	 }
 d } |  j } |  j } |  j } |  j } |  j } t ƒ  |  _ d } t j | j | ƒ } t j | d t ƒ\ } } } | d } xðt |  j ƒ D]ß} | | k rët j | j | | | |
 d d … t j f ƒ } t j | | ƒ } |  j ršt j  t j! | |
 | ƒ ƒ } qšn¯ t j | j t j | | | |
 d d d … f | j ƒ ƒ } t j | | ƒ } |  j ršt j" | | d t j# | ƒ j$ ƒ} | | c  |
 | 7*t j  t j! | ƒ ƒ } n  |
 |  _% | |  _& t j  | t j | | ƒ d ƒ } t j  |
 | | |
 | ƒ } | d | t j  | d ƒ d | } | | d | | d | }
 |  j rß| t! | ƒ | | } | | t! |
 ƒ | |
 7} | d | t! | ƒ | t! |
 ƒ |
 | | t j  | d ƒ | | t! d t j' ƒ 7} |  j j( | ƒ n  | d	 k r3t j  t j) | | ƒ ƒ |  j* k  r3| r/t+ d
 t, | ƒ d ƒ n  Pn  t j- | ƒ } qcW| |  _. t j | j | | | |
 d d … t j f ƒ } d |
 | |  _/ |  j0 | | | ƒ |  S(   s  Fit the model

        Parameters
        ----------
        X : numpy array of shape [n_samples,n_features]
            Training data
        y : numpy array of shape [n_samples]
            Target values. Will be cast to X's dtype if necessary

        sample_weight : numpy array of shape [n_samples]
            Individual weights for each sample

            .. versionadded:: 0.20
               parameter *sample_weight* support to BayesianRidge.

        Returns
        -------
        self : returns an instance of self.
        t   dtypet	   y_numerict   sample_weightg      ð?t   full_matricesi   Ng      à?i    s   Convergence after s    iterations(1   R   t   npt   float64t   Truet   _preprocess_dataR   R   R   t   NoneR   t	   X_offset_t   X_scale_t   shapet   finfot   epst   varR   R   R   R   R   t   listt   scores_t   dott   TR   t   svdt   Falset   rangeR
   t   newaxisR   t   sumR   t   fullt   arrayR   t   alpha_t   lambda_t   pit   appendt   absR   t   printt   strt   copyt   coef_t   sigma_t   _set_intercept(   R   t   Xt   yR   R    t	   y_offset_R!   t	   n_samplest
   n_featuresR$   R1   R2   R   R   R   R   R   t	   coef_old_t   XT_yt   Ut   St   Vht   eigen_vals_t   iter_R9   t   logdet_sigma_t   rmse_t   gamma_t   sR:   (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/bayes.pyt   fit   s„    $							
"	!.			#	<1	(c         C  sŒ   |  j  | ƒ } | t k r | S|  j r? | |  j |  j } n  t j | |  j ƒ | j d d ƒ } t j	 | d |  j
 ƒ } | | f Sd S(   sœ  Predict using the linear model.

        In addition to the mean of the predictive distribution, also its
        standard deviation can be returned.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = (n_samples, n_features)
            Samples.

        return_std : boolean, optional
            Whether to return the standard deviation of posterior prediction.

        Returns
        -------
        y_mean : array, shape = (n_samples,)
            Mean of predictive distribution of query points.

        y_std : array, shape = (n_samples,)
            Standard deviation of predictive distribution of query points.
        t   axisi   g      ð?N(   t   _decision_functionR+   R   R    R!   R   R(   R:   R.   t   sqrtR1   (   R   R<   t
   return_stdt   y_meant   sigmas_squared_datat   y_std(    (    s9   lib/python2.7/site-packages/sklearn/linear_model/bayes.pyt   predict  s    	%N(	   t   __name__t
   __module__t   __doc__R+   R   R   R   RL   RT   (    (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/bayes.pyR	      s   f		vt   ARDRegressionc           B  sP   e  Z d  Z d d d d d d e d e e e e d „ Z d „  Z e d „ Z RS(   sn  Bayesian ARD regression.

    Fit the weights of a regression model, using an ARD prior. The weights of
    the regression model are assumed to be in Gaussian distributions.
    Also estimate the parameters lambda (precisions of the distributions of the
    weights) and alpha (precision of the distribution of the noise).
    The estimation is done by an iterative procedures (Evidence Maximization)

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

    Parameters
    ----------
    n_iter : int, optional
        Maximum number of iterations. Default is 300

    tol : float, optional
        Stop the algorithm if w has converged. Default is 1.e-3.

    alpha_1 : float, optional
        Hyper-parameter : shape parameter for the Gamma distribution prior
        over the alpha parameter. Default is 1.e-6.

    alpha_2 : float, optional
        Hyper-parameter : inverse scale parameter (rate parameter) for the
        Gamma distribution prior over the alpha parameter. Default is 1.e-6.

    lambda_1 : float, optional
        Hyper-parameter : shape parameter for the Gamma distribution prior
        over the lambda parameter. Default is 1.e-6.

    lambda_2 : float, optional
        Hyper-parameter : inverse scale parameter (rate parameter) for the
        Gamma distribution prior over the lambda parameter. Default is 1.e-6.

    compute_score : boolean, optional
        If True, compute the objective function at each step of the model.
        Default is False.

    threshold_lambda : float, optional
        threshold for removing (pruning) weights with high precision from
        the computation. Default is 1.e+4.

    fit_intercept : boolean, optional
        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).
        Default is True.

    normalize : boolean, optional, default False
        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``.

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

    verbose : boolean, optional, default False
        Verbose mode when fitting the model.

    Attributes
    ----------
    coef_ : array, shape = (n_features)
        Coefficients of the regression model (mean of distribution)

    alpha_ : float
       estimated precision of the noise.

    lambda_ : array, shape = (n_features)
       estimated precisions of the weights.

    sigma_ : array, shape = (n_features, n_features)
        estimated variance-covariance matrix of the weights

    scores_ : float
        if computed, value of the objective function (to be maximized)

    Examples
    --------
    >>> from sklearn import linear_model
    >>> clf = linear_model.ARDRegression()
    >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2])
    ... # doctest: +NORMALIZE_WHITESPACE
    ARDRegression(alpha_1=1e-06, alpha_2=1e-06, compute_score=False,
            copy_X=True, fit_intercept=True, lambda_1=1e-06, lambda_2=1e-06,
            n_iter=300, normalize=False, threshold_lambda=10000.0, tol=0.001,
            verbose=False)
    >>> clf.predict([[1, 1]])
    array([1.])

    Notes
    -----
    For an example, see :ref:`examples/linear_model/plot_ard.py
    <sphx_glr_auto_examples_linear_model_plot_ard.py>`.

    References
    ----------
    D. J. C. MacKay, Bayesian nonlinear modeling for the prediction
    competition, ASHRAE Transactions, 1994.

    R. Salakhutdinov, Lecture notes on Statistical Machine Learning,
    http://www.utstat.toronto.edu/~rsalakhu/sta4273/notes/Lecture2.pdf#page=15
    Their beta is our ``self.alpha_``
    Their alpha is our ``self.lambda_``
    ARD is a little different than the slide: only dimensions/features for
    which ``self.lambda_ < self.threshold_lambda`` are kept and the rest are
    discarded.
    i,  gü©ñÒMbP?gíµ ÷Æ°>g     ˆÃ@c         C  sp   | |  _  | |  _ |	 |  _ |
 |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _	 | |  _
 | |  _ d  S(   N(   R
   R   R   R   R   R   R   R   R   t   threshold_lambdaR   R   (   R   R
   R   R   R   R   R   R   RY   R   R   R   R   (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/bayes.pyR   š  s    											c      	   C  s‰  t  | | d t j d t d d ƒ\ } } | j \ } } t j | ƒ } |  j | | |  j |  j |  j	 ƒ \ } } } } } t j
 | d t ƒ}	 |  j }
 |  j } |  j } |  j } |  j } t j t j ƒ j } d t j | ƒ | } t j
 | ƒ } t ƒ  |  _ d } d „  } d „  } xüt |  j ƒ D]ë} | | | | |	 | ƒ } | | | | | |	 | ƒ } t j | t j | | ƒ d ƒ } d | |	 t j | ƒ } | d |
 | |	 d d | | |	 <| | j ƒ  d | | d | } | |  j k  }	 d	 | |	 <|  j r¼|
 t j | ƒ | | j ƒ  } | | t | ƒ | | 7} | d
 t | ƒ | t | ƒ t j t j | ƒ ƒ 7} | d
 | | | | d j ƒ  8} |  j j  | ƒ n  | d	 k rt j t j! | | ƒ ƒ |  j" k  r| rt# d | ƒ n  Pn  t j$ | ƒ } q,W| | | | |	 | ƒ } | | | | | |	 | ƒ } | |  _% | |  _& | |  _' | |  _( |  j) | | | ƒ |  S(   s3  Fit the ARDRegression model according to the given training data
        and parameters.

        Iterative procedure to maximize the evidence

        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, shape = [n_samples]
            Target values (integers). Will be cast to X's dtype if necessary

        Returns
        -------
        self : returns an instance of self.
        R   R   t   ensure_min_samplesi   g      ð?c         S  s!  t  t j | ƒ | t j |  d  d  … | f t j d | | d d g ƒ |  d  d  … | f j ƒ ƒ } t j | |  d  d  … | f t j d | | d d g ƒ ƒ } t j t j d | | d d g ƒ |  d  d  … | f j | ƒ } | j d  d  | j d d … c d | | 7<| S(   Ng      ð?i   iÿÿÿÿ(   R   R   t   eyeR(   t   reshapeR)   t   flatR"   (   R<   R1   R2   t   keep_lambdaR?   R:   (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/bayes.pyt   update_sigmaÚ  s     $#!/c         S  s=   | t  j | t  j |  d  d  … | f j | ƒ ƒ | | <| S(   N(   R   R(   R)   (   R<   R=   R9   R1   R^   R:   (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/bayes.pyt   update_coeffæ  s    	0g       @i    g      à?s   Converged after %s iterationsN(*   R   R   R   R   R"   t   zerosR   R   R   R   t   onest   boolR   R   R   R   R   R#   R$   R%   R&   R'   R   R,   R
   R.   R(   t   diagRY   R   R   R   R4   R5   R   R6   R8   R9   R1   R:   R2   R;   (   R   R<   R=   R?   R@   R9   R    R>   R!   R^   R   R   R   R   R   R$   R1   R2   RA   R_   R`   RG   R:   RI   RJ   RK   (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/bayes.pyRL   «  sf    -							#	!$1				c         C  s®   |  j  | ƒ } | t k r | S|  j r? | |  j |  j } n  | d d … |  j |  j k  f } t j | |  j	 ƒ | j
 d d ƒ } t j | d |  j ƒ } | | f Sd S(   sœ  Predict using the linear model.

        In addition to the mean of the predictive distribution, also its
        standard deviation can be returned.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = (n_samples, n_features)
            Samples.

        return_std : boolean, optional
            Whether to return the standard deviation of posterior prediction.

        Returns
        -------
        y_mean : array, shape = (n_samples,)
            Mean of predictive distribution of query points.

        y_std : array, shape = (n_samples,)
            Standard deviation of predictive distribution of query points.
        NRM   i   g      ð?(   RN   R+   R   R    R!   R2   RY   R   R(   R:   R.   RO   R1   (   R   R<   RP   RQ   RR   RS   (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/bayes.pyRT     s    	"%(   RU   RV   RW   R+   R   R   RL   RT   (    (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/bayes.pyRX   *  s   n			m(   RW   t
   __future__R    t   mathR   t   numpyR   t   scipyR   t   scipy.linalgR   t   baseR   R   R   t   utils.extmathR   t   utilsR   R	   RX   (    (    (    s9   lib/python2.7/site-packages/sklearn/linear_model/bayes.pyt   <module>   s   ÿ 