
    -i                     L   S r SSKrSSKJr  SSKJr  SSKrSSKJ	r
  SSKJrJr  SSKJrJrJrJr  SS	KJr  SS
KJrJr  SSKJr  S rS r\" SS/SS/\" \SSSS9S/S/SS.SS9SS\R8                  S.S j5       r\" S/S/S.SS9S 5       r\" S/S/S.SS9S 5       r\" S/S/S.SS9S 5       r \" S/S/\" \SSSS9/S.SS9SS .S! j5       r!\" S/S/S.SS9S" 5       r"\" S/S/S.SS9S# 5       r#\" S/S/\" \SSSS9/S.SS9SS .S$ j5       r$\" SS/SS// S%QS&.SS9SS'.S( j5       r%\" S/S/\" 1 S)k5      /S*.SS9S+S,.S- j5       r&\" S/S/\" 1 S)k5      /S*.SS9S+S,.S. j5       r'\" S/S/S\" \" S/15      5      /S0.SS9S/S.S1 j5       r(\" S2S/0SS9S3 5       r)g)4zUtilities to evaluate the clustering performance of models.

Functions named as *_score return a scalar value to maximize: the higher the
better.
    N)log)Realsparse   )_max_precision_float_dtypeget_namespace_and_device)HiddenInterval
