
\c           @   s  d  Z  d d l m Z d d l Z d d l Z d d l j 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 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 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) d d l* m+ Z+ e, d  Z- d   Z. d   Z/ d   Z0 e, d d d d  e1 d! e, e2 e, d e1 d"  Z3 d  d e1 e, e, d! e2 d#  Z4 d  d e1 e, e, d! e2 d$  Z5 d%   Z6 e2 e, d&  Z7 e, e, e, d'  Z8 d( e
 e e f d)     YZ9 e1 e, d* e1 d+  Z: d, d-  Z; d. e9 f d/     YZ< d S(0   s   K-means clusteringi(   t   divisionNi   (   t   BaseEstimatort   ClusterMixint   TransformerMixin(   t   euclidean_distances(   t   pairwise_distances_argmin_min(   t	   row_normst   squared_normt   stable_cumsum(   t   assign_rows_csr(   t   mean_variance_axis(   t   _num_samples(   t   check_array(   t   gen_batches(   t   check_random_state(   t   check_is_fitted(   t   FLOAT_DTYPES(   t   Parallel(   t   delayed(   t   effective_n_jobs(   t   string_types(   t   ConvergenceWarningi   (   t   _k_means(   t   k_means_elkanc         C   s  |  j  \ } } t j | | f d |  j } | d k	 sE t d   | d k rm d t t j |   } n  | j |  } t	 j
 |   r |  | j   | d <n |  | | d <t | d t j f |  d | d t }	 |	 j   }
 xt d |  D]} | j |  |
 } t j t |	  |  } t |  | |  d | d t } d } d } d } xg t |  D]Y } t j |	 | |  } | j   } | d k s| | k  rc| | } | } | } qcqcWt	 j
 |   r|  | j   | | <n |  | | | <| }
 | }	 q W| S(	   sT  Init n_clusters seeds according to k-means++

    Parameters
    -----------
    X : array or sparse matrix, shape (n_samples, n_features)
        The data to pick seeds for. To avoid memory copy, the input data
        should be double precision (dtype=np.float64).

    n_clusters : integer
        The number of seeds to choose

    x_squared_norms : array, shape (n_samples,)
        Squared Euclidean norm of each data point.

    random_state : int, RandomState instance
        The generator used to initialize the centers. Use an int to make the
        randomness deterministic.
        See :term:`Glossary <random_state>`.

    n_local_trials : integer, optional
        The number of seeding trials for each center (except the first),
        of which the one reducing inertia the most is greedily chosen.
        Set to None to make the number of trials depend logarithmically
        on the number of seeds (2+log(k)); this is the default.

    Notes
    -----
    Selects initial cluster centers for k-mean clustering in a smart way
    to speed up convergence. see: Arthur, D. and Vassilvitskii, S.
    "k-means++: the advantages of careful seeding". ACM-SIAM symposium
    on Discrete algorithms. 2007

    Version ported from http://www.stanford.edu/~darthur/kMeansppTest.zip,
    which is the implementation used in the aforementioned paper.
    t   dtypes   x_squared_norms None in _k_initi   i    t   Y_norm_squaredt   squaredi   N(   t   shapet   npt   emptyR   t   Nonet   AssertionErrort   intt   logt   randintt   spt   issparset   toarrayR   t   newaxist   Truet   sumt   ranget   random_samplet   searchsortedR   t   minimum(   t   Xt
   n_clusterst   x_squared_normst   random_statet   n_local_trialst	   n_samplest
   n_featurest   centerst	   center_idt   closest_dist_sqt   current_pott   ct	   rand_valst   candidate_idst   distance_to_candidatest   best_candidatet   best_pott   best_dist_sqt   trialt   new_dist_sqt   new_pot(    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   _k_init-   sH    $			

c         C   ss   t  |  | k r. t d | j | f   n  | j d |  j d k ro t d | j d |  j d f   n  d S(   s3   Check if centers is compatible with X and n_centerssN   The shape of the initial centers (%s) does not match the number of clusters %ii   sf   The number of features of the initial centers %s does not match the number of features of the data %s.N(   t   lent
   ValueErrorR   (   R-   t	   n_centersR4   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   _validate_center_shape   s    c         C   sN   t  j |   r( t |  d d d } n t j |  d d } t j |  | S(   s6   Return a tolerance which is independent of the datasett   axisi    i   (   R#   R$   R
   R   t   vart   mean(   R-   t   tolt	   variances(    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt
   _tolerance   s    c         C   s   |  j  d } | d k r/ t j | d |  j St j |  } | t |  k ro t d | t |  f   n  | | j   } | | j	 |  j  Sd S(   s6   Set sample_weight if None, and check for correct dtypei    R   s/   n_samples=%d should be == len(sample_weight)=%dN(
   R   R   R   t   onesR   t   asarrayRC   RD   R(   t   astype(   R-   t   sample_weightR2   t   scale(    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   _check_sample_weight   s    s	   k-means++t   autoi
   i,  g-C6?c            sx  | d k r t  d |   n  t |	  }	  d k rJ t  d    n  |
 rV d n d# } t   d d d t j t j g d | d	 |
   t     k  r t  d
 t     f   n  t       d k r   j	 d }  | d k   n" t
  t  r
n t  d    t  d  rt  d   j j d	 t  t      | d k rt j d | t d d d } qn  t j    s  j d d  }   | 8  t  d  r | 8 qn  t   d t 	 d$ \ } } }  d k r	d } n  | d k r3t j    r*d n d } n  | d k rHt  n+ | d k r]t  n t  d t |    t |  d k r&xWt |  D] }      d  d  d  d  d  d 	 d |	 \ } } } } | d# k s| | k  r| j   } | j   } | } | } qqWn |	 j t j t j   j! d | } t" d  | d d            	 f
 d!   | D  } t# |   \ } } } } t j$ |  } | | } | | } | | } | | } t j    s|
 s  | 7  n  | | 7} n  t% t& |   } |  k  rQt j d" j' |   t( d d n  | rg| | | | f S| | | f Sd# S(%   s5  K-means clustering algorithm.

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

    Parameters
    ----------
    X : array-like or sparse matrix, shape (n_samples, n_features)
        The observations to cluster. It must be noted that the data
        will be converted to C ordering, which will cause a memory copy
        if the given data is not C-contiguous.

    n_clusters : int
        The number of clusters to form as well as the number of
        centroids to generate.

    sample_weight : array-like, shape (n_samples,), optional
        The weights for each observation in X. If None, all observations
        are assigned equal weight (default: None)

    init : {'k-means++', 'random', or ndarray, or a callable}, optional
        Method for initialization, default to 'k-means++':

        'k-means++' : selects initial cluster centers for k-mean
        clustering in a smart way to speed up convergence. See section
        Notes in k_init for more details.

        'random': choose k observations (rows) at random from data for
        the initial centroids.

        If an ndarray is passed, it should be of shape (n_clusters, n_features)
        and gives the initial centers.

        If a callable is passed, it should take arguments X, k and
        and a random state and return an initialization.

    precompute_distances : {'auto', True, False}
        Precompute distances (faster but takes more memory).

        'auto' : do not precompute distances if n_samples * n_clusters > 12
        million. This corresponds to about 100MB overhead per job using
        double precision.

        True : always precompute distances

        False : never precompute distances

    n_init : int, optional, default: 10
        Number of time the k-means algorithm will be run with different
        centroid seeds. The final results will be the best output of
        n_init consecutive runs in terms of inertia.

    max_iter : int, optional, default 300
        Maximum number of iterations of the k-means algorithm to run.

    verbose : boolean, optional
        Verbosity mode.

    tol : float, optional
        The relative increment in the results before declaring convergence.

    random_state : int, RandomState instance or None (default)
        Determines random number generation for centroid initialization. Use
        an int to make the randomness deterministic.
        See :term:`Glossary <random_state>`.

    copy_x : boolean, optional
        When pre-computing distances it is more numerically accurate to center
        the data first.  If copy_x is True (default), then the original data is
        not modified, ensuring X is C-contiguous.  If False, the original data
        is modified, and put back before the function returns, but small
        numerical differences may be introduced by subtracting and then adding
        the data mean, in this case it will also not ensure that data is
        C-contiguous which may cause a significant slowdown.

    n_jobs : int or None, optional (default=None)
        The number of jobs to use for the computation. This works by computing
        each of the n_init runs 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.

    algorithm : "auto", "full" or "elkan", default="auto"
        K-means algorithm to use. The classical EM-style algorithm is "full".
        The "elkan" variation is more efficient by using the triangle
        inequality, but currently doesn't support sparse data. "auto" chooses
        "elkan" for dense data and "full" for sparse data.

    return_n_iter : bool, optional
        Whether or not to return the number of iterations.

    Returns
    -------
    centroid : float ndarray with shape (k, n_features)
        Centroids found at the last iteration of k-means.

    label : integer ndarray with shape (n_samples,)
        label[i] is the code or index of the centroid the
        i'th observation is closest to.

    inertia : float
        The final value of the inertia criterion (sum of squared distances to
        the closest centroid for all observations in the training set).

    best_n_iter : int
        Number of iterations corresponding to the best results.
        Returned only if `return_n_iter` is set to True.

    i    sF   Invalid number of initializations. n_init=%d must be bigger than zero.s@   Number of iterations should be a positive number, got %d insteadt   Ct   accept_sparset   csrR   t   ordert   copys'   n_samples=%d should be >= n_clusters=%dRS   g    `fAsQ   precompute_distances should be 'auto' or True/False, but a value of %r was passedt	   __array__i   sa   Explicit initial center position passed: performing only one init in k-means instead of n_init=%dt
   stackleveli   RG   R   t   fullt   elkans3   Algorithm must be 'auto', 'full' or 'elkan', got %st   max_itert   initt   verboset   precompute_distancesRJ   R/   R0   t   sizet   n_jobsc         3   sQ   |  ]G } t        d   d  d  d  d  d 	 d | Vq d S(   R]   R^   R_   RJ   R`   R/   R0   N(   R   (   t   .0t   seed(
   R-   R^   t   kmeans_singleR]   R.   R`   RP   RJ   R_   R/   (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pys	   <genexpr>  s   sk   Number of distinct clusters ({}) found smaller than n_clusters ({}). Possibly due to duplicate points in X.N(   NNN()   RD   R   R   R   R   t   float64t   float32R   RL   R   t
   isinstancet   boolt   hasattrR   t   typeR'   RF   t   warningst   warnt   RuntimeWarningR#   R$   RI   R   t   _kmeans_single_lloydt   _kmeans_single_elkant   strR   R)   RX   R"   t   iinfot   int32t   maxR   t   zipt   argminRC   t   sett   formatR   (   R-   R.   RP   R^   R`   t   n_initR]   R_   RJ   R0   t   copy_xRb   t	   algorithmt   return_n_iterRW   R2   t   X_meant   best_labelst   best_inertiat   best_centerst   itt   labelst   inertiaR4   t   n_iter_t   best_n_itert   seedst   resultst   n_iterst   bestt   distinct_clusters(    (
   R-   R^   Re   R]   R.   R`   RP   RJ   R_   R/   s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   k_means   s    q!

			$'



	c
         C   sN  t  j |   r t d   n  t |  } | d  k rK t |  d t } n  t |  | | d | d | }
 t j	 |
  }
 | r d GHn  t
 |  |  } t |  | | |
 d | d | d | \ }
 } } | d  k r t j |  |
 | d	 d
 t j } nF t j |  |
 | d	 d d d
 t j | } t j | d
 t j } | | |
 | f S(   Ns2   algorithm='elkan' not supported for sparse input XR   R0   R/   s   Initialization completeRJ   R]   R_   i   R   RG   i   (   R#   R$   t	   TypeErrorR   R   R   R'   t   _init_centroidsR   t   ascontiguousarrayRR   R   R(   Rf   (   R-   RP   R.   R]   R^   R_   R/   R0   RJ   R`   R4   t   checked_sample_weightR   t   n_iterR   t   sq_distances(    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyRp     s(    		'c
      
   C   s  t  |  } t |  |  } d \ }
 } } t |  | | d | d | } | rV d GHn  t j d |  j d f d |  j  } xt |  D]} | j	   } t
 |  | | | d |	 d | \ } } t j |   r t j |  | | | |  } n t j |  | | | |  } | r!d	 | | f GHn  | d k s9| | k  rZ| j	   }
 | j	   } | } n  t | |  } | | k r | rd
 | | | f GHn  Pq q W| d k rt
 |  | | | d |	 d | \ }
 } n  |
 | | | d f S(   s  A single run of k-means, assumes preparation completed prior.

    Parameters
    ----------
    X : array-like of floats, shape (n_samples, n_features)
        The observations to cluster.

    n_clusters : int
        The number of clusters to form as well as the number of
        centroids to generate.

    sample_weight : array-like, shape (n_samples,)
        The weights for each observation in X.

    max_iter : int, optional, default 300
        Maximum number of iterations of the k-means algorithm to run.

    init : {'k-means++', 'random', or ndarray, or a callable}, optional
        Method for initialization, default to 'k-means++':

        'k-means++' : selects initial cluster centers for k-mean
        clustering in a smart way to speed up convergence. See section
        Notes in k_init for more details.

        'random': choose k observations (rows) at random from data for
        the initial centroids.

        If an ndarray is passed, it should be of shape (k, p) and gives
        the initial centers.

        If a callable is passed, it should take arguments X, k and
        and a random state and return an initialization.

    tol : float, optional
        The relative increment in the results before declaring convergence.

    verbose : boolean, optional
        Verbosity mode

    x_squared_norms : array
        Precomputed x_squared_norms.

    precompute_distances : boolean, default: True
        Precompute distances (faster but takes more memory).

    random_state : int, RandomState instance or None (default)
        Determines random number generation for centroid initialization. Use
        an int to make the randomness deterministic.
        See :term:`Glossary <random_state>`.

    Returns
    -------
    centroid : float ndarray with shape (k, n_features)
        Centroids found at the last iteration of k-means.

    label : integer ndarray with shape (n_samples,)
        label[i] is the code or index of the centroid the
        i'th observation is closest to.

    inertia : float
        The final value of the inertia criterion (sum of squared distances to
        the closest centroid for all observations in the training set).

    n_iter : int
        Number of iterations run.
    R0   R/   s   Initialization completeR   i    R   R`   t	   distancess   Iteration %2d, inertia %.3fs>   Converged at iteration %d: center shift %e within tolerance %ei   N(   NNN(   R   RR   R   R   R   t   zerosR   R   R)   RX   t   _labels_inertiaR#   R$   R   t   _centers_sparset   _centers_denseR   (   R-   RP   R.   R]   R^   R_   R/   R0   RJ   R`   R~   R   R   R4   R   t   it   centers_oldR   R   t   center_shift_total(    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyRo     sF    F	%	c   	      C   s   |  j  d } t d |  d | d d d i t d 6 \ } } | j t j  } | | j  d k rj | | (n  | | j   } | | f S(   sh  Compute labels and inertia using a full distance matrix.

    This will overwrite the 'distances' array in-place.

    Parameters
    ----------
    X : numpy array, shape (n_sample, n_features)
        Input data.

    sample_weight : array-like, shape (n_samples,)
        The weights for each observation in X.

    x_squared_norms : numpy array, shape (n_samples,)
        Precomputed squared norms of X.

    centers : numpy array, shape (n_clusters, n_features)
        Cluster centers which data is assigned to.

    distances : numpy array, shape (n_samples,)
        Pre-allocated array in which distances are stored.

    Returns
    -------
    labels : numpy array, dtype=np.int, shape (n_samples,)
        Indices of clusters that samples are assigned to.

    inertia : float
        Sum of squared distances of samples to their closest cluster center.

    i    R-   t   Yt   metrict	   euclideant   metric_kwargsR   (   R   R   R'   RO   R   Rs   R(   (	   R-   RP   R/   R4   R   R2   R   t   mindistR   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt    _labels_inertia_precompute_denseG  s     (
c   	      C   s   |  j  d } t |  |  } t j | d t j  } | d k r^ t j d d d |  j  } n  t j	 |   r t
 j |  | | | | d | } n= | r t |  | | | |  St
 j |  | | | | d | } | | f S(   sL  E step of the K-means EM algorithm.

    Compute the labels and the inertia of the given samples and centers.
    This will compute the distances in-place.

    Parameters
    ----------
    X : float64 array-like or CSR sparse matrix, shape (n_samples, n_features)
        The input samples to assign to the labels.

    sample_weight : array-like, shape (n_samples,)
        The weights for each observation in X.

    x_squared_norms : array, shape (n_samples,)
        Precomputed squared euclidean norm of each data point, to speed up
        computations.

    centers : float array, shape (k, n_features)
        The cluster centers.

    precompute_distances : boolean, default: True
        Precompute distances (faster but takes more memory).

    distances : float array, shape (n_samples,)
        Pre-allocated array to be filled in with each sample's distance
        to the closest center.

    Returns
    -------
    labels : int array of shape(n)
        The resulting assignment

    inertia : float
        Sum of squared distances of samples to their closest cluster center.
    i    iR   R   R   N(   i    (   R   RR   R   R[   Rs   R   R   R   R#   R$   R   t   _assign_labels_csrR   t   _assign_labels_array(	   R-   RP   R/   R4   R`   R   R2   R   R   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyR   w  s"    %		c   
      C   s  t  |  } |  j d } | d k r: t |  d t } n  | d k	 r | | k  r | | k  r t j d | | f t d d d | } n  | j d | |  } |  | }  | | } |  j d } n% | | k  r t	 d | | f   n  t
 | t  r"| d k r"t |  | d	 | d
 | } n t
 | t  r]| d k r]| j |  |  }	 |  |	 } n t | d  rt j | d |  j } nX t |  r| |  | d	 | } t j | d |  j } n t	 d | t |  f   t j |  r| j   } n  t |  | |  | S(   s+  Compute the initial centroids

    Parameters
    ----------

    X : array, shape (n_samples, n_features)

    k : int
        number of centroids

    init : {'k-means++', 'random' or ndarray or callable} optional
        Method for initialization

    random_state : int, RandomState instance or None (default)
        Determines random number generation for centroid initialization. Use
        an int to make the randomness deterministic.
        See :term:`Glossary <random_state>`.

    x_squared_norms :  array, shape (n_samples,), optional
        Squared euclidean norm of each data point. Pass it if you have it at
        hands already to avoid it being recomputed here. Default: None

    init_size : int, optional
        Number of samples to randomly sample for speeding up the
        initialization (sometimes at the expense of accuracy): the
        only algorithm is initialized by running a batch KMeans on a
        random subset of the data. This needs to be larger than k.

    Returns
    -------
    centers : array, shape(k, n_features)
    i    R   s:   init_size=%d should be larger than k=%d. Setting it to 3*kRZ   i   i   s'   n_samples=%d should be larger than k=%ds	   k-means++R0   R/   t   randomRY   R   sp   the init parameter for the k-means should be 'k-means++' or 'random' or an ndarray, '%s' (type '%s') was passed.N(   R   R   R   R   R'   Rl   Rm   Rn   R"   RD   Rh   R   RB   t   permutationRj   R   t   arrayR   t   callableRN   Rk   R#   R$   R%   RF   (
   R-   t   kR^   R0   R/   t	   init_sizeR2   t   init_indicesR4   R   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyR     sF    "


t   KMeansc           B   s   e  Z d  Z d d d d d d d d e d d d  Z d	   Z d d d
  Z d d d  Z d d d  Z	 d   Z
 d   Z d d  Z d d d  Z RS(   s  K-Means clustering

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

    Parameters
    ----------

    n_clusters : int, optional, default: 8
        The number of clusters to form as well as the number of
        centroids to generate.

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

        'k-means++' : selects initial cluster centers for k-mean
        clustering in a smart way to speed up convergence. See section
        Notes in k_init for more details.

        'random': choose k observations (rows) at random from data for
        the initial centroids.

        If an ndarray is passed, it should be of shape (n_clusters, n_features)
        and gives the initial centers.

    n_init : int, default: 10
        Number of time the k-means algorithm will be run with different
        centroid seeds. The final results will be the best output of
        n_init consecutive runs in terms of inertia.

    max_iter : int, default: 300
        Maximum number of iterations of the k-means algorithm for a
        single run.

    tol : float, default: 1e-4
        Relative tolerance with regards to inertia to declare convergence

    precompute_distances : {'auto', True, False}
        Precompute distances (faster but takes more memory).

        'auto' : do not precompute distances if n_samples * n_clusters > 12
        million. This corresponds to about 100MB overhead per job using
        double precision.

        True : always precompute distances

        False : never precompute distances

    verbose : int, default 0
        Verbosity mode.

    random_state : int, RandomState instance or None (default)
        Determines random number generation for centroid initialization. Use
        an int to make the randomness deterministic.
        See :term:`Glossary <random_state>`.

    copy_x : boolean, optional
        When pre-computing distances it is more numerically accurate to center
        the data first.  If copy_x is True (default), then the original data is
        not modified, ensuring X is C-contiguous.  If False, the original data
        is modified, and put back before the function returns, but small
        numerical differences may be introduced by subtracting and then adding
        the data mean, in this case it will also not ensure that data is
        C-contiguous which may cause a significant slowdown.

    n_jobs : int or None, optional (default=None)
        The number of jobs to use for the computation. This works by computing
        each of the n_init runs 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.

    algorithm : "auto", "full" or "elkan", default="auto"
        K-means algorithm to use. The classical EM-style algorithm is "full".
        The "elkan" variation is more efficient by using the triangle
        inequality, but currently doesn't support sparse data. "auto" chooses
        "elkan" for dense data and "full" for sparse data.

    Attributes
    ----------
    cluster_centers_ : array, [n_clusters, n_features]
        Coordinates of cluster centers. If the algorithm stops before fully
        converging (see ``tol`` and ``max_iter``), these will not be
        consistent with ``labels_``.

    labels_ :
        Labels of each point

    inertia_ : float
        Sum of squared distances of samples to their closest cluster center.

    n_iter_ : int
        Number of iterations run.

    Examples
    --------

    >>> from sklearn.cluster import KMeans
    >>> import numpy as np
    >>> X = np.array([[1, 2], [1, 4], [1, 0],
    ...               [10, 2], [10, 4], [10, 0]])
    >>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
    >>> kmeans.labels_
    array([1, 1, 1, 0, 0, 0], dtype=int32)
    >>> kmeans.predict([[0, 0], [12, 3]])
    array([1, 0], dtype=int32)
    >>> kmeans.cluster_centers_
    array([[10.,  2.],
           [ 1.,  2.]])

    See also
    --------

    MiniBatchKMeans
        Alternative online implementation that does incremental updates
        of the centers positions using mini-batches.
        For large scale learning (say n_samples > 10k) MiniBatchKMeans is
        probably much faster than the default batch implementation.

    Notes
    ------
    The k-means problem is solved using either Lloyd's or Elkan's algorithm.

    The average complexity is given by O(k n T), were n is the number of
    samples and T is the number of iteration.

    The worst case complexity is given by O(n^(k+2/p)) with
    n = n_samples, p = n_features. (D. Arthur and S. Vassilvitskii,
    'How slow is the k-means method?' SoCG2006)

    In practice, the k-means algorithm is very fast (one of the fastest
    clustering algorithms available), but it falls in local minima. That's why
    it can be useful to restart it several times.

    If the algorithm stops before fully converging (because of ``tol`` or
    ``max_iter``), ``labels_`` and ``cluster_centers_`` will not be consistent,
    i.e. the ``cluster_centers_`` will not be the means of the points in each
    cluster. Also, the estimator will reassign ``labels_`` after the last
    iteration to make ``labels_`` consistent with ``predict`` on the training
    set.

    i   s	   k-means++i
   i,  g-C6?RS   i    c         C   sg   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ |	 |  _ |
 |  _	 | |  _
 d  S(   N(   R.   R^   R]   RJ   R`   Ry   R_   R0   Rz   Rb   R{   (   t   selfR.   R^   Ry   R]   RJ   R`   R_   R0   Rz   Rb   R{   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   __init__  s    										c         C   s`   t  | d d d t } | j \ } } |  j j d } | | k s\ t d | | f   n  | S(   NRU   RV   R   i   s:   Incorrect number of features. Got %d features, expected %d(   R   R   R   t   cluster_centers_RD   (   R   R-   R2   R3   t   expected_n_features(    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   _check_test_data  s    c         C   s   t  |  j  } t | d |  j d | d |  j d |  j d |  j d |  j d |  j d |  j	 d	 | d
 |  j
 d |  j d |  j d t \ |  _ |  _ |  _ |  _ |  S(   s|  Compute k-means clustering.

        Parameters
        ----------
        X : array-like or sparse matrix, shape=(n_samples, n_features)
            Training instances to cluster. It must be noted that the data
            will be converted to C ordering, which will cause a memory
            copy if the given data is not C-contiguous.

        y : Ignored
            not used, present here for API consistency by convention.

        sample_weight : array-like, shape (n_samples,), optional
            The weights for each observation in X. If None, all observations
            are assigned equal weight (default: None)

        R.   RP   R^   Ry   R]   R_   R`   RJ   R0   Rz   Rb   R{   R|   (   R   R0   R   R.   R^   Ry   R]   R_   R`   RJ   Rz   Rb   R{   R'   R   t   labels_t   inertia_R   (   R   R-   t   yRP   R0   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   fit  s    	!c         C   s   |  j  | d | j S(   s  Compute cluster centers and predict cluster index for each sample.

        Convenience method; equivalent to calling fit(X) followed by
        predict(X).

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            New data to transform.

        y : Ignored
            not used, present here for API consistency by convention.

        sample_weight : array-like, shape (n_samples,), optional
            The weights for each observation in X. If None, all observations
            are assigned equal weight (default: None)

        Returns
        -------
        labels : array, shape [n_samples,]
            Index of the cluster each sample belongs to.
        RP   (   R   R   (   R   R-   R   RP   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   fit_predict  s    c         C   s   |  j  | d | j |  S(   s  Compute clustering and transform X to cluster-distance space.

        Equivalent to fit(X).transform(X), but more efficiently implemented.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            New data to transform.

        y : Ignored
            not used, present here for API consistency by convention.

        sample_weight : array-like, shape (n_samples,), optional
            The weights for each observation in X. If None, all observations
            are assigned equal weight (default: None)

        Returns
        -------
        X_new : array, shape [n_samples, k]
            X transformed in the new space.
        RP   (   R   t
   _transform(   R   R-   R   RP   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   fit_transform  s    c         C   s)   t  |  d  |  j |  } |  j |  S(   s  Transform X to a cluster-distance space.

        In the new space, each dimension is the distance to the cluster
        centers.  Note that even if X is sparse, the array returned by
        `transform` will typically be dense.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            New data to transform.

        Returns
        -------
        X_new : array, shape [n_samples, k]
            X transformed in the new space.
        R   (   R   R   R   (   R   R-   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt	   transform  s    c         C   s   t  | |  j  S(   s-   guts of transform method; no input validation(   R   R   (   R   R-   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyR     s    c         C   sH   t  |  d  |  j |  } t | d t } t | | | |  j  d S(   s  Predict the closest cluster each sample in X belongs to.

        In the vector quantization literature, `cluster_centers_` is called
        the code book and each value returned by `predict` is the index of
        the closest code in the code book.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            New data to predict.

        sample_weight : array-like, shape (n_samples,), optional
            The weights for each observation in X. If None, all observations
            are assigned equal weight (default: None)

        Returns
        -------
        labels : array, shape [n_samples,]
            Index of the cluster each sample belongs to.
        R   R   i    (   R   R   R   R'   R   R   (   R   R-   RP   R/   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   predict  s
    c         C   sI   t  |  d  |  j |  } t | d t } t | | | |  j  d S(   s[  Opposite of the value of X on the K-means objective.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            New data.

        y : Ignored
            not used, present here for API consistency by convention.

        sample_weight : array-like, shape (n_samples,), optional
            The weights for each observation in X. If None, all observations
            are assigned equal weight (default: None)

        Returns
        -------
        score : float
            Opposite of the value of X on the K-means objective.
        R   R   i   (   R   R   R   R'   R   R   (   R   R-   R   RP   R/   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   score9  s
    N(   t   __name__t
   __module__t   __doc__R   R'   R   R   R   R   R   R   R   R   R   (    (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyR     s   						g{Gz?c      
   C   s  t  |  | | | d | \ } } | ro|
 d k rot |	  }	 | |
 | j   k  } | j   d |  j d k r t j |  t d |  j d  } t | | <n  | j   } | rT|	 j	 |  j d d t d | } | r d | GHn  t
 j |   rCt
 j |  rCt |  | j t j  t j |  d j t j  |  qT|  | | | <n  t j | |  | | <n  t
 j |   r| t j |  | | | | | | |  f S| j d } d } x t |  D] } | | k } | | j   } | d k r| r| | | (n  | | c | | 9<| | c t j |  | | | t j f d d 7<| | c | 7<| | | | | | <| r| | j   | j   } | t j | |  7} qqqW| | f S(	   s  Incremental update of the centers for the Minibatch K-Means algorithm.

    Parameters
    ----------

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

    sample_weight : array-like, shape (n_samples,)
        The weights for each observation in X.

    x_squared_norms : array, shape (n_samples,)
        Squared euclidean norm of each data point.

    centers : array, shape (k, n_features)
        The cluster centers. This array is MODIFIED IN PLACE

    counts : array, shape (k,)
         The vector in which we keep track of the numbers of elements in a
         cluster. This array is MODIFIED IN PLACE

    distances : array, dtype float, shape (n_samples), optional
        If not None, should be a pre-allocated array that will be used to store
        the distances of each sample to its closest center.
        May not be None when random_reassign is True.

    random_state : int, RandomState instance or None (default)
        Determines random number generation for centroid initialization and to
        pick new clusters amongst observations with uniform probability. Use
        an int to make the randomness deterministic.
        See :term:`Glossary <random_state>`.

    random_reassign : boolean, optional
        If True, centers with very low counts are randomly reassigned
        to observations.

    reassignment_ratio : float, optional
        Control the fraction of the maximum number of counts for a
        center to be reassigned. A higher value means that low count
        centers are more likely to be reassigned, which means that the
        model will take longer to converge, but should converge in a
        better clustering.

    verbose : bool, optional, default False
        Controls the verbosity.

    compute_squared_diff : bool
        If set to False, the squared diff computation is skipped.

    old_center_buffer : int
        Copy of old centers for monitoring convergence.

    Returns
    -------
    inertia : float
        Sum of squared distances of samples to their closest cluster center.

    squared_diff : numpy array, shape (n_clusters,)
        Squared distances between previous and updated cluster centers.

    R   i    g      ?t   replaceRa   s1   [MiniBatchKMeans] Reassigning %i cluster centers.g        RG   (   R   R   Rt   R(   R   R   t   argsortR    t   Falset   choiceR#   R$   R	   RO   t   intpt   wheret   minR   t   _mini_batch_update_csrR)   R&   t   ravelt   dot(   R-   RP   R/   R4   t   weight_sumst   old_center_buffert   compute_squared_diffR   t   random_reassignR0   t   reassignment_ratioR_   t   nearest_centerR   t   to_reassignt   indices_dont_reassignt   n_reassignst   new_centersR   t   squared_difft
   center_idxt   center_maskt   wsumt   diff(    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   _mini_batch_stepU  sX    C		$		
	
 i    c	         C   s  | |  j  } | |  j  } | j d  }	 | j d  }
 |	 d k rS | }	 | }
 n_ t |  j   d | d } | d k r d n | } |	 d | | | }	 |
 d | | | }
 | r d | d | | |
 f } | GHn  | d k r|	 | k r| rd | d | f GHn  t S| j d	  } | j d
 d  } | d k sK|
 | k  rZd } |
 } n
 | d 7} |  j d k	 r| |  j k r| rd | d | f GHn  t S|	 | d <|
 | d <| | d	 <| | d
 <t S(   s7   Helper function to encapsulate the early stopping logict   ewa_difft   ewa_inertiag       @i   g      ?sC   Minibatch iteration %d/%d: mean batch inertia: %f, ewa inertia: %f g        s3   Converged (small centers change) at iteration %d/%dt   ewa_inertia_mint   no_improvementi    s=   Converged (lack of improvement in inertia) at iteration %d/%dN(   t
   batch_sizet   getR   t   floatR'   t   max_no_improvementR   (   t   modelt   iteration_idxR   RJ   R2   t   centers_squared_difft   batch_inertiat   contextR_   R   R   t   alphat   progress_msgR   R   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   _mini_batch_convergence  sL    	
	




t   MiniBatchKMeansc           B   sn   e  Z d  Z d d d d d e d d d d d d d	  Z d d d
  Z d   Z d d d  Z d d  Z	 RS(   s  Mini-Batch K-Means clustering

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

    Parameters
    ----------

    n_clusters : int, optional, default: 8
        The number of clusters to form as well as the number of
        centroids to generate.

    init : {'k-means++', 'random' or an ndarray}, default: 'k-means++'
        Method for initialization, defaults to 'k-means++':

        'k-means++' : selects initial cluster centers for k-mean
        clustering in a smart way to speed up convergence. See section
        Notes in k_init for more details.

        'random': choose k observations (rows) at random from data for
        the initial centroids.

        If an ndarray is passed, it should be of shape (n_clusters, n_features)
        and gives the initial centers.

    max_iter : int, optional
        Maximum number of iterations over the complete dataset before
        stopping independently of any early stopping criterion heuristics.

    batch_size : int, optional, default: 100
        Size of the mini batches.

    verbose : boolean, optional
        Verbosity mode.

    compute_labels : boolean, default=True
        Compute label assignment and inertia for the complete dataset
        once the minibatch optimization has converged in fit.

    random_state : int, RandomState instance or None (default)
        Determines random number generation for centroid initialization and
        random reassignment. Use an int to make the randomness deterministic.
        See :term:`Glossary <random_state>`.

    tol : float, default: 0.0
        Control early stopping based on the relative center changes as
        measured by a smoothed, variance-normalized of the mean center
        squared position changes. This early stopping heuristics is
        closer to the one used for the batch variant of the algorithms
        but induces a slight computational and memory overhead over the
        inertia heuristic.

        To disable convergence detection based on normalized center
        change, set tol to 0.0 (default).

    max_no_improvement : int, default: 10
        Control early stopping based on the consecutive number of mini
        batches that does not yield an improvement on the smoothed inertia.

        To disable convergence detection based on inertia, set
        max_no_improvement to None.

    init_size : int, optional, default: 3 * batch_size
        Number of samples to randomly sample for speeding up the
        initialization (sometimes at the expense of accuracy): the
        only algorithm is initialized by running a batch KMeans on a
        random subset of the data. This needs to be larger than n_clusters.

    n_init : int, default=3
        Number of random initializations that are tried.
        In contrast to KMeans, the algorithm is only run once, using the
        best of the ``n_init`` initializations as measured by inertia.

    reassignment_ratio : float, default: 0.01
        Control the fraction of the maximum number of counts for a
        center to be reassigned. A higher value means that low count
        centers are more easily reassigned, which means that the
        model will take longer to converge, but should converge in a
        better clustering.

    Attributes
    ----------

    cluster_centers_ : array, [n_clusters, n_features]
        Coordinates of cluster centers

    labels_ :
        Labels of each point (if compute_labels is set to True).

    inertia_ : float
        The value of the inertia criterion associated with the chosen
        partition (if compute_labels is set to True). The inertia is
        defined as the sum of square distances of samples to their nearest
        neighbor.

    Examples
    --------
    >>> from sklearn.cluster import MiniBatchKMeans
    >>> import numpy as np
    >>> X = np.array([[1, 2], [1, 4], [1, 0],
    ...               [4, 2], [4, 0], [4, 4],
    ...               [4, 5], [0, 1], [2, 2],
    ...               [3, 2], [5, 5], [1, -1]])
    >>> # manually fit on batches
    >>> kmeans = MiniBatchKMeans(n_clusters=2,
    ...         random_state=0,
    ...         batch_size=6)
    >>> kmeans = kmeans.partial_fit(X[0:6,:])
    >>> kmeans = kmeans.partial_fit(X[6:12,:])
    >>> kmeans.cluster_centers_
    array([[1, 1],
           [3, 4]])
    >>> kmeans.predict([[0, 0], [4, 4]])
    array([0, 1], dtype=int32)
    >>> # fit on the whole data
    >>> kmeans = MiniBatchKMeans(n_clusters=2,
    ...         random_state=0,
    ...         batch_size=6,
    ...         max_iter=10).fit(X)
    >>> kmeans.cluster_centers_
    array([[3.95918367, 2.40816327],
           [1.12195122, 1.3902439 ]])
    >>> kmeans.predict([[0, 0], [4, 4]])
    array([1, 0], dtype=int32)

    See also
    --------

    KMeans
        The classic implementation of the clustering method based on the
        Lloyd's algorithm. It consumes the whole set of input data at each
        iteration.

    Notes
    -----
    See http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf

    i   s	   k-means++id   i    g        i
   i   g{Gz?c         C   sn   t  t |   j d | d | d | d | d | d | d |  |	 |  _ | |  _ | |  _ |
 |  _ | |  _ d  S(   NR.   R^   R]   R_   R0   RJ   Ry   (   t   superR   R   R   R   t   compute_labelsR   R   (   R   R.   R^   R]   R   R_   R   R0   RJ   R   R   Ry   R   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyR     s    				c         C   so  t  |  j  } t | d d d d d t j t j g } | j \ } } | |  j k  rs t d | |  j f   n  t	 | |  } |  j
 } t |  j d  r t j |  j d | j |  _ | d k r t j d	 |  j
 t d
 d d } q n  t | d t } |  j d k r>t | |  j  }	 t j | d | j }
 n d }	 t j d d | j }
 t j |  j d | j } t t j t |  |  j   } t |  j |  } |  j } | d k rd |  j } n  | | k r| } n  | |  _ | j d | |  } | | } | | } | | } d } x%t  |  D]} |  j! r`d | d | |  j f GHn  t j |  j d | j } t" | |  j |  j d | d | d | } t# | | | | | | |
 t$ d d d |  j! \ } } t% | | | |  \ } } |  j! rd | d | | f GHn  | d k s1| | k  r5| |  _& | |  _' | } q5q5Wi  } x t  |  D] } | j d | |  j  } t# | | | | | | |  j& |  j' |
 |	 d k d | d | d d t |  j' j(    d k d | d |  j) d |  j! \ } } t* |  | | |	 | | | | d |  j! rcPqcqcW| d |  _+ |  j, rk|  j- | |  \ |  _. |  _/ n  |  S(   s  Compute the centroids on X by chunking it into mini-batches.

        Parameters
        ----------
        X : array-like or sparse matrix, shape=(n_samples, n_features)
            Training instances to cluster. It must be noted that the data
            will be converted to C ordering, which will cause a memory copy
            if the given data is not C-contiguous.

        y : Ignored
            not used, present here for API consistency by convention.

        sample_weight : array-like, shape (n_samples,), optional
            The weights for each observation in X. If None, all observations
            are assigned equal weight (default: None)

        RU   RV   RW   RT   R   s'   n_samples=%d should be >= n_clusters=%dRY   i   si   Explicit initial center position passed: performing only one init in MiniBatchKMeans instead of n_init=%dRZ   i   R   g        i    i   s   Init %d/%d with method: %sR0   R/   R   R   R_   s   Inertia for init %d/%d: %fR   i
   R   N(0   R   R0   R   R   Rf   Rg   R   R.   RD   RR   Ry   Rj   R^   R   R   Rl   Rm   Rn   R   R'   RJ   RL   R   R   R    t   ceilR   R]   R   R   t
   init_size_R"   R)   R_   R   R   R   R   R   t   counts_R   R   R   R   R   t   _labels_inertia_minibatchR   R   (   R   R-   R   RP   R0   R2   R3   Ry   R/   RJ   R   R   t	   n_batchesR   R   t   validation_indicest   X_validt   sample_weight_validt   x_squared_norms_validR   t   init_idxR   t   cluster_centersR   R   t   _R   t   convergence_contextR   t   minibatch_indices(    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyR     s    	"			


		
				 		!c   	      C   s   |  j  r d GHn  t | |  } t | d t } t | j d |  j  } g  | D]* } t | | | | | | |  j  ^ qR } t	 |   \ } } t
 j |  t
 j |  f S(   sZ  Compute labels and inertia using mini batches.

        This is slightly slower than doing everything at once but preventes
        memory errors / segfaults.

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

        sample_weight : array-like, shape (n_samples,)
            The weights for each observation in X.

        Returns
        -------
        labels : array, shape (n_samples,)
            Cluster labels for each point.

        inertia : float
            Sum of squared distances of points to nearest cluster.
        s,   Computing label assignment and total inertiaR   i    (   R_   RR   R   R'   R   R   R   R   R   Ru   R   t   hstackR(   (	   R   R-   RP   R/   t   slicest   sR   R   R   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyR   W  s    	4c   	      C   s   t  | d d d d } | j \ } } t |  j d  rZ t j |  j d | j |  _ n  | d k rj |  St | |  } t | d t	 } t
 |  d	 t |  j   |  _ t |  d
  s t |  d  r)t | |  j |  j d |  j d | d |  j |  _ t j |  j d | j |  _ t } d } nH |  j j d d |  j j    d k } t j | j d d | j } t | | | |  j |  j t j d d | j d d | d | d |  j d |  j d |  j |  j rt | | | |  j  \ |  _ |  _ n  |  S(   s?  Update k means estimate on a single mini-batch X.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Coordinates of the data points to cluster. It must be noted that
            X will be copied if it is not C-contiguous.

        y : Ignored
            not used, present here for API consistency by convention.

        sample_weight : array-like, shape (n_samples,), optional
            The weights for each observation in X. If None, all observations
            are assigned equal weight (default: None)

        RU   RV   RW   RT   RY   R   i    R   t   random_state_R   R   R0   R/   R   i
   i   R   R   R   R_   N(   R   R   Rj   R^   R   R   R   RR   R   R'   t   getattrR   R0   R   R   R.   R   R   R   R   R   R   R"   R   R   R   R_   R   R   R   R   (	   R   R-   R   RP   R2   R3   R/   R   R   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   partial_fitw  sD    !				 		
	$c         C   s0   t  |  d  |  j |  } |  j | |  d S(   s  Predict the closest cluster each sample in X belongs to.

        In the vector quantization literature, `cluster_centers_` is called
        the code book and each value returned by `predict` is the index of
        the closest code in the code book.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            New data to predict.

        sample_weight : array-like, shape (n_samples,), optional
            The weights for each observation in X. If None, all observations
            are assigned equal weight (default: None)

        Returns
        -------
        labels : array, shape [n_samples,]
            Index of the cluster each sample belongs to.
        R   i    (   R   R   R   (   R   R-   RP   (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyR     s    N(
   R   R   R   R'   R   R   R   R   R   R   (    (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyR   &  s   				 B(=   R   t
   __future__R    Rl   t   numpyR   t   scipy.sparset   sparseR#   t   baseR   R   R   t   metrics.pairwiseR   R   t   utils.extmathR   R   R   t   utils.sparsefuncs_fastR	   t   utils.sparsefuncsR
   t   utils.validationR   t   utilsR   R   R   R   R   t   utils._joblibR   R   R   t   externals.sixR   t
   exceptionsR   t    R   t   _k_means_elkanR   R   RB   RF   RL   RR   R   R'   R   Rp   Ro   R   R   R   R   R   R   R   (    (    (    s7   lib/python2.7/site-packages/sklearn/cluster/k_means_.pyt   <module>   sd   h							~	1;O U@