ó
‡ˆ\c           @   s  d  Z  d d l m Z m Z d d l Z d d l 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 l m Z d d l m 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 „  Z d „  Z d e f d „  ƒ  YZ d S(   s    Principal Component Analysis
iÿÿÿÿ(   t   logt   sqrtN(   t   linalg(   t   gammaln(   t   issparse(   t   svdsi   (   t   sixi   (   t   _BasePCA(   t   check_random_state(   t   check_array(   t   fast_logdett   randomized_svdt   svd_flip(   t   stable_cumsum(   t   check_is_fittedc      	   C   s   | t  |  ƒ k r! t d ƒ ‚ n  | t d ƒ } xE t | ƒ D]7 } | t | | d ƒ t t j ƒ | | d 7} q? Wt j t j |  |  ƒ ƒ } | | d } | | k rÀ d } d } n; t j |  | ƒ | | } t j | ƒ | | | d } | | | | d d }	 t d t j ƒ |	 | d d }
 d } |  j ƒ  } | | | | +xv t | ƒ D]h } x_ t | d t  |  ƒ ƒ D]D } | t |  | |  | d | | d | | ƒ t | ƒ 7} q„WqdW| | | |
 | d | t | ƒ d } | S(   sZ  Compute the likelihood of a rank ``rank`` dataset

    The dataset is assumed to be embedded in gaussian noise of shape(n,
    dimf) having spectrum ``spectrum``.

    Parameters
    ----------
    spectrum : array of shape (n)
        Data spectrum.
    rank : int
        Tested rank value.
    n_samples : int
        Number of samples.
    n_features : int
        Number of features.

    Returns
    -------
    ll : float,
        The log-likelihood

    Notes
    -----
    This implements the method of `Thomas P. Minka:
    Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604`
    s5   The tested rank cannot exceed the rank of the datasetg       @i    i   g      ð?g        (	   t   lent
   ValueErrorR    t   rangeR   t   npt   pit   sumt   copy(   t   spectrumt   rankt	   n_samplest
   n_featurest   put   it   plt   pvt   vt   mt   ppt   pat	   spectrum_t   jt   ll(    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyt   _assess_dimension_    s0    !	 # 1,c         C   sU   t  |  ƒ } t j | ƒ } x- t | ƒ D] } t |  | | | ƒ | | <q( W| j ƒ  S(   s   Infers the dimension of a dataset of shape (n_samples, n_features)

    The dataset is described by its spectrum `spectrum`.
    (   R   R   t   emptyR   R%   t   argmax(   R   R   R   t
   n_spectrumR$   R   (    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyt   _infer_dimension_^   s
    t   PCAc           B   st   e  Z d  Z d e e d d d d d „ Z d d „ Z d d „ Z d „  Z	 d „  Z
 d „  Z d	 „  Z d d
 „ Z RS(   s£!  Principal component analysis (PCA)

    Linear dimensionality reduction using Singular Value Decomposition of the
    data to project it to a lower dimensional space.

    It uses the LAPACK implementation of the full SVD or a randomized truncated
    SVD by the method of Halko et al. 2009, depending on the shape of the input
    data and the number of components to extract.

    It can also use the scipy.sparse.linalg ARPACK implementation of the
    truncated SVD.

    Notice that this class does not support sparse input. See
    :class:`TruncatedSVD` for an alternative with sparse data.

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

    Parameters
    ----------
    n_components : int, float, None or string
        Number of components to keep.
        if n_components is not set all components are kept::

            n_components == min(n_samples, n_features)

        If ``n_components == 'mle'`` and ``svd_solver == 'full'``, Minka's
        MLE is used to guess the dimension. Use of ``n_components == 'mle'``
        will interpret ``svd_solver == 'auto'`` as ``svd_solver == 'full'``.

        If ``0 < n_components < 1`` and ``svd_solver == 'full'``, select the
        number of components such that the amount of variance that needs to be
        explained is greater than the percentage specified by n_components.

        If ``svd_solver == 'arpack'``, the number of components must be
        strictly less than the minimum of n_features and n_samples.

        Hence, the None case results in::

            n_components == min(n_samples, n_features) - 1

    copy : bool (default True)
        If False, data passed to fit are overwritten and running
        fit(X).transform(X) will not yield the expected results,
        use fit_transform(X) instead.

    whiten : bool, optional (default False)
        When True (False by default) the `components_` vectors are multiplied
        by the square root of n_samples and then divided by the singular values
        to ensure uncorrelated outputs with unit component-wise variances.

        Whitening will remove some information from the transformed signal
        (the relative variance scales of the components) but can sometime
        improve the predictive accuracy of the downstream estimators by
        making their data respect some hard-wired assumptions.

    svd_solver : string {'auto', 'full', 'arpack', 'randomized'}
        auto :
            the solver is selected by a default policy based on `X.shape` and
            `n_components`: if the input data is larger than 500x500 and the
            number of components to extract is lower than 80% of the smallest
            dimension of the data, then the more efficient 'randomized'
            method is enabled. Otherwise the exact full SVD is computed and
            optionally truncated afterwards.
        full :
            run exact full SVD calling the standard LAPACK solver via
            `scipy.linalg.svd` and select the components by postprocessing
        arpack :
            run SVD truncated to n_components calling ARPACK solver via
            `scipy.sparse.linalg.svds`. It requires strictly
            0 < n_components < min(X.shape)
        randomized :
            run randomized SVD by the method of Halko et al.

        .. versionadded:: 0.18.0

    tol : float >= 0, optional (default .0)
        Tolerance for singular values computed by svd_solver == 'arpack'.

        .. versionadded:: 0.18.0

    iterated_power : int >= 0, or 'auto', (default 'auto')
        Number of iterations for the power method computed by
        svd_solver == 'randomized'.

        .. versionadded:: 0.18.0

    random_state : int, RandomState instance or None, optional (default None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`. Used when ``svd_solver`` == 'arpack' or 'randomized'.

        .. versionadded:: 0.18.0

    Attributes
    ----------
    components_ : array, shape (n_components, n_features)
        Principal axes in feature space, representing the directions of
        maximum variance in the data. The components are sorted by
        ``explained_variance_``.

    explained_variance_ : array, shape (n_components,)
        The amount of variance explained by each of the selected components.

        Equal to n_components largest eigenvalues
        of the covariance matrix of X.

        .. versionadded:: 0.18

    explained_variance_ratio_ : array, shape (n_components,)
        Percentage of variance explained by each of the selected components.

        If ``n_components`` is not set then all components are stored and the
        sum of the ratios is equal to 1.0.

    singular_values_ : array, shape (n_components,)
        The singular values corresponding to each of the selected components.
        The singular values are equal to the 2-norms of the ``n_components``
        variables in the lower-dimensional space.

    mean_ : array, shape (n_features,)
        Per-feature empirical mean, estimated from the training set.

        Equal to `X.mean(axis=0)`.

    n_components_ : int
        The estimated number of components. When n_components is set
        to 'mle' or a number between 0 and 1 (with svd_solver == 'full') this
        number is estimated from input data. Otherwise it equals the parameter
        n_components, or the lesser value of n_features and n_samples
        if n_components is None.

    noise_variance_ : float
        The estimated noise covariance following the Probabilistic PCA model
        from Tipping and Bishop 1999. See "Pattern Recognition and
        Machine Learning" by C. Bishop, 12.2.1 p. 574 or
        http://www.miketipping.com/papers/met-mppca.pdf. It is required to
        compute the estimated data covariance and score samples.

        Equal to the average of (min(n_features, n_samples) - n_components)
        smallest eigenvalues of the covariance matrix of X.

    References
    ----------
    For n_components == 'mle', this class uses the method of `Minka, T. P.
    "Automatic choice of dimensionality for PCA". In NIPS, pp. 598-604`

    Implements the probabilistic PCA model from:
    `Tipping, M. E., and Bishop, C. M. (1999). "Probabilistic principal
    component analysis". Journal of the Royal Statistical Society:
    Series B (Statistical Methodology), 61(3), 611-622.
    via the score and score_samples methods.
    See http://www.miketipping.com/papers/met-mppca.pdf

    For svd_solver == 'arpack', refer to `scipy.sparse.linalg.svds`.

    For svd_solver == 'randomized', see:
    `Halko, N., Martinsson, P. G., and Tropp, J. A. (2011).
    "Finding structure with randomness: Probabilistic algorithms for
    constructing approximate matrix decompositions".
    SIAM review, 53(2), 217-288.` and also
    `Martinsson, P. G., Rokhlin, V., and Tygert, M. (2011).
    "A randomized algorithm for the decomposition of matrices".
    Applied and Computational Harmonic Analysis, 30(1), 47-68.`


    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.decomposition import PCA
    >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
    >>> pca = PCA(n_components=2)
    >>> pca.fit(X)
    PCA(copy=True, iterated_power='auto', n_components=2, random_state=None,
      svd_solver='auto', tol=0.0, whiten=False)
    >>> print(pca.explained_variance_ratio_)  # doctest: +ELLIPSIS
    [0.9924... 0.0075...]
    >>> print(pca.singular_values_)  # doctest: +ELLIPSIS
    [6.30061... 0.54980...]

    >>> pca = PCA(n_components=2, svd_solver='full')
    >>> pca.fit(X)                 # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
    PCA(copy=True, iterated_power='auto', n_components=2, random_state=None,
      svd_solver='full', tol=0.0, whiten=False)
    >>> print(pca.explained_variance_ratio_)  # doctest: +ELLIPSIS
    [0.9924... 0.00755...]
    >>> print(pca.singular_values_)  # doctest: +ELLIPSIS
    [6.30061... 0.54980...]

    >>> pca = PCA(n_components=1, svd_solver='arpack')
    >>> pca.fit(X)
    PCA(copy=True, iterated_power='auto', n_components=1, random_state=None,
      svd_solver='arpack', tol=0.0, whiten=False)
    >>> print(pca.explained_variance_ratio_)  # doctest: +ELLIPSIS
    [0.99244...]
    >>> print(pca.singular_values_)  # doctest: +ELLIPSIS
    [6.30061...]

    See also
    --------
    KernelPCA
    SparsePCA
    TruncatedSVD
    IncrementalPCA
    t   autog        c         C   sC   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ d  S(   N(   t   n_componentsR   t   whitent
   svd_solvert   tolt   iterated_powert   random_state(   t   selfR,   R   R-   R.   R/   R0   R1   (    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyt   __init__9  s    						c         C   s   |  j  | ƒ |  S(   sj  Fit the model with X.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training data, where n_samples is the number of samples
            and n_features is the number of features.

        y : Ignored

        Returns
        -------
        self : object
            Returns the instance itself.
        (   t   _fit(   R2   t   Xt   y(    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyt   fitD  s    c         C   ss   |  j  | ƒ \ } } } | d d … d |  j … f } |  j r^ | t | j d d ƒ 9} n | | |  j  9} | S(   s”  Fit the model with X and apply the dimensionality reduction on X.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training data, where n_samples is the number of samples
            and n_features is the number of features.

        y : Ignored

        Returns
        -------
        X_new : array-like, shape (n_samples, n_components)

        Ni    i   (   R4   t   n_components_R-   R   t   shape(   R2   R5   R6   t   Ut   St   V(    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyt   fit_transformW  s    	c         C   s|  t  | ƒ r t d ƒ ‚ n  t | d t j t j g d t d |  j ƒ} |  j d k rŽ |  j
 d k rx t | j ƒ } q— t | j ƒ d } n	 |  j } |  j
 |  _ |  j d k rt | j ƒ d k sÓ | d	 k rß d
 |  _ q| d k r| d t | j ƒ k  rd |  _ qd
 |  _ n  |  j d
 k r;|  j | | ƒ S|  j d k r`|  j | | |  j ƒ St d j |  j ƒ ƒ ‚ d S(   s?   Dispatch to the right submethod depending on the chosen solver.sO   PCA does not support sparse input. See TruncatedSVD for a possible alternative.t   dtypet	   ensure_2dR   t   arpacki   R+   iô  t   mlet   fullgš™™™™™é?t
   randomizeds   Unrecognized svd_solver='{0}'N(   R@   RC   (   R   t	   TypeErrorR	   R   t   float64t   float32t   TrueR   R,   t   NoneR.   t   minR9   t   _fit_svd_solvert   maxt	   _fit_fullt   _fit_truncatedR   t   format(   R2   R5   R,   (    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyR4   s  s,    !	!%	c         C   sN  | j  \ } } | d k r9 | | k  rÉ t d ƒ ‚ qÉ n d | k oY t | | ƒ k n s€ t d | t | | ƒ f ƒ ‚ nI | d k rÉ t | t j t j f ƒ sÉ t d | t | ƒ f ƒ ‚ qÉ n  t j	 | d d ƒ|  _
 | |  j
 8} t j | d t ƒ\ } } } t | | ƒ \ } } | } | d	 | d }	 |	 j ƒ  }
 |	 |
 } | j ƒ  } | d k r|t |	 | | ƒ } nA d | k  o“d
 k  n r½t | ƒ } t j | | ƒ d } n  | t | | ƒ k  rè|	 | j	 ƒ  |  _ n	 d |  _ | | |  _ |  _ | |  |  _ | |  _ |	 |  |  _ | |  |  _ | |  |  _ | | | f S(   s(   Fit the model by computing full SVD on XRA   s?   n_components='mle' is only supported if n_samples >= n_featuresi    sZ   n_components=%r must be between 0 and min(n_samples, n_features)=%r with svd_solver='full'i   sS   n_components=%r must be of type int when greater than or equal to 1, was of type=%rt   axist   full_matricesi   g      ð?g        (   R9   R   RI   t
   isinstancet   numberst   IntegralR   t   integert   typet   meant   mean_R   t   svdt   FalseR   R   R   R)   R   t   searchsortedt   noise_variance_t
   n_samples_t   n_features_t   components_R8   t   explained_variance_t   explained_variance_ratio_t   singular_values_(   R2   R5   R,   R   R   R:   R;   R<   R^   R_   t	   total_varR`   Ra   t   ratio_cumsum(    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyRL     sF    %
		c      
   C   s  | j  \ } } t | t j ƒ r: t d | | f ƒ ‚ nÊ d | k oZ t | | ƒ k n s„ t d | t | | ƒ | f ƒ ‚ n€ t | t j t j	 f ƒ s¾ t d | t
 | ƒ f ƒ ‚ nF | d k r| t | | ƒ k rt d | t | | ƒ | f ƒ ‚ n  t |  j ƒ } t j | d d ƒ|  _ | |  j 8} | d k rà| j d	 d d
 t | j  ƒ ƒ} t | d | d |  j d | ƒ\ } }	 }
 |	 d d d	 … }	 t | d d … d d d	 … f |
 d d d	 … ƒ \ } }
 n? | d k rt | d | d |  j d t d | ƒ\ } }	 }
 n  | | |  _ |  _ |
 |  _ | |  _ |	 d | d |  _ t j | d d d d ƒ} |  j | j ƒ  |  _ |	 j ƒ  |  _ |  j t | | ƒ k  rì| j ƒ  |  j j ƒ  |  _  |  j  t | | ƒ | :_  n	 d |  _  | |	 |
 f S(   sX   Fit the model by computing truncated SVD (by ARPACK or randomized)
        on X
        s7   n_components=%r cannot be a string with svd_solver='%s'i   sX   n_components=%r must be between 1 and min(n_samples, n_features)=%r with svd_solver='%s'sS   n_components=%r must be of type int when greater than or equal to 1, was of type=%rR@   s]   n_components=%r must be strictly less than min(n_samples, n_features)=%r with svd_solver='%s'RO   i    iÿÿÿÿt   sizet   kR/   t   v0NRC   R,   t   n_itert	   flip_signR1   i   t   ddofg        (!   R9   RQ   R   t   string_typesR   RI   RR   RS   R   RT   RU   R   R1   RV   RW   t   uniformR   R/   R   R   R0   RG   R\   R]   R^   R8   R_   t   varR   R`   R   Ra   R[   (   R2   R5   R,   R.   R   R   R1   Rf   R:   R;   R<   Rb   (    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyRM   Ü  sT    %!*>					c         C   s’   t  |  d ƒ t | ƒ } | |  j } | j d } |  j ƒ  } d | t j | | ƒ j d d ƒ } | d | t d t j	 ƒ t
 | ƒ 8} | S(   sÁ  Return the log-likelihood of each sample.

        See. "Pattern Recognition and Machine Learning"
        by C. Bishop, 12.2.1 p. 574
        or http://www.miketipping.com/papers/met-mppca.pdf

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

        Returns
        -------
        ll : array, shape (n_samples,)
            Log-likelihood of each sample under the current model
        RW   i   g      à¿RO   g      à?g       @(   R   R	   RW   R9   t   get_precisionR   t   dotR   R    R   R
   (   R2   R5   t   XrR   t	   precisiont   log_like(    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyt   score_samples#  s    &c         C   s   t  j |  j | ƒ ƒ S(   sÒ  Return the average log-likelihood of all samples.

        See. "Pattern Recognition and Machine Learning"
        by C. Bishop, 12.2.1 p. 574
        or http://www.miketipping.com/papers/met-mppca.pdf

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

        y : Ignored

        Returns
        -------
        ll : float
            Average log-likelihood of the samples under the current model
        (   R   RV   Rr   (   R2   R5   R6   (    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyt   score?  s    N(   t   __name__t
   __module__t   __doc__RH   RG   RY   R3   R7   R=   R4   RL   RM   Rr   Rs   (    (    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyR*   j   s   Í				*	?	G	(    Rv   t   mathR    R   RR   t   numpyR   t   scipyR   t   scipy.specialR   t   scipy.sparseR   t   scipy.sparse.linalgR   t	   externalsR   t   baseR   t   utilsR   R	   t   utils.extmathR
   R   R   R   t   utils.validationR   R%   R)   R*   (    (    (    s8   lib/python2.7/site-packages/sklearn/decomposition/pca.pyt   <module>   s"   	>	