ó
‡ˆ\c           @   sd  d  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 m Z d d l m Z m Z d	 d
 l m Z 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 m Z d d g Z d „  Z  d d d „ Z! d „  Z" d e j# e e e ƒ f d „  ƒ  YZ$ d e$ f d „  ƒ  YZ% d e$ f d „  ƒ  YZ& d S(   sO   Spectral biclustering algorithms.

Authors : Kemal Eren
License: BSD 3 clause

iÿÿÿÿ(   t   ABCMetat   abstractmethodN(   t   norm(   t
   dia_matrixt   issparse(   t   eigsht   svdsi   (   t   KMeanst   MiniBatchKMeansi   (   t   BaseEstimatort   BiclusterMixin(   t   six(   t   check_random_state(   t   make_nonnegativet   randomized_svdt   safe_sparse_dot(   t   assert_all_finitet   check_arrayt   SpectralCoclusteringt   SpectralBiclusteringc         C   s@  t  |  ƒ }  t j d t j |  j d d ƒ ƒ ƒ j ƒ  } t j d t j |  j d d ƒ ƒ ƒ j ƒ  } t j t j | ƒ d | ƒ } t j t j | ƒ d | ƒ } t |  ƒ r|  j	 \ } } t
 | d g f d | | f ƒ} t
 | d g f d | | f ƒ} | |  | } n! | d d … t j f |  | } | | | f S(   s   Normalize ``X`` by scaling rows and columns independently.

    Returns the normalized matrix and the row and column scaling
    factors.

    g      ð?t   axisi   i    t   shapeN(   R   t   npt   asarrayt   sqrtt   sumt   squeezet   wheret   isnanR   R   R   t   newaxis(   t   Xt   row_diagt   col_diagt   n_rowst   n_colst   rt   ct   an(    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyt   _scale_normalize   s    ..!!!iè  gñhãˆµøä>c         C   sŸ   t  |  ƒ }  |  } d } x€ t | ƒ D]r } t | ƒ \ } } } t |  ƒ re t | j |  j ƒ } n t | | ƒ } | } | d k	 r% | | k  r% Pq% q% W| S(   s’   Normalize rows and columns of ``X`` simultaneously so that all
    rows sum to one constant and all columns sum to a different
    constant.

    N(   R   t   Nonet   rangeR&   R   R   t   data(   R   t   max_itert   tolt   X_scaledt   distt   _t   X_new(    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyt   _bistochastic_normalize4   s    c         C   s   t  |  d d ƒ}  t |  ƒ r- t d ƒ ‚ n  t j |  ƒ } | j d d ƒ d d … t j f } | j d d ƒ } | j ƒ  } | | | | S(   s>   Normalize ``X`` according to Kluger's log-interactions scheme.t	   min_valuei   s[   Cannot compute log of a sparse matrix, because log(x) diverges to -infinity as x goes to 0.R   Ni    (   R   R   t
   ValueErrorR   t   logt   meanR   (   R   t   Lt   row_avgt   col_avgt   avg(    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyt   _log_normalizeK   s    %t   BaseSpectralc        
   B   s\   e  Z d  Z e d d d
 e d d d
 d
 d „ ƒ Z d „  Z d
 d „ Z d „  Z	 d	 „  Z
 RS(   s%   Base class for spectral biclustering.i   t
   randomizeds	   k-means++i
   c	   	      C   sL   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ d  S(   N(   t
   n_clusterst
   svd_methodt
   n_svd_vecst
   mini_batcht   initt   n_initt   n_jobst   random_state(	   t   selfR<   R=   R>   R?   R@   RA   RB   RC   (    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyt   __init__]   s    							c         C   s7   d } |  j  | k r3 t d j |  j  | ƒ ƒ ‚ n  d  S(   NR;   t   arpacks9   Unknown SVD method: '{0}'. svd_method must be one of {1}.(   R;   RF   (   R=   R2   t   format(   RD   t   legal_svd_methods(    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyt   _check_parametersj   s
    	c         C   s6   t  | d d d t j ƒ} |  j ƒ  |  j | ƒ |  S(   s™   Creates a biclustering for X.

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

        y : Ignored

        t   accept_sparset   csrt   dtype(   R   R   t   float64RI   t   _fit(   RD   R   t   y(    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyt   fitq   s    

c         C   sÓ  |  j  d k r[ i  } |  j d k	 r4 |  j | d <n  t | | d |  j | \ } } } n1|  j  d k rŒt | d | d |  j ƒ\ } } } t j t j | ƒ ƒ rt	 | j
 | ƒ } t |  j ƒ }	 |	 j d d | j d	 ƒ }
 t | d |  j d
 |
 ƒ\ } } | j
 } n  t j t j | ƒ ƒ rŒt	 | | j
 ƒ } t |  j ƒ }	 |	 j d d | j d	 ƒ }
 t | d |  j d
 |
 ƒ\ } } qŒn  t | ƒ t | ƒ | d d … | d … f } | | } | | j
 f S(   sy   Returns first `n_components` left and right singular
        vectors u and v, discarding the first `n_discard`.

        R;   t   n_oversamplesRC   RF   t   kt   ncviÿÿÿÿi   i    t   v0N(   R=   R>   R'   R   RC   R   R   t   anyR   R   t   TR   t   uniformR   R   R   (   RD   t   arrayt   n_componentst	   n_discardt   kwargst   uR.   t   vtt   ARC   RT   t   v(    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyt   _svd€   s2    $!'


c      
   C   sŒ   |  j  r3 t | d |  j d |  j d |  j ƒ} n0 t | d |  j d |  j d |  j d |  j ƒ} | j | ƒ | j } | j	 } | | f S(   NR@   RA   RC   RB   (
   R?   R   R@   RA   RC   R   RB   RP   t   cluster_centers_t   labels_(   RD   R)   R<   t   modelt   centroidt   labels(    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyt   _k_means¦   s    						N(   t   __name__t
   __module__t   __doc__R   R'   t   FalseRE   RI   RP   R`   Rf   (    (    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyR:   Y   s   	
		&c        	   B   s8   e  Z d  Z d d d e d d d d d „ Z d „  Z RS(   sˆ  Spectral Co-Clustering algorithm (Dhillon, 2001).

    Clusters rows and columns of an array `X` to solve the relaxed
    normalized cut of the bipartite graph created from `X` as follows:
    the edge between row vertex `i` and column vertex `j` has weight
    `X[i, j]`.

    The resulting bicluster structure is block-diagonal, since each
    row and each column belongs to exactly one bicluster.

    Supports sparse matrices, as long as they are nonnegative.

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

    Parameters
    ----------
    n_clusters : integer, optional, default: 3
        The number of biclusters to find.

    svd_method : string, optional, default: 'randomized'
        Selects the algorithm for finding singular vectors. May be
        'randomized' or 'arpack'. If 'randomized', use
        :func:`sklearn.utils.extmath.randomized_svd`, which may be faster
        for large matrices. If 'arpack', use
        :func:`scipy.sparse.linalg.svds`, which is more accurate, but
        possibly slower in some cases.

    n_svd_vecs : int, optional, default: None
        Number of vectors to use in calculating the SVD. Corresponds
        to `ncv` when `svd_method=arpack` and `n_oversamples` when
        `svd_method` is 'randomized`.

    mini_batch : bool, optional, default: False
        Whether to use mini-batch k-means, which is faster but may get
        different results.

    init : {'k-means++', 'random' or an ndarray}
         Method for initialization of k-means algorithm; defaults to
         'k-means++'.

    n_init : int, optional, default: 10
        Number of random initializations that are tried with the
        k-means algorithm.

        If mini-batch k-means is used, the best initialization is
        chosen and the algorithm runs once. Otherwise, the algorithm
        is run for each initialization and the best solution chosen.

    n_jobs : int or None, optional (default=None)
        The number of jobs to use for the computation. This works by breaking
        down the pairwise matrix into n_jobs even slices and computing them in
        parallel.

        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    random_state : int, RandomState instance or None (default)
        Used for randomizing the singular value decomposition and the k-means
        initialization. Use an int to make the randomness deterministic.
        See :term:`Glossary <random_state>`.

    Attributes
    ----------
    rows_ : array-like, shape (n_row_clusters, n_rows)
        Results of the clustering. `rows[i, r]` is True if
        cluster `i` contains row `r`. Available only after calling ``fit``.

    columns_ : array-like, shape (n_column_clusters, n_columns)
        Results of the clustering, like `rows`.

    row_labels_ : array-like, shape (n_rows,)
        The bicluster label of each row.

    column_labels_ : array-like, shape (n_cols,)
        The bicluster label of each column.

    Examples
    --------
    >>> from sklearn.cluster import SpectralCoclustering
    >>> import numpy as np
    >>> X = np.array([[1, 1], [2, 1], [1, 0],
    ...               [4, 7], [3, 5], [3, 6]])
    >>> clustering = SpectralCoclustering(n_clusters=2, random_state=0).fit(X)
    >>> clustering.row_labels_
    array([0, 1, 1, 0, 0, 0], dtype=int32)
    >>> clustering.column_labels_
    array([0, 0], dtype=int32)
    >>> clustering # doctest: +NORMALIZE_WHITESPACE
    SpectralCoclustering(init='k-means++', mini_batch=False, n_clusters=2,
               n_init=10, n_jobs=None, n_svd_vecs=None, random_state=0,
               svd_method='randomized')

    References
    ----------

    * Dhillon, Inderjit S, 2001. `Co-clustering documents and words using
      bipartite spectral graph partitioning
      <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.140.3011>`__.

    i   R;   s	   k-means++i
   c	   	   	   C   s/   t  t |  ƒ j | | | | | | | | ƒ d  S(   N(   t   superR   RE   (	   RD   R<   R=   R>   R?   R@   RA   RB   RC   (    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyRE     s    c         C   sO  t  | ƒ \ } } } d t t j t j |  j ƒ ƒ ƒ } |  j | | d d ƒ\ } } t j | d  d  … t j f | | d  d  … t j f | f ƒ } |  j	 | |  j ƒ \ }	 }
 | j
 d } |
 |  |  _ |
 | |  _ t j g  t |  j ƒ D] } |  j | k ^ qó ƒ |  _ t j g  t |  j ƒ D] } |  j | k ^ q*ƒ |  _ d  S(   Ni   RZ   i    (   R&   t   intR   t   ceilt   log2R<   R`   t   vstackR   Rf   R   t   row_labels_t   column_labels_R(   t   rows_t   columns_(   RD   R   t   normalized_dataR   R    t   n_svR\   R_   t   zR.   Re   R!   R$   (    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyRN   (  s    % #	.	N(   Rg   Rh   Ri   R'   Rj   RE   RN   (    (    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyR   ¶   s
   e	
c           B   s\   e  Z d  Z d d d d d d e d d d d d „ Z d „  Z d	 „  Z d
 „  Z d „  Z	 RS(   s_  Spectral biclustering (Kluger, 2003).

    Partitions rows and columns under the assumption that the data has
    an underlying checkerboard structure. For instance, if there are
    two row partitions and three column partitions, each row will
    belong to three biclusters, and each column will belong to two
    biclusters. The outer product of the corresponding row and column
    label vectors gives this checkerboard structure.

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

    Parameters
    ----------
    n_clusters : integer or tuple (n_row_clusters, n_column_clusters)
        The number of row and column clusters in the checkerboard
        structure.

    method : string, optional, default: 'bistochastic'
        Method of normalizing and converting singular vectors into
        biclusters. May be one of 'scale', 'bistochastic', or 'log'.
        The authors recommend using 'log'. If the data is sparse,
        however, log normalization will not work, which is why the
        default is 'bistochastic'. CAUTION: if `method='log'`, the
        data must not be sparse.

    n_components : integer, optional, default: 6
        Number of singular vectors to check.

    n_best : integer, optional, default: 3
        Number of best singular vectors to which to project the data
        for clustering.

    svd_method : string, optional, default: 'randomized'
        Selects the algorithm for finding singular vectors. May be
        'randomized' or 'arpack'. If 'randomized', uses
        `sklearn.utils.extmath.randomized_svd`, which may be faster
        for large matrices. If 'arpack', uses
        `scipy.sparse.linalg.svds`, which is more accurate, but
        possibly slower in some cases.

    n_svd_vecs : int, optional, default: None
        Number of vectors to use in calculating the SVD. Corresponds
        to `ncv` when `svd_method=arpack` and `n_oversamples` when
        `svd_method` is 'randomized`.

    mini_batch : bool, optional, default: False
        Whether to use mini-batch k-means, which is faster but may get
        different results.

    init : {'k-means++', 'random' or an ndarray}
         Method for initialization of k-means algorithm; defaults to
         'k-means++'.

    n_init : int, optional, default: 10
        Number of random initializations that are tried with the
        k-means algorithm.

        If mini-batch k-means is used, the best initialization is
        chosen and the algorithm runs once. Otherwise, the algorithm
        is run for each initialization and the best solution chosen.

    n_jobs : int or None, optional (default=None)
        The number of jobs to use for the computation. This works by breaking
        down the pairwise matrix into n_jobs even slices and computing them in
        parallel.

        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    random_state : int, RandomState instance or None (default)
        Used for randomizing the singular value decomposition and the k-means
        initialization. Use an int to make the randomness deterministic.
        See :term:`Glossary <random_state>`.

    Attributes
    ----------
    rows_ : array-like, shape (n_row_clusters, n_rows)
        Results of the clustering. `rows[i, r]` is True if
        cluster `i` contains row `r`. Available only after calling ``fit``.

    columns_ : array-like, shape (n_column_clusters, n_columns)
        Results of the clustering, like `rows`.

    row_labels_ : array-like, shape (n_rows,)
        Row partition labels.

    column_labels_ : array-like, shape (n_cols,)
        Column partition labels.

    Examples
    --------
    >>> from sklearn.cluster import SpectralBiclustering
    >>> import numpy as np
    >>> X = np.array([[1, 1], [2, 1], [1, 0],
    ...               [4, 7], [3, 5], [3, 6]])
    >>> clustering = SpectralBiclustering(n_clusters=2, random_state=0).fit(X)
    >>> clustering.row_labels_
    array([1, 1, 1, 0, 0, 0], dtype=int32)
    >>> clustering.column_labels_
    array([0, 1], dtype=int32)
    >>> clustering # doctest: +NORMALIZE_WHITESPACE
    SpectralBiclustering(init='k-means++', method='bistochastic',
               mini_batch=False, n_best=3, n_clusters=2, n_components=6,
               n_init=10, n_jobs=None, n_svd_vecs=None, random_state=0,
               svd_method='randomized')

    References
    ----------

    * Kluger, Yuval, et. al., 2003. `Spectral biclustering of microarray
      data: coclustering genes and conditions
      <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.135.1608>`__.

    i   t   bistochastici   R;   s	   k-means++i
   c      	   C   sJ   t  t |  ƒ j | | | | | |	 |
 | ƒ | |  _ | |  _ | |  _ d  S(   N(   Rk   R   RE   t   methodRY   t   n_best(   RD   R<   Rx   RY   Ry   R=   R>   R?   R@   RA   RB   RC   (    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyRE   ¯  s    		c         C   sC  t  t |  ƒ j ƒ  d
 } |  j | k rF t d j |  j | ƒ ƒ ‚ n  y t |  j ƒ Wn^ t k
 r· y' |  j \ } } t | ƒ t | ƒ Wq¸ t t f k
 r³ t d ƒ ‚ q¸ Xn X|  j	 d k  râ t d j |  j	 ƒ ƒ ‚ n  |  j
 d k  rt d j |  j
 ƒ ƒ ‚ n  |  j
 |  j	 k r?t d	 j |  j
 |  j	 ƒ ƒ ‚ n  d  S(   NRw   t   scaleR3   s1   Unknown method: '{0}'. method must be one of {1}.s˜   Incorrect parameter n_clusters has value: {}. It should either be a single integer or an iterable with two integers: (n_row_clusters, n_column_clusters)i   sB   Parameter n_components must be greater than 0, but its value is {}s<   Parameter n_best must be greater than 0, but its value is {}s7   n_best cannot be larger than n_components, but {} >  {}(   Rw   Rz   R3   (   Rk   R   RI   Rx   R2   RG   Rl   R<   t	   TypeErrorRY   Ry   (   RD   t   legal_methodsR#   R$   (    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyRI   ¿  s.    	
			c         C   s÷  |  j  } |  j d k r1 t | ƒ } | d 7} nO |  j d k rb t | ƒ \ } } } | d 7} n |  j d k r€ t | ƒ } n  |  j d k r• d n d } |  j | | | ƒ \ } } | j } | j }	 y |  j \ }
 } Wn t k
 rû |  j }
 } n X|  j	 | |  j
 |
 ƒ } |  j	 |	 |  j
 | ƒ } |  j | | j |
 ƒ |  _ |  j | j | j | ƒ |  _ t j g  t |
 ƒ D]( } t | ƒ D] } |  j | k ^ qˆqxƒ |  _ t j g  t |
 ƒ D]( } t | ƒ D] } |  j | k ^ qÏq¿ƒ |  _ d  S(   NRw   i   Rz   R3   i    (   RY   Rx   R0   R&   R9   R`   RV   R<   R{   t   _fit_best_piecewiseRy   t   _project_and_clusterRp   Rq   R   Ro   R(   Rr   Rs   (   RD   R   Ru   Rt   R.   RZ   R\   R_   t   utR]   t   n_row_clusterst   n_col_clusterst   best_utt   best_vtt   label(    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyRN   Ü  s>    						.	c            sg   ‡  ‡ f d †  } t  j | d d d | ƒ} t  j t d d d | | ƒ} | t  j | ƒ |  } | S(   sØ   Find the ``n_best`` vectors that are best approximated by piecewise
        constant vectors.

        The piecewise vectors are found by k-means; the best is chosen
        according to Euclidean distance.

        c            s2   ˆ j  |  j d d ƒ ˆ  ƒ \ } } | | j ƒ  S(   Niÿÿÿÿi   (   Rf   t   reshapet   ravel(   R_   Rd   Re   (   R<   RD   (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyt   make_piecewise  s    $R   i   t   arr(   R   t   apply_along_axisR   t   argsort(   RD   t   vectorsRy   R<   R‡   t   piecewise_vectorst   distst   result(    (   R<   RD   s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyR}     s    c         C   s+   t  | | ƒ } |  j | | ƒ \ } } | S(   s7   Project ``data`` to ``vectors`` and cluster the result.(   R   Rf   (   RD   R)   R‹   R<   t	   projectedR.   Re   (    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyR~     s    N(
   Rg   Rh   Ri   R'   Rj   RE   RI   RN   R}   R~   (    (    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyR   ;  s   s				'	('   Ri   t   abcR    R   t   numpyR   t   scipy.linalgR   t   scipy.sparseR   R   t   scipy.sparse.linalgR   R   t    R   R   t   baseR	   R
   t	   externalsR   t   utilsR   t   utils.extmathR   R   R   t   utils.validationR   R   t   __all__R&   R0   R9   t   with_metaclassR:   R   R   (    (    (    s8   lib/python2.7/site-packages/sklearn/cluster/bicluster.pyt   <module>   s(   			\…