
    0Ph=P              
       
   d Z ddlZddlmZmZ ddl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mZ dd	lmZ dd
lmZmZmZ ddlmZmZ d Zd Z edgdgdd          dddddddddd            Z G d dee
          ZdS )z*Affinity Propagation clustering algorithm.    N)IntegralReal   )config_context)BaseEstimatorClusterMixin_fit_context)ConvergenceWarning)euclidean_distancespairwise_distances_argmin)check_random_state)Interval
StrOptionsvalidate_params)check_is_fittedvalidate_datac                 B     fd} fd} |            o	 |            S )Nc                  J    t          j          j        d         k              S )Nr   )npallflat)
preferences   e/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/cluster/_affinity_propagation.pyall_equal_preferenceszB_equal_similarities_and_preferences.<locals>.all_equal_preferences   s    vjJOA$66777    c                      t          j        j        t                    } t          j        | d           t          j        |          j        |          j        d         k              S )N)dtyper   )r   onesshapeboolfill_diagonalr   r   )maskSs    r   all_equal_similaritieszC_equal_similarities_and_preferences.<locals>.all_equal_similarities   sQ    wqwd+++
q!!!vaglagl1o5666r    )r#   r   r   r$   s   ``  r   #_equal_similarities_and_preferencesr&      sV    8 8 8 8 87 7 7 7 7 ! ""?'='='?'??r   c          	      n   | j         d         }|dk    st          | |          rt          j        d           |j        d         | j        |dz
           k    rS|r)t          j        |          t          j        |          dfn't          j        |          t          j        |          fS |r.t          j        dg          t          j        dg|z            dfn,t          j        dg          t          j        dg|z            fS || j        dd|dz   <   t          j        ||f          }	t          j        ||f          }
t          j        ||f          }| t          j	        | j
                  j        | z  t          j	        | j
                  j        dz  z   |                    ||f          z  z  } t          j        ||f          }t          j        |          }t          |          D ]}t          j        |	| |           t          j        |d          }|||f         }t
          j         |||f<   t          j        |d          }t          j        | |dddf         |           | ||f         |z
  |||f<   |d|z
  z  }|
|z  }
|
|z  }
t          j        |
d|           |
j        dd|dz            |j        dd|dz   <   |t          j        |d          z  }t          j        |                                          }|                    dt
          j        |           ||j        dd|dz   <   |d|z
  z  }|	|z  }	|	|z  }	t          j        |	          t          j        |
          z   dk    }||dd||z  f<   t          j        |d          }||k    r_t          j        |d          }t          j        ||k    |dk    z             |k    }|s|dk    s||k    rd}|rt3          d	|z              nd
}|rt3          d           t          j        |          }|j        }|dk    r;|rt          j        dt8                     t          j        | dd|f         d          }t          j        |          ||<   t          |          D ]o}t          j        ||k              d         }t          j        t          j        | |ddt
          j        f         |f         d                    }||         ||<   pt          j        | dd|f         d          }t          j        |          ||<   ||         }t          j        |          }t          j         ||          }n4t          j        dt8                     t          j        dg|z            }g }|r|||dz   fS ||fS )z$Main affinity propagation algorithm.r      zTAll samples have mutually equal similarities. Returning arbitrary cluster center(s).Nd   )size)axisFzConverged after %d iterations.TzDid not convergezcAffinity propagation did not converge, this model may return degenerate cluster centers and labels.zWAffinity propagation did not converge and this model will not have any cluster centers.)!r   r&   warningswarnr   r   arangearrayzerosfinfor   epstinystandard_normalrangeaddargmaxinfmaxsubtractmaximumsumdiagcopyclipprintflatnonzeror*   r
   wherenewaxisuniquesearchsorted)r#   r   convergence_itermax_iterdampingverbosereturn_n_iterrandom_state	n_samplesARtmpeinditIYY2dAEKseunconvergednever_convergedckiijlabelscluster_centers_indicess                                 r   _affinity_propagationrc   "   s    
IA~~<Q
KK~ 	5	
 	
 	
 ?1y1} 555 !B9%%ry';';Q??i	**BIi,@,@A !@1#!y 9 91==hsmmRXqcIo%>%>? ",AFy1}
)Y'((A
)Y'((A
(Iy)
*
*C 
!BHQW$5$5$:S$@@$$9i*@$AA
B BA
 	)-.//A
)I

CHoo 0& 0&
q!SIc"""QKvgCFVCa    	AqDz3'''Qi"nCF 	q7{	W	S 	
1a%&V,<,<y1},<%=!!IM!" 	rvc""""WS\\  BFC   %'!!IM!" 	q7{	W	S WQZZ"'!**$)&'!!!R""
"#F11!!!"""B&"(8"8R1W!EFF)SK QUUx"' A:R?@@@ 	&$%%%
qA	A1uu 	MH #   Ia1gA&&&y||!q 	 	A!q&!!!$B	"&2aaam#4b#8!9BBBCCAa5AaDDIa1gA&&&y||!1"$)F"3"3!8&AA5 	
 	
 	
 2$*++"$ /&Q66&..r   