StrOptionsvalidate_params)type_of_target)check_arraycheck_consistent_length   )expected_mutual_informationc                 t   [        U SSSS9n [        USSSS9n[        U 5      n[        U5      nSX24;   a$  SU SU S3n[        R                  " U[        5        U R
                  S	:w  a  [        S
U R                  < 35      eUR
                  S	:w  a  [        SUR                  < 35      e[        X5        X4$ )zCheck that the labels arrays are 1D and of same dimension.

Parameters
----------
labels_true : array-like of shape (n_samples,)
    The true labels.

labels_pred : array-like of shape (n_samples,)
    The predicted labels.
Fr   N)	ensure_2densure_min_samplesdtype
continuousz8Clustering metrics expects discrete values but received z values for label, and z values for targetr   z!labels_true must be 1D: shape is z!labels_pred must be 1D: shape is )	r   r   warningswarnUserWarningndim
ValueErrorshaper   )labels_truelabels_pred
type_label	type_predmsgs        V/var/www/html/venv/lib/python3.13/site-packages/sklearn/metrics/cluster/_supervised.pycheck_clusteringsr$      s     	K 	K  ,J{+I	..|29+ > 	
 	c;' 1+BSBSUVV1+BSBSUVVK5##    c                     US:X  a  [        X5      $ US:X  a  [        R                  " X-  5      $ US:X  a  [        R                  " X/5      $ US:X  a  [	        X5      $ [        S5      e)z(Return a particular mean of two numbers.min	geometric
arithmeticmaxzC'average_method' must be 'min', 'geometric', 'arithmetic', or 'max')r'   npsqrtmeanr*   r   )UVaverage_methods      r#   _generalized_averager1   F   sf    1y	;	&wwqu~	<	'wwv	5	 1yQ
 	
r%   
array-likeleft)closedbooleanno_validation)r   r   epsr   r   T)prefer_skip_nested_validationF)r7   r   r   c                   Ub  U(       a  [        S5      e[        R                  " U SS9u  pV[        R                  " USS9u  pxUR                  S   n	UR                  S   n
[        R
                  " [        R                  " UR                  S   5      Xh44X4US9nU(       a"  UR                  5       nUR                  5         U$ UR                  5       nUb  X-   nU$ )a  Build a contingency matrix describing the relationship between labels.

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

Parameters
----------
labels_true : array-like of shape (n_samples,)
    Ground truth class labels to be used as a reference.

labels_pred : array-like of shape (n_samples,)
    Cluster labels to evaluate.

eps : float, default=None
    If a float, that value is added to all values in the contingency
    matrix. This helps to stop NaN propagation.
    If ``None``, nothing is adjusted.

sparse : bool, default=False
    If `True`, return a sparse CSR contingency matrix. If `eps` is not
    `None` and `sparse` is `True` will raise ValueError.

    .. versionadded:: 0.18

dtype : numeric type, default=np.int64
    Output dtype. Ignored if `eps` is not `None`.

    .. versionadded:: 0.24

Returns
-------
contingency : {array-like, sparse}, shape=[n_classes_true, n_classes_pred]
    Matrix :math:`C` such that :math:`C_{i, j}` is the number of samples in
    true class :math:`i` and in predicted class :math:`j`. If
    ``eps is None``, the dtype of this array will be integer unless set
    otherwise with the ``dtype`` argument. If ``eps`` is given, the dtype
    will be float.
    Will be a ``sklearn.sparse.csr_matrix`` if ``sparse=True``.

Examples
--------
>>> from sklearn.metrics.cluster import contingency_matrix
>>> labels_true = [0, 0, 1, 1, 2, 2]
>>> labels_pred = [1, 0, 2, 1, 0, 2]
>>> contingency_matrix(labels_true, labels_pred)
array([[1, 1, 0],
       [0, 1, 1],
       [1, 0, 1]])
z!Cannot set 'eps' when sparse=TrueT)return_inverser   )r   r   )
r   r+   uniquer   sp
coo_matrixonestocsrsum_duplicatestoarray)r   r   r7   r   r   classes	class_idxclusterscluster_idx	n_classes
n_clusterscontingencys               r#   contingency_matrixrI   V   s    | 6<==;tDGIIk$GHa I"J --	#	$y&>?%K
 !'')""$ 	 "))+?%+Kr%   r   r   c                    [        X5      u  p[        R                  " U R                  S   5      n[	        XS[        R                  S9n[        R
                  " UR                  SS95      n[        R
                  " UR                  SS95      nUR                  S-  R                  5       n[        R                  " S[        R                  S9nXb-
  US	'   UR                  U5      R                  5       U-
  US
'   UR                  5       R                  U5      R                  5       U-
  US'   US-  US
   -
  US   -
  U-
  US'   U$ )up  Pair confusion matrix arising from two clusterings.

The pair confusion matrix :math:`C` computes a 2 by 2 similarity matrix
between two clusterings by considering all pairs of samples and counting
pairs that are assigned into the same or into different clusters under
the true and predicted clusterings [1]_.

Considering a pair of samples that is clustered together a positive pair,
then as in binary classification the count of true negatives is
:math:`C_{00}`, false negatives is :math:`C_{10}`, true positives is
:math:`C_{11}` and false positives is :math:`C_{01}`.

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

Parameters
----------
labels_true : array-like of shape (n_samples,), dtype=integral
    Ground truth class labels to be used as a reference.

labels_pred : array-like of shape (n_samples,), dtype=integral
    Cluster labels to evaluate.

Returns
-------
C : ndarray of shape (2, 2), dtype=np.int64
    The contingency matrix.

See Also
--------
sklearn.metrics.rand_score : Rand Score.
sklearn.metrics.adjusted_rand_score : Adjusted Rand Score.
sklearn.metrics.adjusted_mutual_info_score : Adjusted Mutual Information.

References
----------
.. [1] :doi:`Hubert, L., Arabie, P. "Comparing partitions."
       Journal of Classification 2, 193–218 (1985).
       <10.1007/BF01908075>`

Examples
--------
Perfectly matching labelings have all non-zero entries on the
diagonal regardless of actual label values:

  >>> from sklearn.metrics.cluster import pair_confusion_matrix
  >>> pair_confusion_matrix([0, 0, 1, 1], [1, 1, 0, 0])
  array([[8, 0],
         [0, 4]]...

Labelings that assign all classes members to the same clusters
are complete but may be not always pure, hence penalized, and
have some off-diagonal non-zero entries:

  >>> pair_confusion_matrix([0, 0, 1, 2], [0, 0, 1, 1])
  array([[8, 2],
         [0, 2]]...

Note that the matrix is not symmetric.
r   T)r   r   r   axis   )rN   rN   )r   )r   r   )r   r   )r   r   )r   r   )r$   r+   int64r   rI   ravelsumdataemptydot	transpose)r   r   	n_samplesrH   n_cn_ksum_squaresCs           r#   pair_confusion_matrixr[      s#   F  1JK**1-.I %RXXK ((;???*
+C
((;???*
+C##Q&++-K
rxx(A%AdGooc"&&(;6AdG##%))#.224{BAdGlQtW$qw.<AdGHr%   c                     [        X5      nUR                  5       R                  5       nUR                  5       nX4:X  d  US:X  a  g[        X4-  5      $ )u  Rand index.

The Rand Index computes a similarity measure between two clusterings
by considering all pairs of samples and counting pairs that are
assigned in the same or different clusters in the predicted and
true clusterings [1]_ [2]_.

The raw RI score [3]_ is:

.. code-block:: text

    RI = (number of agreeing pairs) / (number of pairs)

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

Parameters
----------
labels_true : array-like of shape (n_samples,), dtype=integral
    Ground truth class labels to be used as a reference.

labels_pred : array-like of shape (n_samples,), dtype=integral
    Cluster labels to evaluate.

Returns
-------
RI : float
   Similarity score between 0.0 and 1.0, inclusive, 1.0 stands for
   perfect match.

See Also
--------
adjusted_rand_score: Adjusted Rand Score.
adjusted_mutual_info_score: Adjusted Mutual Information.

References
----------
.. [1] :doi:`Hubert, L., Arabie, P. "Comparing partitions."
   Journal of Classification 2, 193–218 (1985).
   <10.1007/BF01908075>`.

.. [2] `Wikipedia: Simple Matching Coefficient
    <https://en.wikipedia.org/wiki/Simple_matching_coefficient>`_

.. [3] `Wikipedia: Rand Index <https://en.wikipedia.org/wiki/Rand_index>`_

Examples
--------
Perfectly matching labelings have a score of 1 even

  >>> from sklearn.metrics.cluster import rand_score
  >>> rand_score([0, 0, 1, 1], [1, 1, 0, 0])
  1.0

Labelings that assign all classes members to the same clusters
are complete but may not always be pure, hence penalized:

  >>> rand_score([0, 0, 1, 2], [0, 0, 1, 1])
  0.83
r         ?)r[   diagonalrQ   float)r   r   rH   	numeratordenominators        r#   
rand_scorerb     sR    F (AK$$&**,I//#K;!#3 ())r%   c                     [        X5      u  u  p#u  pE[        U5      [        U5      [        U5      [        U5      4u  p#pEUS:X  a  US:X  a  gSXR-  XC-  -
  -  XT-   XB-   -  XS-   X2-   -  -   -  $ )u  Rand index adjusted for chance.

The Rand Index computes a similarity measure between two clusterings
by considering all pairs of samples and counting pairs that are
assigned in the same or different clusters in the predicted and
true clusterings.

The raw RI score is then "adjusted for chance" into the ARI score
using the following scheme::

    ARI = (RI - Expected_RI) / (max(RI) - Expected_RI)

The adjusted Rand index is thus ensured to have a value close to
0.0 for random labeling independently of the number of clusters and
samples and exactly 1.0 when the clusterings are identical (up to
a permutation). The adjusted Rand index is bounded below by -0.5 for
especially discordant clusterings.

ARI is a symmetric measure::

    adjusted_rand_score(a, b) == adjusted_rand_score(b, a)

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

Parameters
----------
labels_true : array-like of shape (n_samples,), dtype=int
    Ground truth class labels to be used as a reference.

labels_pred : array-like of shape (n_samples,), dtype=int
    Cluster labels to evaluate.

Returns
-------
ARI : float
   Similarity score between -0.5 and 1.0. Random labelings have an ARI
   close to 0.0. 1.0 stands for perfect match.

See Also
--------
adjusted_mutual_info_score : Adjusted Mutual Information.

References
----------
.. [Hubert1985] L. Hubert and P. Arabie, Comparing Partitions,
  Journal of Classification 1985
  https://link.springer.com/article/10.1007%2FBF01908075

.. [Steinley2004] D. Steinley, Properties of the Hubert-Arabie
  adjusted Rand index, Psychological Methods 2004

.. [wk] https://en.wikipedia.org/wiki/Rand_index#Adjusted_Rand_index

.. [Chacon] :doi:`Minimum adjusted Rand index for two clusterings of a given size,
  2022, J. E. Chacón and A. I. Rastrojo <10.1007/s11634-022-00491-w>`

Examples
--------
Perfectly matching labelings have a score of 1 even

  >>> from sklearn.metrics.cluster import adjusted_rand_score
  >>> adjusted_rand_score([0, 0, 1, 1], [0, 0, 1, 1])
  1.0
  >>> adjusted_rand_score([0, 0, 1, 1], [1, 1, 0, 0])
  1.0

Labelings that assign all classes members to the same clusters
are complete but may not always be pure, hence penalized::

  >>> adjusted_rand_score([0, 0, 1, 2], [0, 0, 1, 1])
  0.57

ARI is symmetric, so labelings that have pure clusters with members
coming from the same classes but unnecessary splits are penalized::

  >>> adjusted_rand_score([0, 0, 1, 1], [0, 0, 1, 2])
  0.57

If classes members are completely split across different clusters, the
assignment is totally incomplete, hence the ARI is very low::

  >>> adjusted_rand_score([0, 0, 0, 0], [0, 1, 2, 3])
  0.0

ARI may take a negative value for especially discordant labelings that
are a worse choice than the expected value of random labels::

  >>> adjusted_rand_score([0, 0, 1, 1], [0, 1, 0, 1])
  -0.5

See :ref:`sphx_glr_auto_examples_cluster_plot_adjusted_for_chance_measures.py`
for a more detailed example.
r   r]   g       @)r[   int)r   r   tnfpfntps         r#   adjusted_rand_scoreri   V  s|    J /{HHRhrWc"gs2wB7NBB 
Qw27"'BG#$RW(=RW@U(UVVr%   r   r   betar]   rk   c                B   [        X5      u  p[        U 5      S:X  a  g[        U 5      n[        U5      n[        XSS9n[	        SSUS9nU(       a  Xc-  OSnU(       a  Xd-  OSnXx-   S:X  a  Sn	OS	U-   U-  U-  X'-  U-   -  n	[        U5      [        U5      [        U	5      4$ )
a  Compute the homogeneity and completeness and V-Measure scores at once.

