ó
\c           @   s@  d  Z  d d l 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 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	 d l m Z d   Z d   Z  d   Z! d d d d e# e# d  Z$ d e f d     YZ% d S(   s   Spectral Embeddingi˙˙˙˙(   t   divisionN(   t   sparse(   t   eigh(   t   eigsht   lobpcg(   t   connected_components(   t	   laplaciani   (   t   BaseEstimator(   t   six(   t   check_random_statet   check_arrayt   check_symmetric(   t   _deterministic_vector_sign_flip(   t
   rbf_kernel(   t   kneighbors_graphc   
      C   s1  |  j  d } t j |   r+ |  j   }  n  t j | d t j } t j | d t j } t | | <xĹ t |  D]ˇ } | j	   } t j
 | | d | | | j	   k r° Pn  t j |  d } | j t  xV | D]N } t j |   r|  | j   j   }	 n
 |  | }	 t j
 | |	 d | q× Wqr W| S(   s=  Find the largest graph connected components that contains one
    given node

    Parameters
    ----------
    graph : array-like, shape: (n_samples, n_samples)
        adjacency matrix of the graph, non-zero weight means an edge
        between the nodes

    node_id : int
        The index of the query node of the graph

    Returns
    -------
    connected_components_matrix : array-like, shape: (n_samples,)
        An array of bool value indicating the indexes of the nodes
        belonging to the largest connected components of the given query
        node
    i    t   dtypet   out(   t   shapeR   t   issparset   tocsrt   npt   zerost   boolt   Truet   ranget   sumt
   logical_ort   wheret   fillt   Falset   toarrayt   ravel(
   t   grapht   node_idt   n_nodet   connected_nodest   nodes_to_exploret   _t   last_num_componentt   indicest   it	   neighbors(    (    sC   lib/python2.7/site-packages/sklearn/manifold/spectral_embedding_.pyt   _graph_connected_component   s&    

c         C   sO   t  j |   r+ t |   \ } } | d k St |  d  j   |  j d k Sd S(   s{   Return whether the graph is connected (True) or Not (False)

    Parameters
    ----------
    graph : array-like or sparse matrix, shape: (n_samples, n_samples)
        adjacency matrix of the graph, non-zero weight means an edge
        between the nodes

    Returns
    -------
    is_connected : bool
        True means the graph is fully connected and False means not
    i   i    N(   R   t
   isspmatrixR   R*   R   R   (   R    t   n_connected_componentsR%   (    (    sC   lib/python2.7/site-packages/sklearn/manifold/spectral_embedding_.pyt   _graph_is_connectedE   s    
c         C   s˝   |  j  d } t j |   sB | rš | |  j d d | d  <qš nw |  j   }  | rv |  j |  j k } | |  j | <n  t j	 |  j |  j  j
 } | d k r­ |  j   }  n |  j   }  |  S(   sE  Set the diagonal of the laplacian matrix and convert it to a
    sparse format well suited for eigenvalue decomposition

    Parameters
    ----------
    laplacian : array or sparse matrix
        The graph laplacian
    value : float
        The value of the diagonal
    norm_laplacian : bool
        Whether the value of the diagonal should be changed or not

    Returns
    -------
    laplacian : array or sparse matrix
        An array of matrix in a form that is well suited to fast
        eigenvalue decomposition, depending on the band width of the
        matrix.
    i    Ni   i   (   R   R   R+   t   flatt   tocoot   rowt   colt   dataR   t   uniquet   sizet   todiaR   (   R   t   valuet   norm_laplaciant   n_nodest   diag_idxt   n_diags(    (    sC   lib/python2.7/site-packages/sklearn/manifold/spectral_embedding_.pyt	   _set_diag\   s     i   g        c         C   s_  t  |   }  y d d l m } Wn, t k
 rN | d k rO t d   qO n X| d k rd d } n | d  k r t d |   n  t |  } |  j d } | rŻ | d	 } n  t |   sË t	 j
 d
  n  t |  d | d t \ }	 }
 | d k s!| d k rÝt j |	  s!| d | k  rÝt |	 d	 |  }	 y |	 d 9}	 | j d d	 |	 j d  } t |	 d | d d d d d | d | \ } } | j | d d  } | rľ| |
 } n  WqÝt k
 rŮd } |	 d 9}	 qÝXn  | d k rńt j |	  st	 j
 d  n  t |	 d t j d t }	 t |	 d	 |  }	 | t |	 d   } | j   } | j |	 j d | d	  } |
 j   | d d  d f <t |	 | d | d d d t \ } } | j } | rŇ| |
 } n  | j d d	 k r0t  q0n?| d k r0t |	 d t j d t }	 | d | d	 k  rt j |	  rJ|	 j   }	 n  t |	  \ } } | j |  } | r-| |
 } q-q0t |	 d	 |  }	 | j |	 j d | d	  } |
 j   | d d  d f <t |	 | d d d t d d \ } } | j |  } | r| |
 } n  | j d d	 k r0t  q0n  t |  } | rP| d	 | !j S| |  j Sd S(!   sK  Project the sample on the first eigenvectors of the graph Laplacian.

    The adjacency matrix is used to compute a normalized graph Laplacian
    whose spectrum (especially the eigenvectors associated to the
    smallest eigenvalues) has an interpretation in terms of minimal
    number of cuts necessary to split the graph into comparably sized
    components.

    This embedding can also 'work' even if the ``adjacency`` variable is
    not strictly the adjacency matrix of a graph but more generally
    an affinity or similarity matrix between samples (for instance the
    heat kernel of a euclidean distance matrix or a k-NN matrix).

    However care must taken to always make the affinity matrix symmetric
    so that the eigenvector decomposition works as expected.

    Note : Laplacian Eigenmaps is the actual algorithm implemented here.

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

    Parameters
    ----------
    adjacency : array-like or sparse matrix, shape: (n_samples, n_samples)
        The adjacency matrix of the graph to embed.

    n_components : integer, optional, default 8
        The dimension of the projection subspace.

    eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'}, default None
        The eigenvalue decomposition strategy to use. AMG requires pyamg
        to be installed. It can be faster on very large, sparse problems,
        but may also lead to instabilities.

    random_state : int, RandomState instance or None, optional, default: None
        A pseudo random number generator used for the initialization of the
        lobpcg eigenvectors decomposition.  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
        ``solver`` == 'amg'.

    eigen_tol : float, optional, default=0.0
        Stopping criterion for eigendecomposition of the Laplacian matrix
        when using arpack eigen_solver.

    norm_laplacian : bool, optional, default=True
        If True, then compute normalized Laplacian.

    drop_first : bool, optional, default=True
        Whether to drop the first eigenvector. For spectral embedding, this
        should be True as the first eigenvector should be constant vector for
        connected graph, but for spectral clustering, this should be kept as
        False to retain the first eigenvector.

    Returns
    -------
    embedding : array, shape=(n_samples, n_components)
        The reduced samples.

    Notes
    -----
    Spectral Embedding (Laplacian Eigenmaps) is most useful when the graph
    has one connected component. If there graph has many components, the first
    few eigenvectors will simply uncover the connected components of the graph.

    References
    ----------
    * https://en.wikipedia.org/wiki/LOBPCG

    * Toward the Optimal Preconditioned Eigensolver: Locally Optimal
      Block Preconditioned Conjugate Gradient Method
      Andrew V. Knyazev
      https://doi.org/10.1137%2FS1064827500366124
    i˙˙˙˙(   t   smoothed_aggregation_solvert   amgs>   The eigen_solver was set to 'amg', but pyamg is not available.t   arpackR   sK   Unknown value for eigen_solver: '%s'.Should be 'amg', 'arpack', or 'lobpcg'i    i   sJ   Graph is not fully connected, spectral embedding may not work as expected.t   normedt   return_diagi   t   kt   sigmag      đ?t   whicht   LMt   tolt   v0Ns$   AMG works better for sparse matricesR   t   accept_sparset   csrt   Mgę-q=t   largestgVçŻŇ<t   maxiteriĐ  (   R>   R   R=   (    R   t   pyamgR<   t   ImportErrort
   ValueErrort   NoneR	   R   R-   t   warningst   warnt   csgraph_laplacianR   R   R+   R;   t   uniformR   t   Tt   RuntimeErrorR   R
   R   t   float64t   aspreconditionert   randR   R   R   R   R   R   (   t	   adjacencyt   n_componentst   eigen_solvert   random_statet	   eigen_tolR7   t
   drop_firstR<   R8   R   t   ddRF   t   lambdast   diffusion_mapt	   embeddingt   mlRI   t   X(    (    sC   lib/python2.7/site-packages/sklearn/manifold/spectral_embedding_.pyt   spectral_embedding   s    M	 
			t   SpectralEmbeddingc           B   s_   e  Z d  Z d d d d d d d d  Z e d    Z d d  Z d d  Z d d  Z	 RS(	   sY  Spectral embedding for non-linear dimensionality reduction.

    Forms an affinity matrix given by the specified function and
    applies spectral decomposition to the corresponding graph laplacian.
    The resulting transformation is given by the value of the
    eigenvectors for each data point.

    Note : Laplacian Eigenmaps is the actual algorithm implemented here.

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

    Parameters
    -----------
    n_components : integer, default: 2
        The dimension of the projected subspace.

    affinity : string or callable, default : "nearest_neighbors"
        How to construct the affinity matrix.
         - 'nearest_neighbors' : construct affinity matrix by knn graph
         - 'rbf' : construct affinity matrix by rbf kernel
         - 'precomputed' : interpret X as precomputed affinity matrix
         - callable : use passed in function as affinity
           the function takes in data matrix (n_samples, n_features)
           and return affinity matrix (n_samples, n_samples).

    gamma : float, optional, default : 1/n_features
        Kernel coefficient for rbf kernel.

    random_state : int, RandomState instance or None, optional, default: None
        A pseudo random number generator used for the initialization of the
        lobpcg eigenvectors.  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 ``solver`` ==
        'amg'.

    eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'}
        The eigenvalue decomposition strategy to use. AMG requires pyamg
        to be installed. It can be faster on very large, sparse problems,
        but may also lead to instabilities.

    n_neighbors : int, default : max(n_samples/10 , 1)
        Number of nearest neighbors for nearest_neighbors graph building.

    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.

    Attributes
    ----------

    embedding_ : array, shape = (n_samples, n_components)
        Spectral embedding of the training matrix.

    affinity_matrix_ : array, shape = (n_samples, n_samples)
        Affinity_matrix constructed from samples or precomputed.

    Examples
    --------
    >>> from sklearn.datasets import load_digits
    >>> from sklearn.manifold import SpectralEmbedding
    >>> X, _ = load_digits(return_X_y=True)
    >>> X.shape
    (1797, 64)
    >>> embedding = SpectralEmbedding(n_components=2)
    >>> X_transformed = embedding.fit_transform(X[:100])
    >>> X_transformed.shape
    (100, 2)

    References
    ----------

    - A Tutorial on Spectral Clustering, 2007
      Ulrike von Luxburg
      http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323

    - On Spectral Clustering: Analysis and an algorithm, 2001
      Andrew Y. Ng, Michael I. Jordan, Yair Weiss
      http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.8100

    - Normalized cuts and image segmentation, 2000
      Jianbo Shi, Jitendra Malik
      http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.160.2324
    i   t   nearest_neighborsc         C   sC   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ d  S(   N(   RZ   t   affinityt   gammaR\   R[   t   n_neighborst   n_jobs(   t   selfRZ   Rh   Ri   R\   R[   Rj   Rk   (    (    sC   lib/python2.7/site-packages/sklearn/manifold/spectral_embedding_.pyt   __init__Ź  s    						c         C   s   |  j  d k S(   Nt   precomputed(   Rh   (   Rl   (    (    sC   lib/python2.7/site-packages/sklearn/manifold/spectral_embedding_.pyt	   _pairwiseˇ  s    c         C   sL  |  j  d k r | |  _ |  j S|  j  d k rŮ t j |  rV t j d  d |  _  qŮ |  j d k	 rn |  j n t t	 | j
 d d  d  |  _ t | |  j d t d	 |  j |  _ d
 |  j |  j j |  _ |  j Sn  |  j  d k r3|  j d k	 r |  j n d | j
 d |  _ t | d |  j |  _ |  j S|  j  |  |  _ |  j S(   s1  Calculate the affinity matrix from data
        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training vector, where n_samples is the number of samples
            and n_features is the number of features.

            If affinity is "precomputed"
            X : array-like, shape (n_samples, n_samples),
            Interpret X as precomputed adjacency graph computed from
            samples.

        Y: Ignored

        Returns
        -------
        affinity_matrix, shape (n_samples, n_samples)
        Rn   Rg   s`   Nearest neighbors affinity currently does not support sparse input, falling back to rbf affinityt   rbfi    i
   i   t   include_selfRk   g      ŕ?g      đ?Ri   N(   Rh   t   affinity_matrix_R   R   RP   RQ   Rj   RO   t   maxt   intR   t   n_neighbors_R   R   Rk   RT   Ri   t   gamma_R   (   Rl   Rd   t   Y(    (    sC   lib/python2.7/site-packages/sklearn/manifold/spectral_embedding_.pyt   _get_affinity_matrixť  s*    	#	
,c         C   sÉ   t  | d d d |  } t |  j  } t |  j t j  rj |  j t d  k r t d |  j   q n% t	 |  j  s t d |  j   n  |  j
 |  } t | d	 |  j d
 |  j d | |  _ |  S(   s  Fit the model from data in X.

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

            If affinity is "precomputed"
            X : array-like, shape (n_samples, n_samples),
            Interpret X as precomputed adjacency graph computed from
            samples.

        Returns
        -------
        self : object
            Returns the instance itself.
        t   ensure_min_samplesi   t	   estimatorRg   Rp   Rn   s]   %s is not a valid affinity. Expected 'precomputed', 'rbf', 'nearest_neighbors' or a callable.sD   'affinity' is expected to be an affinity name or a callable. Got: %sRZ   R[   R\   (   Rg   Rp   Rn   (   R
   R	   R\   t
   isinstanceRh   R   t   string_typest   setRN   t   callableRx   Re   RZ   R[   t
   embedding_(   Rl   Rd   t   yR\   t   affinity_matrix(    (    sC   lib/python2.7/site-packages/sklearn/manifold/spectral_embedding_.pyt   fitę  s     				c         C   s   |  j  |  |  j S(   s*  Fit the model from data in X and transform X.

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

            If affinity is "precomputed"
            X : array-like, shape (n_samples, n_samples),
            Interpret X as precomputed adjacency graph computed from
            samples.

        Returns
        -------
        X_new : array-like, shape (n_samples, n_components)
        (   R   R   (   Rl   Rd   R   (    (    sC   lib/python2.7/site-packages/sklearn/manifold/spectral_embedding_.pyt   fit_transform  s    N(
   t   __name__t
   __module__t   __doc__RO   Rm   t   propertyRo   Rx   R   R   (    (    (    sC   lib/python2.7/site-packages/sklearn/manifold/spectral_embedding_.pyRf   T  s   V		/((&   R   t
   __future__R    RP   t   numpyR   t   scipyR   t   scipy.linalgR   t   scipy.sparse.linalgR   R   t   scipy.sparse.csgraphR   R   RR   t   baseR   t	   externalsR   t   utilsR	   R
   R   t   utils.extmathR   t   metrics.pairwiseR   R)   R   R*   R-   R;   RO   R   Re   Rf   (    (    (    sC   lib/python2.7/site-packages/sklearn/manifold/spectral_embedding_.pyt   <module>   s*   	+		,Ę