array-likeboolean)r#   rK   Fprefer_skip_nested_validation            ?T)r   rG   rH   rI   r?   rJ   rK   rL   c          
          t          |||||d||                              |           }	|r|	j        |	j        |	j        fS |	j        |	j        fS )a  Perform Affinity Propagation Clustering of data.

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

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

    preference : array-like of shape (n_samples,) or float, default=None
        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, default=15
        Number of iterations with no change in the number
        of estimated clusters that stops the convergence.

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

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

    copy : bool, default=True
        If copy is False, the affinity matrix is modified inplace by the
        algorithm, for memory efficiency.

    verbose : bool, default=False
        The verbosity level.

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

    random_state : int, RandomState instance or None, default=None
        Pseudo-random number generator to control the starting state.
        Use an int for reproducible results across function calls.
        See the :term:`Glossary <random_state>`.

        .. versionadded:: 0.23
            this parameter was previously hardcoded as 0.

    Returns
    -------
    cluster_centers_indices : ndarray of shape (n_clusters,)
        Index of clusters centers.

    labels : ndarray of 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 usage,
    see :ref:`sphx_glr_auto_examples_cluster_plot_affinity_propagation.py`.
    You may also check out,
    :ref:`sphx_glr_auto_examples_applications_plot_stock_market.py`

    When the algorithm does not converge, it will still return a arrays of
    ``cluster_center_indices`` and labels if there are any exemplars/clusters,
    however they may be degenerate and should be used with caution.

    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

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.cluster import affinity_propagation
    >>> from sklearn.metrics.pairwise import euclidean_distances
    >>> X = np.array([[1, 2], [1, 4], [1, 0],
    ...               [4, 2], [4, 4], [4, 0]])
    >>> S = -euclidean_distances(X, squared=True)
    >>> cluster_centers_indices, labels = affinity_propagation(S, random_state=0)
    >>> cluster_centers_indices
    array([0, 3])
    >>> labels
    array([0, 0, 0, 1, 1, 1])
    precomputedrI   rH   rG   r?   r   affinityrJ   rL   )AffinityPropagationfitcluster_centers_indices_labels_n_iter_)
r#   r   rG   rH   rI   r?   rJ   rK   rL   	estimators
             r   affinity_propagationru      ss    d $)!	 	 	 
c!ff   X193DiFWWW-y/@@@r   c                   .    e Zd ZU dZ eeddd          g eeddd          g eeddd          gdgd	 eeddd
          dg eddh          gdgdgdZe	e
d<   ddddddddddZ fdZ ed          dd            Zd Zd fd	Z xZS )ro   am  Perform Affinity Propagation Clustering of data.

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

    Parameters
    ----------
    damping : float, default=0.5
        Damping factor in the range `[0.5, 1.0)` 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, default=200
        Maximum number of iterations.

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

    copy : bool, default=True
        Make a copy of input data.

    preference : array-like of shape (n_samples,) or float, default=None
        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 : {'euclidean', 'precomputed'}, default='euclidean'
        Which affinity to use. At the moment 'precomputed' and
        ``euclidean`` are supported. 'euclidean' uses the
        negative squared euclidean distance between points.

    verbose : bool, default=False
        Whether to be verbose.

    random_state : int, RandomState instance or None, default=None
        Pseudo-random number generator to control the starting state.
        Use an int for reproducible results across function calls.
        See the :term:`Glossary <random_state>`.

        .. versionadded:: 0.23
            this parameter was previously hardcoded as 0.

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

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

    labels_ : ndarray of shape (n_samples,)
        Labels of each point.

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

    n_iter_ : int
        Number of iterations taken to converge.

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    AgglomerativeClustering : Recursively merges the pair of
        clusters that minimally increases a given linkage distance.
    FeatureAgglomeration : Similar to AgglomerativeClustering,
        but recursively merges features instead of samples.
    KMeans : K-Means clustering.
    MiniBatchKMeans : Mini-Batch K-Means clustering.
    MeanShift : Mean shift clustering using a flat kernel.
    SpectralClustering : Apply clustering to a projection
        of the normalized Laplacian.

    Notes
    -----
    For an example usage,
    see :ref:`sphx_glr_auto_examples_cluster_plot_affinity_propagation.py`.

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

    When the algorithm does not converge, it will still return a arrays of
    ``cluster_center_indices`` and labels if there are any exemplars/clusters,
    however they may be degenerate and should be used with caution.

    When ``fit`` does not converge, ``cluster_centers_`` is still populated
    however it may be degenerate. In such a case, proceed with caution.
    If ``fit`` does not converge and fails to produce any ``cluster_centers_``
    then ``predict`` will 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

    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(random_state=5).fit(X)
    >>> clustering
    AffinityPropagation(random_state=5)
    >>> 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]])
    rj   g      ?left)closedr(   Nre   rd   neither	euclideanrl   rJ   rL   rm   _parameter_constraintsri   rh   TFc                v    || _         || _        || _        || _        || _        || _        || _        || _        d S N)rI   rH   rG   r?   rJ   r   rn   rL   )	selfrI   rH   rG   r?   r   rn   rJ   rL   s	            r   __init__zAffinityPropagation.__init__  sD       0	$ (r   c                     t                                                      }| j        dk    |j        _        | j        dk    |j        _        |S )Nrl   )super__sklearn_tags__rn   