Those metrics are based on normalized conditional entropy measures of
the clustering labeling to evaluate given the knowledge of a Ground
Truth class labels of the same samples.

A clustering result satisfies homogeneity if all of its clusters
contain only data points which are members of a single class.

A clustering result satisfies completeness if all the data points
that are members of a given class are elements of the same cluster.

Both scores have positive values between 0.0 and 1.0, larger values
being desirable.

Those 3 metrics are independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score values in any way.

V-Measure is furthermore symmetric: swapping ``labels_true`` and
``label_pred`` will give the same score. This does not hold for
homogeneity and completeness. V-Measure is identical to
:func:`normalized_mutual_info_score` with the arithmetic averaging
method.

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

Parameters
----------
labels_true : array-like of shape (n_samples,)
    Ground truth class labels to be used as a reference.

labels_pred : array-like of shape (n_samples,)
    Cluster labels to evaluate.

beta : float, default=1.0
    Ratio of weight attributed to ``homogeneity`` vs ``completeness``.
    If ``beta`` is greater than 1, ``completeness`` is weighted more
    strongly in the calculation. If ``beta`` is less than 1,
    ``homogeneity`` is weighted more strongly.

Returns
-------
homogeneity : float
    Score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling.

completeness : float
    Score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling.

v_measure : float
    Harmonic mean of the first two.

