ó
‡ˆ\c           @   sÙ   d  Z  d d l Z d d l m Z m Z d d l Z d d l m Z d d l	 m
 Z
 m Z d d l m Z d d l m Z m Z d d	 l m Z m Z m Z d d
 l m Z d d l m Z d e
 e f d „  ƒ  YZ d S(   s§  Factor Analysis.

A latent linear variable model.

FactorAnalysis is similar to probabilistic PCA implemented by PCA.score
While PCA assumes Gaussian noise with the same variance for each
feature, the FactorAnalysis model assumes different variances for
each of them.

This implementation is based on David Barber's Book,
Bayesian Reasoning and Machine Learning,
http://www.cs.ucl.ac.uk/staff/d.barber/brml,
Algorithm 21.1
iÿÿÿÿN(   t   sqrtt   log(   t   linalgi   (   t   BaseEstimatort   TransformerMixin(   t   xrange(   t   check_arrayt   check_random_state(   t   fast_logdett   randomized_svdt   squared_norm(   t   check_is_fitted(   t   ConvergenceWarningt   FactorAnalysisc        	   B   sk   e  Z d  Z d d e d d d d d d „ Z d d „ Z d „  Z d	 „  Z d
 „  Z	 d „  Z
 d d „ Z RS(   s6  Factor Analysis (FA)

    A simple linear generative model with Gaussian latent variables.

    The observations are assumed to be caused by a linear transformation of
    lower dimensional latent factors and added Gaussian noise.
    Without loss of generality the factors are distributed according to a
    Gaussian with zero mean and unit covariance. The noise is also zero mean
    and has an arbitrary diagonal covariance matrix.

    If we would restrict the model further, by assuming that the Gaussian
    noise is even isotropic (all diagonal entries are the same) we would obtain
    :class:`PPCA`.

    FactorAnalysis performs a maximum likelihood estimate of the so-called
    `loading` matrix, the transformation of the latent variables to the
    observed ones, using expectation-maximization (EM).

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

    Parameters
    ----------
    n_components : int | None
        Dimensionality of latent space, the number of components
        of ``X`` that are obtained after ``transform``.
        If None, n_components is set to the number of features.

    tol : float
        Stopping tolerance for EM algorithm.

    copy : bool
        Whether to make a copy of X. If ``False``, the input X gets overwritten
        during fitting.

    max_iter : int
        Maximum number of iterations.

    noise_variance_init : None | array, shape=(n_features,)
        The initial guess of the noise variance for each feature.
        If None, it defaults to np.ones(n_features)

    svd_method : {'lapack', 'randomized'}
        Which SVD method to use. If 'lapack' use standard SVD from
        scipy.linalg, if 'randomized' use fast ``randomized_svd`` function.
        Defaults to 'randomized'. For most applications 'randomized' will
        be sufficiently precise while providing significant speed gains.
        Accuracy can also be improved by setting higher values for
        `iterated_power`. If this is not sufficient, for maximum precision
        you should choose 'lapack'.

    iterated_power : int, optional
        Number of iterations for the power method. 3 by default. Only used
        if ``svd_method`` equals 'randomized'

    random_state : int, RandomState instance or None, optional (default=0)
        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`. Only used when ``svd_method`` equals 'randomized'.

    Attributes
    ----------
    components_ : array, [n_components, n_features]
        Components with maximum variance.

    loglike_ : list, [n_iterations]
        The log likelihood at each iteration.

    noise_variance_ : array, shape=(n_features,)
        The estimated noise variance for each feature.

    n_iter_ : int
        Number of iterations run.

    Examples
    --------
    >>> from sklearn.datasets import load_digits
    >>> from sklearn.decomposition import FactorAnalysis
    >>> X, _ = load_digits(return_X_y=True)
    >>> transformer = FactorAnalysis(n_components=7, random_state=0)
    >>> X_transformed = transformer.fit_transform(X)
    >>> X_transformed.shape
    (1797, 7)

    References
    ----------
    .. David Barber, Bayesian Reasoning and Machine Learning,
        Algorithm 21.1

    .. Christopher M. Bishop: Pattern Recognition and Machine Learning,
        Chapter 12.2.4

    See also
    --------
    PCA: Principal component analysis is also a latent linear variable model
        which however assumes equal noise variance for each feature.
        This extra assumption makes probabilistic PCA faster as it can be
        computed in closed form.
    FastICA: Independent component analysis, a latent variable model with
        non-Gaussian latent variables.
    g{®Gáz„?iè  t
   randomizedi   i    c	   	      C   sk   | |  _  | |  _ | |  _ | |  _ | d k rC t d | ƒ ‚ n  | |  _ | |  _ | |  _ | |  _ d  S(   Nt   lapackR   sA   SVD method %s is not supported. Please consider the documentation(   R   R   (	   t   n_componentst   copyt   tolt   max_itert
   ValueErrort
   svd_methodt   noise_variance_initt   iterated_powert   random_state(	   t   selfR   R   R   R   R   R   R   R   (    (    sD   lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.pyt   __init__Š   s    							c            s  t  | d ˆ j d t j ƒ} | j \ } } ˆ j ‰  ˆ  d k rK | ‰  n  t j | d d ƒˆ _ | ˆ j 8} t	 | ƒ } | t
 d t j ƒ ˆ  } t j | d d ƒ} ˆ j d k rÖ t j | d | j ƒ} nI t ˆ j ƒ | k rt d t ˆ j ƒ | f ƒ ‚ n  t j ˆ j ƒ } g  }	 t j }
 d } ˆ j d k rV‡  f d	 †  } nI ˆ j d
 k rŒt ˆ j ƒ ‰ ‡  ‡ ‡ f d †  } n t d ˆ j ƒ ‚ xJt ˆ j ƒ D]!} t j	 | ƒ | } | | | | ƒ \ } } } | d C} t j	 t j | d d ƒ ƒ d d … t j f | } ~ | | 9} | t j t j
 | ƒ ƒ } | | t j t j
 | ƒ ƒ 7} | | d 9} |	 j | ƒ | |
 ˆ j k  r¡Pn  | }
 t j | t j | d d d ƒ| ƒ } q¯Wt j d d d t  ƒ | ˆ _! | ˆ _" |	 ˆ _# | d ˆ _$ ˆ S(   sî   Fit the FactorAnalysis model to X using EM

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

        y : Ignored

        Returns
        -------
        self
        R   t   dtypet   axisi    g       @sI   noise_variance_init dimension does not with number of features : %d != %dgê-™—q=R   c            s=   t  j |  d t ƒ\ } } } | ˆ   | ˆ   t | ˆ  ƒ f S(   Nt   full_matrices(   R   t   svdt   FalseR
   (   t   Xt   _t   st   V(   R   (    sD   lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.pyt   my_svdÆ   s    R   c            sD   t  |  ˆ  d ˆ d ˆ j ƒ\ } } } | | t |  ƒ t | ƒ f S(   NR   t   n_iter(   R	   R   R
   (   R    R!   R"   R#   (   R   R   R   (    sD   lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.pyR$   Í   s    sA   SVD method %s is not supported. Please consider the documentationi   g      ð?g        Ns    FactorAnalysis did not converge.s    You might wants&    to increase the number of iterations.i   (%   R   R   t   npt   float64t   shapeR   t   Nonet   meant   mean_R    R   t   pit   varR   t   onesR   t   lenR   t   arrayt   infR   R   R   R   R   t   maximumt   newaxist   sumt   appendR   t   warningst   warnR   t   components_t   noise_variance_t   loglike_t   n_iter_(   R   R    t   yt	   n_samplest
   n_featurest   nsqrtt   llconstR-   t   psit   logliket   old_llt   SMALLR$   t   it   sqrt_psiR"   R#   t	   unexp_vart   Wt   ll(    (   R   R   R   sD   lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.pyt   fitš   sd    		

6
 -			c         C   sž   t  |  d ƒ t | ƒ } t j t |  j ƒ ƒ } | |  j } |  j |  j } t j	 | t j
 | |  j j ƒ ƒ } t j
 | | j ƒ } t j
 | | ƒ } | S(   s¥  Apply dimensionality reduction to X using the model.

        Compute the expected mean of the latent variables.
        See Barber, 21.2.33 (or Bishop, 12.66).

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

        Returns
        -------
        X_new : array-like, shape (n_samples, n_components)
            The latent variables of X.
        R8   (   R   R   R&   t   eyeR/   R8   R+   R9   R   t   invt   dott   T(   R   R    t   Iht   X_transformedt   Wpsit   cov_zt   tmp(    (    sD   lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.pyt	   transformö   s    %c         C   sU   t  |  d ƒ t j |  j j |  j ƒ } | j d d t | ƒ d … c |  j 7<| S(   s  Compute data covariance with the FactorAnalysis model.

        ``cov = components_.T * components_ + diag(noise_variance)``

        Returns
        -------
        cov : array, shape (n_features, n_features)
            Estimated covariance of data.
        R8   Ni   (   R   R&   RM   R8   RN   t   flatR/   R9   (   R   t   cov(    (    sD   lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.pyt   get_covariance  s    
)c         C   sI  t  |  d ƒ |  j j d } |  j d k r@ t j d |  j ƒ S|  j | k rb t j |  j	 ƒ  ƒ S|  j } t j
 | |  j | j ƒ } | j d d t | ƒ d … c d 7<t j
 | j t j
 t j | ƒ | ƒ ƒ } | |  j d d … t j f :} | |  j t j d d … f :} | j d d t | ƒ d … c d |  j 7<| S(   sÉ   Compute data precision matrix with the FactorAnalysis model.

        Returns
        -------
        precision : array, shape (n_features, n_features)
            Estimated precision of data.
        R8   i   i    g      ð?N(   R   R8   R(   R   R&   t   diagR9   R   RL   RW   RM   RN   RU   R/   R3   (   R   R>   R8   t	   precision(    (    sD   lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.pyt   get_precision$  s    	& !-c         C   s†   t  |  d ƒ | |  j } |  j ƒ  } | j d } d | t j | | ƒ j d d ƒ } | d | t d t j ƒ t	 | ƒ 8} | S(   s)  Compute the log-likelihood of each sample

        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
        R8   i   g      à¿R   g      à?g       @(
   R   R+   RZ   R(   R&   RM   R4   R   R,   R   (   R   R    t   XrRY   R>   t   log_like(    (    sD   lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.pyt   score_samplesA  s    &c         C   s   t  j |  j | ƒ ƒ S(   s:  Compute the average log-likelihood of the samples

        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&   R*   R]   (   R   R    R<   (    (    sD   lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.pyt   scoreX  s    N(   t   __name__t
   __module__t   __doc__R)   t   TrueR   RJ   RT   RW   RZ   R]   R^   (    (    (    sD   lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.pyR   $   s   e\				(   Ra   R6   t   mathR    R   t   numpyR&   t   scipyR   t   baseR   R   t   externals.six.movesR   t   utilsR   R   t   utils.extmathR   R	   R
   t   utils.validationR   t
   exceptionsR   R   (    (    (    sD   lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.pyt   <module>   s   