input_tagspairwisesparse)r~   tags	__class__s     r   r   z$AffinityPropagation.__sklearn_tags__  s?    ww''))#'=M#A !%-!?r   rf   c           
         | j         dk    r t          | || j        d          }|| _        n)t          | |d          }t	          |d           | _        | j        j        d         | j        j        d         k    rt          d	| j        j         d
          | j        t          j	        | j                  }n| j        }t          j
        |          }t          | j                  }t          | j        | j        | j        || j        | j        d|          \  | _        | _        | _        | j         dk    r$|| j                                                 | _        | S )a  Fit the clustering from features, or affinity matrix.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features), or                 array-like of shape (n_samples, n_samples)
            Training instances to cluster, or similarities / affinities between
            instances if ``affinity='precomputed'``. If a sparse feature matrix
            is provided, it will be converted into a sparse ``csr_matrix``.

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

        Returns
        -------
        self
            Returns the instance itself.
        rl   T)r?   force_writeablecsr)accept_sparse)squaredr   r(   z7The matrix of similarities must be a square array. Got z	 instead.N)rH   rG   r   rI   rJ   rK   rL   )rn   r   r?   affinity_matrix_r   r   
ValueErrorr   r   medianasarrayr   rL   rc   rH   rG   rI   rJ   rq   rr   rs   cluster_centers_)r~   Xyr   rL   s        r   rp   zAffinityPropagation.fit  sq   ( =M))dADItLLLA$%D!!dAU;;;A%8D%I%I%I$ID! &q)T-B-H-KKK>,2> > >  
 ?"4#899JJJZ
++
)$*;<< "!]!2!LL%	
 	
 	
		
)LL =M))$%d&C$D$I$I$K$KD!r   c                    t          |            t          | |dd          }t          | d          st          d          | j        j        d         dk    r?t          d          5  t          || j                  cd	d	d	           S # 1 swxY w Y   d	S t          j	        d
t                     t          j        dg|j        d         z            S )a  Predict the closest cluster each sample in X belongs to.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            New data to predict. If a sparse matrix is provided, it will be
            converted into a sparse ``csr_matrix``.

        Returns
        -------
        labels : ndarray of shape (n_samples,)
            Cluster labels.
        Fr   )resetr   r   z<Predict method is not supported when affinity='precomputed'.r   T)assume_finiteNzzThis model does not have any cluster centers because affinity propagation did not converge. Labeling every sample as '-1'.r,   )r   r   hasattrr   r   r   r   r   r-   r.   r
   r   r0   )r~   r   s     r   predictzAffinityPropagation.predict&  s@    	$eDDDt/00 	N    &q)A--d333 K K0D4IJJK K K K K K K K K K K K K K K K K K M5 #   8RD171:-...s   (B

BBc                 H    t                                          ||          S )a  Fit clustering from features/affinity matrix; return cluster labels.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features), or                 array-like of shape (n_samples, n_samples)
            Training instances to cluster, or similarities / affinities between
            instances if ``affinity='precomputed'``. If a sparse feature matrix
            is provided, it will be converted into a sparse ``csr_matrix``.

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

        Returns
        -------
        labels : ndarray of shape (n_samples,)
            Cluster labels.
        )r   fit_predict)r~   r   r   r   s      r   r   zAffinityPropagation.fit_predictI  s    & ww""1a(((r   r}   )__name__
__module____qualname____doc__r   r   r   r   r{   dict__annotations__r   r   r	   rp   r   r   __classcell__)r   s   @r   ro   ro   8  s        D DN HT3F;;;<Xh4???@%Xh4GGGHHT4i888

  Zm <==>;'($ $D   $ ) ) ) ) )*     \555: : : 65:x!/ !/ !/F) ) ) ) ) ) ) ) ) )r   ro   )r   r-   numbersr   r   numpyr   _configr   baser   r   r	   
exceptionsr
   metricsr   r   utilsr   utils._param_validationr   r   r   utils.validationr   r   r&   rc   ru   ro   r%   r   r   <module>r      s   0 0
  " " " " " " " "     $ $ $ $ $ $ < < < < < < < < < < + + + + + + D D D D D D D D & & & & & & K K K K K K K K K K = = = = = = = =@ @ @M/ M/ M/h ^#  #(   	xA xA xA xA xAvd) d) d) d) d), d) d) d) d) d)r   