See Also
--------
homogeneity_score : Homogeneity metric of cluster labeling.
completeness_score : Completeness metric of cluster labeling.
v_measure_score : V-Measure (NMI with arithmetic mean option).

Examples
--------
>>> from sklearn.metrics import homogeneity_completeness_v_measure
>>> y_true, y_pred = [0, 0, 1, 1, 2, 2], [0, 0, 1, 2, 2, 2]
>>> homogeneity_completeness_v_measure(y_true, y_pred)
(0.71, 0.771, 0.74)
r   )r]   r]   r]   Tr   NrH   r]           r   )r$   lenentropyrI   mutual_info_scorer_   )
r   r   rk   	entropy_C	entropy_KrH   MIhomogeneitycompletenessv_measure_scores
             r#   "homogeneity_completeness_v_measurery     s    T  1JK
;1$I$I$[dKK	4;	?B&/""SK'02#cL!S( X !L02 	 u\2E/4JJJr%   c                     [        X5      S   $ )a  Homogeneity metric of a cluster labeling given a ground truth.

A clustering result satisfies homogeneity if all of its clusters
contain only data points which are members of a single class.

This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.

This metric is not symmetric: switching ``label_true`` with ``label_pred``
will return the :func:`completeness_score` which will be different in
general.

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

Parameters
----------
labels_true : array-like of shape (n_samples,)
    Ground truth class labels to be used as a reference.

labels_pred : array-like of shape (n_samples,)
    Cluster labels to evaluate.

Returns
-------
homogeneity : float
   Score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling.

See Also
--------
completeness_score : Completeness metric of cluster labeling.
v_measure_score : V-Measure (NMI with arithmetic mean option).

References
----------

.. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A
   conditional entropy-based external cluster evaluation measure
   <https://aclweb.org/anthology/D/D07/D07-1043.pdf>`_

Examples
--------

Perfect labelings are homogeneous::

  >>> from sklearn.metrics.cluster import homogeneity_score
  >>> homogeneity_score([0, 0, 1, 1], [1, 1, 0, 0])
  1.0

Non-perfect labelings that further split classes into more clusters can be
perfectly homogeneous::

  >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 1, 2]))
  1.000000
  >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 2, 3]))
  1.000000

Clusters that include samples from different classes do not make for an
homogeneous labeling::

  >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 0, 1]))
  0.0...
  >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 0, 0]))
  0.0...
r   ry   rJ   s     r#   homogeneity_scorer|   +      R .kGJJr%   c                     [        X5      S   $ )a^  Compute completeness metric of a cluster labeling given a ground truth.

A clustering result satisfies completeness if all the data points
that are members of a given class are elements of the same cluster.

This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.

This metric is not symmetric: switching ``label_true`` with ``label_pred``
will return the :func:`homogeneity_score` which will be different in
general.

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

Parameters
----------
labels_true : array-like of shape (n_samples,)
    Ground truth class labels to be used as a reference.

labels_pred : array-like of shape (n_samples,)
    Cluster labels to evaluate.

Returns
-------
completeness : float
   Score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling.

See Also
--------
homogeneity_score : Homogeneity metric of cluster labeling.
v_measure_score : V-Measure (NMI with arithmetic mean option).

References
----------

.. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A
   conditional entropy-based external cluster evaluation measure
   <https://aclweb.org/anthology/D/D07/D07-1043.pdf>`_

Examples
--------

Perfect labelings are complete::

  >>> from sklearn.metrics.cluster import completeness_score
  >>> completeness_score([0, 0, 1, 1], [1, 1, 0, 0])
  1.0

