ó
‡ˆ\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	 d d	 l
 m Z d d
 l
 m Z d d l m Z d „  Z d d d d „ Z d „  Z d d „ Z d „  Z d „  Z d S(   s    Unsupervised evaluation metrics.iÿÿÿÿ(   t   divisionNi   (   t   check_random_state(   t	   check_X_y(   t   safe_indexingi   (   t   pairwise_distances_chunked(   t   pairwise_distances(   t   LabelEncoderc         C   s3   d |  k  o | k  n s/ t  d |  ƒ ‚ n  d S(   s¥   Check that number of labels are valid.

    Parameters
    ----------
    n_labels : int
        Number of labels

    n_samples : int
        Number of samples
    i   sG   Number of labels is %d. Valid values are 2 to n_samples - 1 (inclusive)N(   t
   ValueError(   t   n_labelst	   n_samples(    (    sC   lib/python2.7/site-packages/sklearn/metrics/cluster/unsupervised.pyt   check_number_of_labels   s    t	   euclideanc         K   s¸   | d k	 r™ t |  | d d d g ƒ\ }  } t | ƒ } | j |  j d ƒ |  } | d k r |  | j | j | | }  } q™ |  | | | }  } n  t j t |  | d | | ƒ S(   s  Compute the mean Silhouette Coefficient of all samples.

    The Silhouette Coefficient is calculated using the mean intra-cluster
    distance (``a``) and the mean nearest-cluster distance (``b``) for each
    sample.  The Silhouette Coefficient for a sample is ``(b - a) / max(a,
    b)``.  To clarify, ``b`` is the distance between a sample and the nearest
    cluster that the sample is not a part of.
    Note that Silhouette Coefficient is only defined if number of labels
    is 2 <= n_labels <= n_samples - 1.

    This function returns the mean Silhouette Coefficient over all samples.
    To obtain the values for each sample, use :func:`silhouette_samples`.

    The best value is 1 and the worst value is -1. Values near 0 indicate
    overlapping clusters. Negative values generally indicate that a sample has
    been assigned to the wrong cluster, as a different cluster is more similar.

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

    Parameters
    ----------
    X : array [n_samples_a, n_samples_a] if metric == "precomputed", or,              [n_samples_a, n_features] otherwise
        Array of pairwise distances between samples, or a feature array.

    labels : array, shape = [n_samples]
         Predicted labels for each sample.

    metric : string, or callable
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string, it must be one of the options
        allowed by :func:`metrics.pairwise.pairwise_distances
        <sklearn.metrics.pairwise.pairwise_distances>`. If X is the distance
        array itself, use ``metric="precomputed"``.

    sample_size : int or None
        The size of the sample to use when computing the Silhouette Coefficient
        on a random subset of the data.
        If ``sample_size is None``, no sampling is used.

    random_state : int, RandomState instance or None, optional (default=None)
        The generator used to randomly select a subset of samples.  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 ``sample_size is not None``.

    **kwds : optional keyword parameters
        Any further parameters are passed directly to the distance function.
        If using a scipy.spatial.distance metric, the parameters are still
        metric dependent. See the scipy docs for usage examples.

    Returns
    -------
    silhouette : float
        Mean Silhouette Coefficient for all samples.

    References
    ----------

    .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the
       Interpretation and Validation of Cluster Analysis". Computational
       and Applied Mathematics 20: 53-65.
       <https://www.sciencedirect.com/science/article/pii/0377042787901257>`_

    .. [2] `Wikipedia entry on the Silhouette Coefficient
           <https://en.wikipedia.org/wiki/Silhouette_(clustering)>`_

    t   accept_sparset   csct   csri    t   precomputedt   metricN(	   t   NoneR   R   t   permutationt   shapet   Tt   npt   meant   silhouette_samples(   t   Xt   labelsR   t   sample_sizet   random_statet   kwdst   indices(    (    sC   lib/python2.7/site-packages/sklearn/metrics/cluster/unsupervised.pyt   silhouette_score&   s    G!"c   	      C   sß   t  j t |  ƒ t | ƒ f d |  j ƒ} xI t t |  ƒ ƒ D]5 } | | c t  j | d |  | d t | ƒ ƒ7<q= Wt  j t |  ƒ ƒ | | | t |  ƒ !f } | | } t  j | | <| | } | j d d ƒ } | | f S(   s   Accumulate silhouette statistics for vertical chunk of X

    Parameters
    ----------
    D_chunk : shape (n_chunk_samples, n_samples)
        precomputed distances for a chunk
    start : int
        first index in chunk
    labels : array, shape (n_samples,)
        corresponding cluster labels, encoded as {0, ..., n_clusters-1}
    label_freqs : array
        distribution of cluster labels in ``labels``
    t   dtypet   weightst	   minlengtht   axisi   (	   R   t   zerost   lenR   t   ranget   bincountt   aranget   inft   min(	   t   D_chunkt   startR   t   label_freqst   clust_distst   it   intra_indext   intra_clust_distst   inter_clust_dists(    (    sC   lib/python2.7/site-packages/sklearn/metrics/cluster/unsupervised.pyt   _silhouette_reducex   s     ,

c      	   K   sb  t  |  | d d d g ƒ\ }  } t ƒ  } | j | ƒ } t | ƒ } t j | ƒ } t t | j ƒ | ƒ | | d <t j	 t
 d | d | ƒ} t t |  d | | Œ  } | \ }	 }
 t j |	 ƒ }	 t j |
 ƒ }
 | d j | d	 d
 ƒ} t j d d d d ƒ  |	 | }	 Wd QX|
 |	 } t j d d d d ƒ  | t j |	 |
 ƒ } Wd QXt j | ƒ S(   s	  Compute the Silhouette Coefficient for each sample.

    The Silhouette Coefficient is a measure of how well samples are clustered
    with samples that are similar to themselves. Clustering models with a high
    Silhouette Coefficient are said to be dense, where samples in the same
    cluster are similar to each other, and well separated, where samples in
    different clusters are not very similar to each other.

    The Silhouette Coefficient is calculated using the mean intra-cluster
    distance (``a``) and the mean nearest-cluster distance (``b``) for each
    sample.  The Silhouette Coefficient for a sample is ``(b - a) / max(a,
    b)``.
    Note that Silhouette Coefficient is only defined if number of labels
    is 2 <= n_labels <= n_samples - 1.

    This function returns the Silhouette Coefficient for each sample.

    The best value is 1 and the worst value is -1. Values near 0 indicate
    overlapping clusters.

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

    Parameters
    ----------
    X : array [n_samples_a, n_samples_a] if metric == "precomputed", or,              [n_samples_a, n_features] otherwise
        Array of pairwise distances between samples, or a feature array.

    labels : array, shape = [n_samples]
             label values for each sample

    metric : string, or callable
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string, it must be one of the options
        allowed by :func:`sklearn.metrics.pairwise.pairwise_distances`. If X is
        the distance array itself, use "precomputed" as the metric.

    `**kwds` : optional keyword parameters
        Any further parameters are passed directly to the distance function.
        If using a ``scipy.spatial.distance`` metric, the parameters are still
        metric dependent. See the scipy docs for usage examples.

    Returns
    -------
    silhouette : array, shape = [n_samples]
        Silhouette Coefficient for each samples.

    References
    ----------

    .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the
       Interpretation and Validation of Cluster Analysis". Computational
       and Applied Mathematics 20: 53-65.
       <https://www.sciencedirect.com/science/article/pii/0377042787901257>`_

    .. [2] `Wikipedia entry on the Silhouette Coefficient
       <https://en.wikipedia.org/wiki/Silhouette_(clustering)>`_

    R   R   R   R   R   R,   t   reduce_funci   t   modet   clipt   dividet   ignoret   invalidN(   R   R   t   fit_transformR$   R   R&   R
   t   classes_t	   functoolst   partialR2   t   zipR   t   concatenatet   taket   errstatet   maximumt
   nan_to_num(   R   R   R   R   t   leR	   R,   R3   t   resultsR0   R1   t   denomt   sil_samples(    (    sC   lib/python2.7/site-packages/sklearn/metrics/cluster/unsupervised.pyR   ˜   s*    <!	

c         C   s  t  |  | ƒ \ }  } t ƒ  } | j | ƒ } |  j \ } } t | j ƒ } t | | ƒ d \ } } t j |  d d ƒ} xy t	 | ƒ D]k }	 |  | |	 k }
 t j |
 d d ƒ} | t |
 ƒ t j
 | | d ƒ 7} | t j
 |
 | d ƒ 7} q† W| d k rd S| | | | | d S(   su  Compute the Calinski and Harabaz score.

    It is also known as the Variance Ratio Criterion.

    The score is defined as ratio between the within-cluster dispersion and
    the between-cluster dispersion.

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

    Parameters
    ----------
    X : array-like, shape (``n_samples``, ``n_features``)
        List of ``n_features``-dimensional data points. Each row corresponds
        to a single data point.

    labels : array-like, shape (``n_samples``,)
        Predicted labels for each sample.

    Returns
    -------
    score : float
        The resulting Calinski-Harabaz score.

    References
    ----------
    .. [1] `T. Calinski and J. Harabasz, 1974. "A dendrite method for cluster
       analysis". Communications in Statistics
       <https://www.tandfonline.com/doi/abs/10.1080/03610927408827101>`_
    g        R"   i    i   g      ð?(   g        g        (   R   R   R9   R   R$   R:   R
   R   R   R%   t   sum(   R   R   RC   R	   t   _R   t
   extra_dispt
   intra_dispR   t   kt	   cluster_kt   mean_k(    (    sC   lib/python2.7/site-packages/sklearn/metrics/cluster/unsupervised.pyt   calinski_harabaz_scoreï   s     	%c         C   sz  t  |  | ƒ \ }  } t ƒ  } | j | ƒ } |  j \ } } t | j ƒ } t | | ƒ t j | ƒ } t j | t |  d ƒ f d t j	 ƒ} xd t
 | ƒ D]V } t |  | | k ƒ }	 |	 j d d ƒ }
 |
 | | <t j t |	 |
 g ƒ ƒ | | <qœ Wt | ƒ } t j | d ƒ s&t j | d ƒ r*d S| d d … d f | | } t j | | t j k <t j t j | d d ƒƒ S(   s]  Computes the Davies-Bouldin score.

    The score is defined as the ratio of within-cluster distances to
    between-cluster distances.

    Read more in the :ref:`User Guide <davies-bouldin_index>`.

    Parameters
    ----------
    X : array-like, shape (``n_samples``, ``n_features``)
        List of ``n_features``-dimensional data points. Each row corresponds
        to a single data point.

    labels : array-like, shape (``n_samples``,)
        Predicted labels for each sample.

    Returns
    -------
    score: float
        The resulting Davies-Bouldin score.

    References
    ----------
    .. [1] Davies, David L.; Bouldin, Donald W. (1979).
       `"A Cluster Separation Measure"
       <https://ieeexplore.ieee.org/document/4766909>`__.
       IEEE Transactions on Pattern Analysis and Machine Intelligence.
       PAMI-1 (2): 224-227
    i    R   R"   g        Ni   (   R   R   R9   R   R$   R:   R
   R   R#   t   floatR%   R   R   t   averageR   t   allcloseR   t   nanR(   t   nanmax(   R   R   RC   R	   RH   R   t   intra_distst	   centroidsRK   RL   t   centroidt   centroid_distancest   score(    (    sC   lib/python2.7/site-packages/sklearn/metrics/cluster/unsupervised.pyt   davies_bouldin_score#  s(    	(
	$(   t   __doc__t
   __future__R    R;   t   numpyR   t   utilsR   R   R   t   pairwiseR   R   t   preprocessingR   R
   R   R   R2   R   RN   RY   (    (    (    sC   lib/python2.7/site-packages/sklearn/metrics/cluster/unsupervised.pyt   <module>   s    	Q	 W	4