ó
‡ˆ\c           @   sÎ   d  Z  d d l 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 d d l m Z d d	 l m Z d
 „  Z d d d d e e e d „ Z d e e f d „  ƒ  YZ d S(   s*   Affinity Propagation clustering algorithm.iÿÿÿÿN(   t   ConvergenceWarningi   (   t   BaseEstimatort   ClusterMixin(   t   as_float_arrayt   check_array(   t   check_is_fitted(   t   euclidean_distances(   t   pairwise_distances_argminc            s.   ‡ f d †  } ‡  f d †  } | ƒ  o- | ƒ  S(   Nc              s   t  j ˆ  ˆ  j d k ƒ S(   Ni    (   t   npt   allt   flat(    (   t
   preference(    sD   lib/python2.7/site-packages/sklearn/cluster/affinity_propagation_.pyt   all_equal_preferences   s    c             sM   t  j ˆ  j d t ƒ}  t  j |  d ƒ t  j ˆ  |  j ˆ  |  j d k ƒ S(   Nt   dtypei    (   R   t   onest   shapet   boolt   fill_diagonalR	   R
   (   t   mask(   t   S(    sD   lib/python2.7/site-packages/sklearn/cluster/affinity_propagation_.pyt   all_equal_similarities   s    (    (   R   R   R   R   (    (   R   R   sD   lib/python2.7/site-packages/sklearn/cluster/affinity_propagation_.pyt#   _equal_similarities_and_preferences   s    i   iÈ   g      à?c         C   s`  t  |  d | ƒ}  |  j d } |  j d |  j d k rU t d t |  j ƒ ƒ ‚ n  | d k rs t j |  ƒ } n  | d k  s‹ | d k rš t d ƒ ‚ n  t j | ƒ } | d k sÄ t |  | ƒ rˆt	 j
 d ƒ | j d |  j | d k r0| rt j | ƒ t j | ƒ d f St j | ƒ t j | ƒ f S| r_t j d g ƒ t j d g | ƒ d f St j d g ƒ t j d g | ƒ f Sn  t j j d ƒ }	 | |  j d d | d … <t j | | f ƒ }
 t j | | f ƒ } t j | | f ƒ } |  t j t j ƒ j |  t j t j ƒ j d	 |	 j | | ƒ 7}  t j | | f ƒ } t j | ƒ } xvt | ƒ D]Z} t j |
 |  | ƒ t j | d
 d ƒ} | | | f } t j | | | f <t j | d
 d ƒ} t j |  | d d … d f | ƒ |  | | f | | | | f <| d | 9} | | 9} | | 7} t j | d | ƒ | j d d | d … | j d d | d … <| t j | d
 d ƒ8} t j | ƒ j ƒ  } | j d t j | ƒ | | j d d | d … <| d | 9} |
 | 9}
 |
 | 8}
 t j |
 ƒ t j | ƒ d k } | | d d … | | f <t j | d
 d ƒ} | | k rht j | d
 d ƒ} t j | | k | d k ƒ | k } | r| d k s©| | k rÂ| r»d | GHn  PqÂqhqhW| rÔd GHn  t j  | ƒ } | j! } | d k rt j |  d d … | f d
 d ƒ} t j | ƒ | | <xv t | ƒ D]h } t j" | | k ƒ d } t j t j |  | d d … t j# f | f d
 d ƒƒ } | | | | <q=Wt j |  d d … | f d
 d ƒ} t j | ƒ | | <| | } t j$ | ƒ } t j% | | ƒ } n, t	 j
 d t& ƒ t j d g | ƒ } g  } | rR| | | d f S| | f Sd S(   sP
  Perform Affinity Propagation Clustering of data

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

    Parameters
    ----------

    S : array-like, shape (n_samples, n_samples)
        Matrix of similarities between points

    preference : array-like, shape (n_samples,) or float, optional
        Preferences for each point - points with larger values of
        preferences are more likely to be chosen as exemplars. The number of
        exemplars, i.e. of clusters, is influenced by the input preferences
        value. If the preferences are not passed as arguments, they will be
        set to the median of the input similarities (resulting in a moderate
        number of clusters). For a smaller amount of clusters, this can be set
        to the minimum value of the similarities.

    convergence_iter : int, optional, default: 15
        Number of iterations with no change in the number
        of estimated clusters that stops the convergence.

    max_iter : int, optional, default: 200
        Maximum number of iterations

    damping : float, optional, default: 0.5
        Damping factor between 0.5 and 1.

    copy : boolean, optional, default: True
        If copy is False, the affinity matrix is modified inplace by the
        algorithm, for memory efficiency

    verbose : boolean, optional, default: False
        The verbosity level

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

    Returns
    -------

    cluster_centers_indices : array, shape (n_clusters,)
        index of clusters centers

    labels : array, shape (n_samples,)
        cluster labels for each point

    n_iter : int
        number of iterations run. Returned only if `return_n_iter` is
        set to True.

    Notes
    -----
    For an example, see :ref:`examples/cluster/plot_affinity_propagation.py
    <sphx_glr_auto_examples_cluster_plot_affinity_propagation.py>`.

    When the algorithm does not converge, it returns an empty array as
    ``cluster_center_indices`` and ``-1`` as label for each training sample.

    When all training samples have equal similarities and equal preferences,
    the assignment of cluster centers and labels depends on the preference.
    If the preference is smaller than the similarities, a single cluster center
    and label ``0`` for every sample will be returned. Otherwise, every
    training sample becomes its own cluster center and is assigned a unique
    label.

    References
    ----------
    Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages
    Between Data Points", Science Feb. 2007
    t   copyi    i   s#   S must be a square array (shape=%s)g      à?s   damping must be >= 0.5 and < 1sT   All samples have mutually equal similarities. Returning arbitrary cluster center(s).Nid   t   axiss   Converged after %d iterations.s   Did not convergesT   Affinity propagation did not converge, this model will not have any cluster centers.iÿÿÿÿ('   R   R   t
   ValueErrort   reprt   NoneR   t   mediant   arrayR   t   warningst   warnR
   t   aranget   randomt   RandomStatet   zerost   finfot   doublet   epst   tinyt   randnt   ranget   addt   argmaxt   inft   maxt   subtractt   maximumt   sumt   diagR   t   clipt   flatnonzerot   sizet   wheret   newaxist   uniquet   searchsortedR    (   R   R   t   convergence_itert   max_itert   dampingR   t   verboset   return_n_itert	   n_samplest   random_statet   At   Rt   tmpt   et   indt   itt   It   Yt   Y2t   dAt   Et   Kt   set   unconvergedt   ct   kt   iit   jt   labelst   cluster_centers_indices(    (    sD   lib/python2.7/site-packages/sklearn/cluster/affinity_propagation_.pyt   affinity_propagation!   s     K%/)0#

.

"		%;%
	t   AffinityPropagationc           B   sP   e  Z d  Z d d d e d	 d e d „ Z e d „  ƒ Z d	 d „ Z	 d „  Z
 RS(
   sd  Perform Affinity Propagation Clustering of data.

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

    Parameters
    ----------
    damping : float, optional, default: 0.5
        Damping factor (between 0.5 and 1) is the extent to
        which the current value is maintained relative to
        incoming values (weighted 1 - damping). This in order
        to avoid numerical oscillations when updating these
        values (messages).

    max_iter : int, optional, default: 200
        Maximum number of iterations.

    convergence_iter : int, optional, default: 15
        Number of iterations with no change in the number
        of estimated clusters that stops the convergence.

    copy : boolean, optional, default: True
        Make a copy of input data.

    preference : array-like, shape (n_samples,) or float, optional
        Preferences for each point - points with larger values of
        preferences are more likely to be chosen as exemplars. The number
        of exemplars, ie of clusters, is influenced by the input
        preferences value. If the preferences are not passed as arguments,
        they will be set to the median of the input similarities.

    affinity : string, optional, default=``euclidean``
        Which affinity to use. At the moment ``precomputed`` and
        ``euclidean`` are supported. ``euclidean`` uses the
        negative squared euclidean distance between points.

    verbose : boolean, optional, default: False
        Whether to be verbose.


    Attributes
    ----------
    cluster_centers_indices_ : array, shape (n_clusters,)
        Indices of cluster centers

    cluster_centers_ : array, shape (n_clusters, n_features)
        Cluster centers (if affinity != ``precomputed``).

    labels_ : array, shape (n_samples,)
        Labels of each point

    affinity_matrix_ : array, shape (n_samples, n_samples)
        Stores the affinity matrix used in ``fit``.

    n_iter_ : int
        Number of iterations taken to converge.

    Examples
    --------
    >>> from sklearn.cluster import AffinityPropagation
    >>> import numpy as np
    >>> X = np.array([[1, 2], [1, 4], [1, 0],
    ...               [4, 2], [4, 4], [4, 0]])
    >>> clustering = AffinityPropagation().fit(X)
    >>> clustering # doctest: +NORMALIZE_WHITESPACE
    AffinityPropagation(affinity='euclidean', convergence_iter=15, copy=True,
              damping=0.5, max_iter=200, preference=None, verbose=False)
    >>> clustering.labels_
    array([0, 0, 0, 1, 1, 1])
    >>> clustering.predict([[0, 0], [4, 4]])
    array([0, 1])
    >>> clustering.cluster_centers_
    array([[1, 2],
           [4, 2]])

    Notes
    -----
    For an example, see :ref:`examples/cluster/plot_affinity_propagation.py
    <sphx_glr_auto_examples_cluster_plot_affinity_propagation.py>`.

    The algorithmic complexity of affinity propagation is quadratic
    in the number of points.

    When ``fit`` does not converge, ``cluster_centers_`` becomes an empty
    array and all training samples will be labelled as ``-1``. In addition,
    ``predict`` will then label every sample as ``-1``.

    When all training samples have equal similarities and equal preferences,
    the assignment of cluster centers and labels depends on the preference.
    If the preference is smaller than the similarities, ``fit`` will result in
    a single cluster center and label ``0`` for every sample. Otherwise, every
    training sample becomes its own cluster center and is assigned a unique
    label.

    References
    ----------

    Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages
    Between Data Points", Science Feb. 2007
    g      à?iÈ   i   t	   euclideanc         C   sC   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ d  S(   N(   R:   R9   R8   R   R;   R   t   affinity(   t   selfR:   R9   R8   R   R   RV   R;   (    (    sD   lib/python2.7/site-packages/sklearn/cluster/affinity_propagation_.pyt   __init__Q  s    						c         C   s   |  j  d k S(   Nt   precomputed(   RV   (   RW   (    (    sD   lib/python2.7/site-packages/sklearn/cluster/affinity_propagation_.pyt	   _pairwise]  s    c         C   sô   t  | d d ƒ} |  j d k r- | |  _ nA |  j d k rU t | d t ƒ|  _ n t d t |  j ƒ ƒ ‚ t |  j |  j d |  j	 d |  j
 d	 |  j d
 |  j d |  j d t ƒ\ |  _ |  _ |  _ |  j d k rð | |  j j ƒ  |  _ n  |  S(   sr   Create affinity matrix from negative euclidean distances, then
        apply affinity propagation clustering.

        Parameters
        ----------

        X : array-like, shape (n_samples, n_features) or (n_samples, n_samples)
            Data matrix or, if affinity is ``precomputed``, matrix of
            similarities / affinities.

        y : Ignored

        t   accept_sparset   csrRY   RU   t   squareds=   Affinity must be 'precomputed' or 'euclidean'. Got %s insteadR9   R8   R:   R   R;   R<   (   R   RV   t   affinity_matrix_R   t   TrueR   t   strRS   R   R9   R8   R:   R   R;   t   cluster_centers_indices_t   labels_t   n_iter_t   cluster_centers_(   RW   t   Xt   y(    (    sD   lib/python2.7/site-packages/sklearn/cluster/affinity_propagation_.pyt   fita  s    -c         C   s|   t  |  d ƒ t |  d ƒ s+ t d ƒ ‚ n  |  j j d k rM t | |  j ƒ St j d t ƒ t	 j
 d g | j d ƒ Sd S(   sU  Predict the closest cluster each sample in X belongs to.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            New data to predict.

        Returns
        -------
        labels : array, shape (n_samples,)
            Index of the cluster each sample belongs to.
        Ra   Rd   s<   Predict method is not supported when affinity='precomputed'.i    sz   This model does not have any cluster centers because affinity propagation did not converge. Labeling every sample as '-1'.iÿÿÿÿN(   R   t   hasattrR   Rd   R3   R   R   R   R    R   R   R   (   RW   Re   (    (    sD   lib/python2.7/site-packages/sklearn/cluster/affinity_propagation_.pyt   predict„  s    	N(   t   __name__t
   __module__t   __doc__R_   R   t   FalseRX   t   propertyRZ   Rg   Ri   (    (    (    sD   lib/python2.7/site-packages/sklearn/cluster/affinity_propagation_.pyRT   ì   s   c		
#(   Rl   t   numpyR   R   t   sklearn.exceptionsR    t   baseR   R   t   utilsR   R   t   utils.validationR   t   metricsR   R   R   R   R_   Rm   RS   RT   (    (    (    sD   lib/python2.7/site-packages/sklearn/cluster/affinity_propagation_.pyt   <module>   s   			É