Non-perfect labelings that assign all classes members to the same clusters
are still complete::

  >>> print(completeness_score([0, 0, 1, 1], [0, 0, 0, 0]))
  1.0
  >>> print(completeness_score([0, 1, 2, 3], [0, 0, 1, 1]))
  0.999

If classes members are split across different clusters, the
assignment cannot be complete::

  >>> print(completeness_score([0, 0, 1, 1], [0, 1, 0, 1]))
  0.0
  >>> print(completeness_score([0, 0, 0, 0], [0, 1, 2, 3]))
  0.0
r   r{   rJ   s     r#   completeness_scorer   w  r}   r%   c                    [        XUS9S   $ )a  V-measure cluster labeling given a ground truth.

This score is identical to :func:`normalized_mutual_info_score` with
the ``'arithmetic'`` option for averaging.

The V-measure is the harmonic mean between homogeneity and completeness::

    v = (1 + beta) * homogeneity * completeness
         / (beta * homogeneity + completeness)

This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.

This metric is furthermore symmetric: switching ``label_true`` with
``label_pred`` will return the same score value. This can be useful to
measure the agreement of two independent label assignments strategies
on the same dataset when the real ground truth is not known.

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

Parameters
----------
labels_true : array-like of shape (n_samples,)
    Ground truth class labels to be used as a reference.

labels_pred : array-like of shape (n_samples,)
    Cluster labels to evaluate.

beta : float, default=1.0
    Ratio of weight attributed to ``homogeneity`` vs ``completeness``.
    If ``beta`` is greater than 1, ``completeness`` is weighted more
    strongly in the calculation. If ``beta`` is less than 1,
    ``homogeneity`` is weighted more strongly.

Returns
-------
v_measure : float
   Score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling.

See Also
--------
homogeneity_score : Homogeneity metric of cluster labeling.
completeness_score : Completeness metric of cluster labeling.
normalized_mutual_info_score : Normalized Mutual Information.

References
----------

.. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A
   conditional entropy-based external cluster evaluation measure
   <https://aclweb.org/anthology/D/D07/D07-1043.pdf>`_

Examples
--------
Perfect labelings are both homogeneous and complete, hence have score 1.0::

  >>> from sklearn.metrics.cluster import v_measure_score
  >>> v_measure_score([0, 0, 1, 1], [0, 0, 1, 1])
  1.0
  >>> v_measure_score([0, 0, 1, 1], [1, 1, 0, 0])
  1.0

Labelings that assign all classes members to the same clusters
are complete but not homogeneous, hence penalized::

  >>> print("%.6f" % v_measure_score([0, 0, 1, 2], [0, 0, 1, 1]))
  0.8
  >>> print("%.6f" % v_measure_score([0, 1, 2, 3], [0, 0, 1, 1]))
  0.67

Labelings that have pure clusters with members coming from the same
classes are homogeneous but un-necessary splits harm completeness
and thus penalize V-measure as well::

  >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 1, 2]))
  0.8
  >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 1, 2, 3]))
  0.67

If classes members are completely split across different clusters,
the assignment is totally incomplete, hence the V-Measure is null::

  >>> print("%.6f" % v_measure_score([0, 0, 0, 0], [0, 1, 2, 3]))
  0.0

Clusters that include samples from totally different classes totally
destroy the homogeneity of the labeling, hence::

  >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 0, 0]))
  0.0
