
\c           @   s   d  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
 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 e e f d     YZ d S(   s$   Kernel Principal Components AnalysisiN(   t   linalg(   t   eigshi   (   t   check_random_state(   t   check_is_fittedt   check_array(   t   NotFittedError(   t   BaseEstimatort   TransformerMixin(   t   KernelCenterer(   t   pairwise_kernelst	   KernelPCAc           B   s   e  Z d  Z d d d d d d d e d d d e d e d d  Z e d    Z d d	  Z	 d
   Z
 d   Z d d  Z d d  Z d   Z d   Z RS(   s  Kernel Principal component analysis (KPCA)

    Non-linear dimensionality reduction through the use of kernels (see
    :ref:`metrics`).

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

    Parameters
    ----------
    n_components : int, default=None
        Number of components. If None, all non-zero components are kept.

    kernel : "linear" | "poly" | "rbf" | "sigmoid" | "cosine" | "precomputed"
        Kernel. Default="linear".

    gamma : float, default=1/n_features
        Kernel coefficient for rbf, poly and sigmoid kernels. Ignored by other
        kernels.

    degree : int, default=3
        Degree for poly kernels. Ignored by other kernels.

    coef0 : float, default=1
        Independent term in poly and sigmoid kernels.
        Ignored by other kernels.

    kernel_params : mapping of string to any, default=None
        Parameters (keyword arguments) and values for kernel passed as
        callable object. Ignored by other kernels.

    alpha : int, default=1.0
        Hyperparameter of the ridge regression that learns the
        inverse transform (when fit_inverse_transform=True).

    fit_inverse_transform : bool, default=False
        Learn the inverse transform for non-precomputed kernels.
        (i.e. learn to find the pre-image of a point)

    eigen_solver : string ['auto'|'dense'|'arpack'], default='auto'
        Select eigensolver to use. If n_components is much less than
        the number of training samples, arpack may be more efficient
        than the dense eigensolver.

    tol : float, default=0
        Convergence tolerance for arpack.
        If 0, optimal value will be chosen by arpack.

    max_iter : int, default=None
        Maximum number of iterations for arpack.
        If None, optimal value will be chosen by arpack.

    remove_zero_eig : boolean, default=False
        If True, then all components with zero eigenvalues are removed, so
        that the number of components in the output may be < n_components
        (and sometimes even zero due to numerical instability).
        When n_components is None, this parameter is ignored and components
        with zero eigenvalues are removed regardless.

    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 ``eigen_solver`` == 'arpack'.

        .. versionadded:: 0.18

    copy_X : boolean, default=True
        If True, input X is copied and stored by the model in the `X_fit_`
        attribute. If no further changes will be done to X, setting
        `copy_X=False` saves memory by storing a reference.

        .. versionadded:: 0.18

    n_jobs : int or None, optional (default=None)
        The number of parallel jobs to run.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

        .. versionadded:: 0.18

    Attributes
    ----------
    lambdas_ : array, (n_components,)
        Eigenvalues of the centered kernel matrix in decreasing order.
        If `n_components` and `remove_zero_eig` are not set,
        then all values are stored.

    alphas_ : array, (n_samples, n_components)
        Eigenvectors of the centered kernel matrix. If `n_components` and
        `remove_zero_eig` are not set, then all components are stored.

    dual_coef_ : array, (n_samples, n_features)
        Inverse transform matrix. Only available when
        ``fit_inverse_transform`` is True.

    X_transformed_fit_ : array, (n_samples, n_components)
        Projection of the fitted data on the kernel principal components.
        Only available when ``fit_inverse_transform`` is True.

    X_fit_ : (n_samples, n_features)
        The data used to fit the model. If `copy_X=False`, then `X_fit_` is
        a reference. This attribute is used for the calls to transform.

    Examples
    --------
    >>> from sklearn.datasets import load_digits
    >>> from sklearn.decomposition import KernelPCA
    >>> X, _ = load_digits(return_X_y=True)
    >>> transformer = KernelPCA(n_components=7, kernel='linear')
    >>> X_transformed = transformer.fit_transform(X)
    >>> X_transformed.shape
    (1797, 7)

    References
    ----------
    Kernel PCA was introduced in:
        Bernhard Schoelkopf, Alexander J. Smola,
        and Klaus-Robert Mueller. 1999. Kernel principal
        component analysis. In Advances in kernel methods,
        MIT Press, Cambridge, MA, USA 327-352.
    t   lineari   i   g      ?t   autoi    c         C   s   | r! | d k r! t  d   n  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ |	 |  _	 | |  _
 |
 |  _ | |  _ | |  _ | |  _ | |  _ d  S(   Nt   precomputeds7   Cannot fit_inverse_transform with a precomputed kernel.(   t
   ValueErrort   n_componentst   kernelt   kernel_paramst   gammat   degreet   coef0t   alphat   fit_inverse_transformt   eigen_solvert   remove_zero_eigt   tolt   max_itert   random_statet   n_jobst   copy_X(   t   selfR   R   R   R   R   R   R   R   R   R   R   R   R   R   R   (    (    s?   lib/python2.7/site-packages/sklearn/decomposition/kernel_pca.pyt   __init__   s$    														c         C   s   |  j  d k S(   NR   (   R   (   R   (    (    s?   lib/python2.7/site-packages/sklearn/decomposition/kernel_pca.pyt	   _pairwise   s    c      
   C   sm   t  |  j  r! |  j p i  } n$ i |  j d 6|  j d 6|  j d 6} t | | d |  j d t d |  j | S(   NR   R   R   t   metrict   filter_paramsR   (	   t   callableR   R   R   R   R   R	   t   TrueR   (   R   t   Xt   Yt   params(    (    s?   lib/python2.7/site-packages/sklearn/decomposition/kernel_pca.pyt   _get_kernel   s    
c         C   s  |  j  j |  } |  j d k r1 | j d } n t | j d |  j  } |  j d k r | j d d k r | d k  r d } q d } n	 |  j } | d k r t j | d | j d | | j d d f \ |  _	 |  _
 ns | d k rRt |  j  } | j d	 d | j d  } t | | d
 d d |  j d |  j d | \ |  _	 |  _
 n  |  j	 j   d d d	  } |  j	 | |  _	 |  j
 d d  | f |  _
 |  j s|  j d k r|  j
 d d  |  j	 d k f |  _
 |  j	 |  j	 d k |  _	 n  | S(   s    Fit's using kernel Ki    R   i   i
   t   arpackt   denset   eigvalsi   it   whicht   LAR   t   maxitert   v0N(   t	   _centerert   fit_transformR   t   Nonet   shapet   minR   R    t   eight   lambdas_t   alphas_R   R   t   uniformR   R   R   t   argsortR   (   R   t   KR   R   R   R/   t   indices(    (    s?   lib/python2.7/site-packages/sklearn/decomposition/kernel_pca.pyt   _fit_transform   s6    			:		%c         C   s   t  | d  r t d   n  | j d } |  j |  } | j d  d  | d  c |  j 7<t j | | d t d t |  _	 | |  _
 d  S(   Nt   tocsrs6   Inverse transform not implemented for sparse matrices!i    i   t   sym_post   overwrite_a(   t   hasattrt   NotImplementedErrorR3   R(   t   flatR   R    t   solveR$   t
   dual_coef_t   X_transformed_fit_(   R   t   X_transformedR%   t	   n_samplesR:   (    (    s?   lib/python2.7/site-packages/sklearn/decomposition/kernel_pca.pyt   _fit_inverse_transform   s    #!c         C   s   t  | d d d |  j } t   |  _ |  j |  } |  j |  |  j r t j t j	 |  j
   } t j |  j |  } |  j | |  n  | |  _ |  S(   s_  Fit the model from data in X.

        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.

        Returns
        -------
        self : object
            Returns the instance itself.
        t   accept_sparset   csrt   copy(   R   R   R   R0   R(   R<   R   t   npt   diagt   sqrtR6   t   dotR7   RH   t   X_fit_(   R   R%   t   yR:   t   sqrt_lambdasRF   (    (    s?   lib/python2.7/site-packages/sklearn/decomposition/kernel_pca.pyt   fit   s    		c         K   sI   |  j  | |  |  j t j |  j  } |  j rE |  j | |  n  | S(   sl  Fit the model from data in X and transform X.

        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.

        Returns
        -------
        X_new : array-like, shape (n_samples, n_components)
        (   RS   R7   RL   RN   R6   R   RH   (   R   R%   RQ   R'   RF   (    (    s?   lib/python2.7/site-packages/sklearn/decomposition/kernel_pca.pyR1     s
    	c         C   sQ   t  |  d  |  j j |  j | |  j   } t j | |  j t j |  j	   S(   s   Transform X.

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

        Returns
        -------
        X_new : array-like, shape (n_samples, n_components)
        RP   (
   R   R0   t	   transformR(   RP   RL   RO   R7   RN   R6   (   R   R%   R:   (    (    s?   lib/python2.7/site-packages/sklearn/decomposition/kernel_pca.pyRT     s    !c         C   s@   |  j  s t d   n  |  j | |  j  } t j | |  j  S(   sI  Transform X back to original space.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_components)

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

        References
        ----------
        "Learning to Find Pre-Images", G BakIr et al, 2004.
        s|   The fit_inverse_transform parameter was not set to True when instantiating and hence the inverse transform is not available.(   R   R   R(   RE   RL   RO   RD   (   R   R%   R:   (    (    s?   lib/python2.7/site-packages/sklearn/decomposition/kernel_pca.pyt   inverse_transform-  s    	N(   t   __name__t
   __module__t   __doc__R2   t   FalseR$   R   t   propertyR    R(   R<   RH   RS   R1   RT   RU   (    (    (    s?   lib/python2.7/site-packages/sklearn/decomposition/kernel_pca.pyR
      s   z			,		(   RX   t   numpyRL   t   scipyR    t   scipy.sparse.linalgR   t   utilsR   t   utils.validationR   R   t
   exceptionsR   t   baseR   R   t   preprocessingR   t   metrics.pairwiseR	   R
   (    (    (    s?   lib/python2.7/site-packages/sklearn/decomposition/kernel_pca.pyt   <module>   s   