rl   rN   r{   rj   s      r#   rx   rx     s    J .kTRSTUUr%   )r2   zsparse matrixN)r   r   rH   rn   c                   Uc  [        X5      u  p[        XSS9nO0[        U/ SQ[        [        R
                  [        R                  /S9n[        U[        R                  5      (       a  [        R                  " U5      u  p4X#U4   nO[        R                  " U5      u  p4nUR                  5       n[        R                  " UR                  SS95      n[        R                  " UR                  SS95      nUR                  S:X  d  UR                  S:X  a  g	[        R                  " U5      n	XV-  n
UR!                  U5      R#                  [        R                  S
S9UR!                  U5      R#                  [        R                  S
S9-  n[        R                  " U5      * [        UR                  5       5      -   [        UR                  5       5      -   nX[        U5      -
  -  X-  -   n[        R$                  " [        R&                  " U5      [        R(                  " UR*                  5      R,                  :  S	U5      n[/        [        R0                  " UR                  5       S	S5      5      $ )a  Mutual Information between two clusterings.

The Mutual Information is a measure of the similarity between two labels
of the same data. Where :math:`|U_i|` is the number of the samples
in cluster :math:`U_i` and :math:`|V_j|` is the number of the
samples in cluster :math:`V_j`, the Mutual Information
between clusterings :math:`U` and :math:`V` is given as:

.. math::

    MI(U,V)=\sum_{i=1}^{|U|} \sum_{j=1}^{|V|} \frac{|U_i\cap V_j|}{N}
    \log\frac{N|U_i \cap V_j|}{|U_i||V_j|}

This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.

This metric is furthermore symmetric: switching :math:`U` (i.e
``label_true``) with :math:`V` (i.e. ``label_pred``) will return the
same score value. This can be useful to measure the agreement of two
independent label assignments strategies on the same dataset when the
real ground truth is not known.

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

Parameters
----------
labels_true : array-like of shape (n_samples,), dtype=integral
    A clustering of the data into disjoint subsets, called :math:`U` in
    the above formula.

labels_pred : array-like of shape (n_samples,), dtype=integral
    A clustering of the data into disjoint subsets, called :math:`V` in
    the above formula.

contingency : {array-like, sparse matrix} of shape             (n_classes_true, n_classes_pred), default=None
    A contingency matrix given by the
    :func:`~sklearn.metrics.cluster.contingency_matrix` function. If value
    is ``None``, it will be computed, otherwise the given value is used,
    with ``labels_true`` and ``labels_pred`` ignored.

Returns
-------
mi : float
   Mutual information, a non-negative value, measured in nats using the
   natural logarithm.

See Also
--------
adjusted_mutual_info_score : Adjusted against chance Mutual Information.
normalized_mutual_info_score : Normalized Mutual Information.

Notes
-----
The logarithm used is the natural logarithm (base-e).

Examples
--------
>>> from sklearn.metrics import mutual_info_score
>>> labels_true = [0, 1, 1, 0, 1, 0]
>>> labels_pred = [0, 1, 0, 0, 1, 1]
>>> mutual_info_score(labels_true, labels_pred)
0.0566
NTr   )csrcsccoo)accept_sparser   r   rL   r   ro   Fcopy)r$   rI   r   rd   r+   int32rO   
isinstancendarraynonzeror<   findrQ   rP   sizer   takeastypewhereabsfinfor   r7   r_   clip)r   r   rH   nzxnzynz_valcontingency_sumpipjlog_contingency_nmcontingency_nmouter	log_outermis                 r#   rr   rr   +  s   T #4[#N ($O!/"((+
 +rzz**::k*#X& 77;/&!oo'O	+//q/)	*B	+//q/)	*B 
ww!|rww!|-NGGCLu58K8K
u 9L 9 E RVVX.RVVX>Is?/CCD

$	%  
"&&*rxx1555sB	?B3-..r%   >   r*   r'   r(   r)   )r   r   r0   r)   )r0   c                   [        X5      u  pU R                  S   n[        R                  " U 5      n[        R                  " U5      nUR                  S   UR                  S   s=:X  a  S:X  d-  O  UR                  S   UR                  S   s=:X  a  S:X  a   g  OgUR                  S   S:X  d  UR                  S   S:X  a  g[	        XSS9n[        XUS9n[        Xc5      n[        U 5      [        U5      p[        XU5      nX-
  nUS:  a,  [        U[        R                  " S5      R                  * 5      nO*[        U[        R                  " S5      R                  5      nXx-
  nUS:  a,  [        U[        R                  " S5      R                  * 5      nO*[        U[        R                  " S5      R                  5      n[        X-  5      $ )	a  Adjusted Mutual Information between two clusterings.

Adjusted Mutual Information (AMI) is an adjustment of the Mutual
Information (MI) score to account for chance. It accounts for the fact that
the MI is generally higher for two clusterings with a larger number of
clusters, regardless of whether there is actually more information shared.
For two clusterings :math:`U` and :math:`V`, the AMI is given as::

    AMI(U, V) = [MI(U, V) - E(MI(U, V))] / [avg(H(U), H(V)) - E(MI(U, V))]

This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.

This metric is furthermore symmetric: switching :math:`U` (``label_true``)
with :math:`V` (``labels_pred``) will return the same score value. This can
be useful to measure the agreement of two independent label assignments
strategies on the same dataset when the real ground truth is not known.

Be mindful that this function is an order of magnitude slower than other
metrics, such as the Adjusted Rand Index.

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

Parameters
----------
labels_true : int array-like of shape (n_samples,)
    A clustering of the data into disjoint subsets, called :math:`U` in
    the above formula.

labels_pred : int array-like of shape (n_samples,)
    A clustering of the data into disjoint subsets, called :math:`V` in
    the above formula.

average_method : {'min', 'geometric', 'arithmetic', 'max'}, default='arithmetic'
    How to compute the normalizer in the denominator.

    .. versionadded:: 0.20

    .. versionchanged:: 0.22
       The default value of ``average_method`` changed from 'max' to
       'arithmetic'.

Returns
-------
ami: float (upperlimited by 1.0)
   The AMI returns a value of 1 when the two partitions are identical
   (ie perfectly matched). Random partitions (independent labellings) have
   an expected AMI around 0 on average hence can be negative. The value is
   in adjusted nats (based on the natural logarithm).

See Also
--------
adjusted_rand_score : Adjusted Rand Index.
mutual_info_score : Mutual Information (not adjusted for chance).

References
----------
.. [1] `Vinh, Epps, and Bailey, (2010). Information Theoretic Measures for
   Clusterings Comparison: Variants, Properties, Normalization and
   Correction for Chance, JMLR
   <http://jmlr.csail.mit.edu/papers/volume11/vinh10a/vinh10a.pdf>`_

.. [2] `Wikipedia entry for the Adjusted Mutual Information
   <https://en.wikipedia.org/wiki/Adjusted_Mutual_Information>`_

Examples
--------

Perfect labelings are both homogeneous and complete, hence have
score 1.0::

  >>> from sklearn.metrics.cluster import adjusted_mutual_info_score
  >>> adjusted_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1])
  1.0
  >>> adjusted_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0])
  1.0

If classes members are completely split across different clusters,
the assignment is totally in-complete, hence the AMI is null::

  >>> adjusted_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3])
  0.0
r   r   r]   ro   Tr   rn   float64)r$   r   r+   r;   rI   rr   r   rq   r1   r'   r   r7   r*   r_   )r   r   r0   rV   rB   rD   rH   r   emih_trueh_pred
normalizerra   r`   s                 r#   adjusted_mutual_info_scorer     s   ~  1JK!!!$Iii$Gyy%H 	aHNN1-22==x~~a05A5 6	q	Q	(.."3q"8$[dKK	;	MB
%k
=C[)7;+?F%fnEJ"K
 Q+(;(?(?'?@+rxx	':'>'>?I1}	BHHY$7$;$;#;<		288I#6#:#:;	())r%   c                   [        X5      u  p[        R                  " U 5      n[        R                  " U5      nUR                  S   UR                  S   s=:X  a  S:X  d-  O  UR                  S   UR                  S   s=:X  a  S:X  a   g  Og[	        XSS9nUR                  [        R                  SS9n[        XUS9nUS:X  a  g	[        U 5      [        U5      p[        XxU5      n	[        Xi-  5      $ )
aK	  Normalized Mutual Information between two clusterings.

Normalized Mutual Information (NMI) is a normalization of the Mutual
Information (MI) score to scale the results between 0 (no mutual
information) and 1 (perfect correlation). In this function, mutual
information is normalized by some generalized mean of ``H(labels_true)``
and ``H(labels_pred))``, defined by the `average_method`.

This measure is not adjusted for chance. Therefore
:func:`adjusted_mutual_info_score` might be preferred.

This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.

This metric is furthermore symmetric: switching ``label_true`` with
``label_pred`` will return the same score value. This can be useful to
measure the agreement of two independent label assignments strategies
on the same dataset when the real ground truth is not known.

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

Parameters
----------
labels_true : int array-like of shape (n_samples,)
    A clustering of the data into disjoint subsets.

labels_pred : int array-like of shape (n_samples,)
    A clustering of the data into disjoint subsets.

average_method : {'min', 'geometric', 'arithmetic', 'max'}, default='arithmetic'
    How to compute the normalizer in the denominator.

    .. versionadded:: 0.20

    .. versionchanged:: 0.22
       The default value of ``average_method`` changed from 'geometric' to
       'arithmetic'.

Returns
-------
nmi : float
   Score between 0.0 and 1.0 in normalized nats (based on the natural
   logarithm). 1.0 stands for perfectly complete labeling.

See Also
--------
v_measure_score : V-Measure (NMI with arithmetic mean option).
adjusted_rand_score : Adjusted Rand Index.
adjusted_mutual_info_score : Adjusted Mutual Information (adjusted
    against chance).

Examples
--------

Perfect labelings are both homogeneous and complete, hence have
score 1.0::

  >>> from sklearn.metrics.cluster import normalized_mutual_info_score
  >>> normalized_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1])
  1.0
  >>> normalized_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0])
  1.0

If classes members are completely split across different clusters,
the assignment is totally in-complete, hence the NMI is null::

  >>> normalized_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3])
  0.0
r   r   r]   Tr   Fr   rn   ro   )r$   r+   r;   r   rI   r   r   rr   rq   r1   r_   )
r   r   r0   rB   rD   rH   r   r   r   r   s
             r#   normalized_mutual_info_scorer   )  s    b  1JKii$Gyy%H 	aHNN1-22==x~~a05A5 6$[dKK$$RZZe$<K	;	MB
 
Qw [)7;+?F%fnEJ!!r%   
deprecated)r   r   r   c                   US:w  a  [         R                  " S[        5        [        X5      u  pU R                  u  n[        XSS9nUR                  [        R                  SS9n[        R                  " UR                  UR                  5      U-
  n[        R                  " [        R                  " UR                  SS95      R                  5       S	-  5      U-
  n[        R                  " [        R                  " UR                  S
S95      R                  5       S	-  5      U-
  nUS:w  a:  [        [        R                  " XV-  5      [        R                  " XW-  5      -  5      $ S$ )a  Measure the similarity of two clusterings of a set of points.

.. versionadded:: 0.18

The Fowlkes-Mallows index (FMI) is defined as the geometric mean of
the precision and recall::

    FMI = TP / sqrt((TP + FP) * (TP + FN))

Where ``TP`` is the number of **True Positive** (i.e. the number of pairs of
points that belong to the same cluster in both ``labels_true`` and
``labels_pred``), ``FP`` is the number of **False Positive** (i.e. the
number of pairs of points that belong to the same cluster in
``labels_pred`` but not in ``labels_true``) and ``FN`` is the number of
**False Negative** (i.e. the number of pairs of points that belong to the
same cluster in ``labels_true`` but not in ``labels_pred``).

The score ranges from 0 to 1. A high value indicates a good similarity
between two clusters.

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

Parameters
----------
labels_true : array-like of shape (n_samples,), dtype=int
    A clustering of the data into disjoint subsets.

labels_pred : array-like of shape (n_samples,), dtype=int
    A clustering of the data into disjoint subsets.

sparse : bool, default=False
    Compute contingency matrix internally with sparse matrix.

    .. deprecated:: 1.7
        The ``sparse`` parameter is deprecated and will be removed in 1.9. It has
        no effect.

Returns
-------
score : float
   The resulting Fowlkes-Mallows score.

References
----------
.. [1] `E. B. Fowkles and C. L. Mallows, 1983. "A method for comparing two
   hierarchical clusterings". Journal of the American Statistical
   Association
   <https://www.tandfonline.com/doi/abs/10.1080/01621459.1983.10478008>`_

.. [2] `Wikipedia entry for the Fowlkes-Mallows Index
       <https://en.wikipedia.org/wiki/Fowlkes-Mallows_index>`_

Examples
--------

Perfect labelings are both homogeneous and complete, hence have
score 1.0::

  >>> from sklearn.metrics.cluster import fowlkes_mallows_score
  >>> fowlkes_mallows_score([0, 0, 1, 1], [0, 0, 1, 1])
  1.0
  >>> fowlkes_mallows_score([0, 0, 1, 1], [1, 1, 0, 0])
  1.0

If classes members are completely split across different clusters,
the assignment is totally random, hence the FMI is null::

  >>> fowlkes_mallows_score([0, 0, 0, 0], [0, 1, 2, 3])
  0.0
r   zThe 'sparse' parameter was deprecated in 1.7 and will be removed in 1.9. It has no effect. Leave it to its default value to silence this warning.Tr   Fr   r   rL   rN   r   ro   )r   r   FutureWarningr$   r   rI   r   r+   rO   rT   rR   rQ   asarrayrP   r_   r,   )r   r   r   rV   ctkpkqks           r#   fowlkes_mallows_scorer     s   ` W	
  1JK$$LY;DAA	&A		)	+B	

155a5=)//1Q6	7)	CB	

155a5=)//1Q6	7)	CB9;s5!BGGBG$445KKr%   labelsc           	         [        U 5      u  pnU(       a  U R                  S   O
[        U 5      nUS:X  a  gUR                  UR	                  U 5      S   [        X5      5      nUR                  S:X  a  gUR                  U5      n[        UR                  XV-  UR                  U5      [        U5      -
  -  5      * 5      $ )a  Calculate the entropy for a labeling.

Parameters
----------
labels : array-like of shape (n_samples,), dtype=int
    The labels.

Returns
-------
entropy : float
   The entropy for a labeling.

Notes
-----
The logarithm used is the natural logarithm (base-e).
r   r]   r   ro   )
r	   r   rp   r   unique_countsr   r   rQ   r_   r   )r   xpis_array_api_compliantdevice_
labels_lenr   pi_sums          r#   rq   rq     s    . +C6*J'B$:aFJQ	2##F+A.0J20W	XB 
ww!|VVBZF
 "&&"+"&&*s6{*BCDDEEr%   )*__doc__r   mathr   numbersr   numpyr+   scipyr   r<   utils._array_apir   r	   utils._param_validationr
   r   r   r   utils.multiclassr   utils.validationr   r   _expected_mutual_info_fastr   r$   r1   rO   rI   r[   rb   ri   ry   r|   r   rx   rr   r   r   r   rq    r%   r#   <module>r      sX        T T T . D C+$\
  $d+$d+q$v6=+  #'	 &*%rxxK	Kb $~$~ #'KK\ $~$~ #'F*F*R $~$~ #'fWfWR $~$~$478
 #' JM ZKZKz $~$~ #'BKBKJ $~$~ #'BKBKJ $~$~$478
 #' 7: ]V]V@ $d+$d+<
 #' @D i/i/X $~$~%&OPQ
 #' 1=**D $~$~%&OPQ
 #' 1=e"e"P $~$~fZ%?@A
 #' ?K WLWLt <. #'	!F!Fr%   