
    -i                        S r SSKrSSKJrJrJrJr  SSKJrJ	r	  SSK
rSSKJr  SSKJr  SSKJrJrJrJr  SS	KJr  SS
KJr  SSKJrJr  SSKJr  SSK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SK-J.r.  S r/S r0\$" S// SQ\"" \SSSS9S/S/S.SS9SSSS.S  j5       r1     S+S! jr2S" r3S# r4S$ r5\6" \1\3\4\5S%9r7S& r8 " S' S(\\5      r9 " S) S*\\.\95      r:g),z}Hierarchical Agglomerative Clustering

These routines perform some hierarchical agglomerative clustering of some
input data.
    N)heapifyheappopheappushheappushpop)IntegralReal)sparse)connected_components   )BaseEstimatorClassNamePrefixFeaturesOutMixinClusterMixin_fit_context)DistanceMetric)METRIC_MAPPING64)_VALID_METRICSpaired_distances)check_array)IntFloatDict)
HasMethodsInterval
StrOptionsvalidate_params)_fix_connected_components)check_memoryvalidate_data   )_hierarchical_fast)AgglomerationTransformc           	         U R                   S   nUR                   S   U:w  d  UR                   S   U:w  a'  [        SUR                   < SU R                   < 35      eXR                  -   n[        R                  " U5      (       d  [        R
                  " U5      nUR                  S:w  a  UR                  5       n[        U5      u  pEUS:  a&  [        R                  " SU-  SS9  [        U UUUUS	S
9nX4$ )a  
Fixes the connectivity matrix.

The different steps are:

- copies it
- makes it symmetric
- converts it to LIL if necessary
- completes it if necessary.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    Feature matrix representing `n_samples` samples to be clustered.

connectivity : sparse matrix, default=None
    Connectivity matrix. Defines for each sample the neighboring samples
    following a given structure of the data. The matrix is assumed to
    be symmetric and only the upper triangular half is used.
    Default is `None`, i.e, the Ward algorithm is unstructured.

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.

Returns
-------
connectivity : sparse matrix
    The fixed connectivity matrix.

n_connected_components : int
    The number of connected components in the graph.
r   r   z%Wrong shape for connectivity matrix: z when X is lilzxthe number of connected components of the connectivity matrix is %d > 1. Completing it to avoid stopping the tree early.r   
stacklevelconnectivity)Xgraphn_connected_componentscomponent_labelsmetricmode)shape
ValueErrorTr	   issparse
lil_matrixformattolilr
   warningswarnr   )r%   r$   affinity	n_samplesr'   labelss         Q/var/www/html/venv/lib/python3.13/site-packages/sklearn/cluster/_agglomerative.py_fix_connectivityr8   .   s   F 
I!	)\-?-?-Bi-O!!177,
 	
  ..0L ??<((((6 e##))+ &:,%G"!')?@ 		
 1#9#
 //    c                    SSK Jn  U R                  [        R                  SS9n [        R
                  " U R                  R                  S9R                  nXpR                  U R                  S:H  '   U" U R                  5       5      nUR                  5       nSUR                  UR                  U:H  '   [        R                  " UR                  UR                  UR                  /5      R                  n	U	[        R                  " U	R                  S   SS9S	S	24   n	[         R"                  " U	5      n
U
S	S	2S	S24   R                  [$        5      n[        R&                  " U[        R(                  S9n[+        X5       H&  u  nu  pUb  X:  a    OX:  a  XU'   X:  d  M"  XU'   M(     U(       a  U
S	S	2S4   nXXU4$ XX4$ )
z
Perform single linkage clustering on sparse data via the minimum
spanning tree from scipy.sparse.csgraph, then using union-find to label.
The parent array is then generated by walking through the tree.
r   )minimum_spanning_treeFcopydtyper   	mergesortkindN)scipy.sparse.csgraphr;   astypenpfloat64finfodatar?   epstocsrtocoovstackrowcolr-   argsort_hierarchical_single_linkage_labelintarangeintp	enumerate)r$   r5   n_nodes
n_clustersr'   return_distancer;   epsilon_valuemst	mst_arraysingle_linkage_tree	children_parentileftright	distancess                    r7   _single_linkage_treerc   z   s    ;  &&rzz&>L HH<#4#4#:#:;??M0=l''1,-   2 2 4
5C ))+C +,CHHSXX&'		377CGGSXX6799I "**Y[[^+FIJI (==iH#ArrE*11#6I YYwbgg.F%i;=D!al>4L?5M < '1-	)YNNi??r9   
array-like)rd   sparse matrixNr`   closedboolean)r%   r$   rW   rX   Tprefer_skip_nested_validationFr$   rW   rX   c                
   [         R                  " U 5      n U R                  S:X  a  [         R                  " U S5      n U R                  u  pEUc  SSKJn  Ub  [        R                  " SSS9  [         R                  " U S	S
9n UR                  U 5      nUSS2SS24   R                  [         R                  5      nU(       a  USS2S4   n	USUSU	4$ USUS4$ [        XSS9u  pUc	  SU-  S-
  nOX$:  a  [        SX$4-  5      eSU-  U-
  n/ n/ n/ n[        UR                   5       H`  u  nnUR#                  U5        U Vs/ s H  nUU:  d  M  UPM     nnUR%                  ['        U5      U/-  5        UR%                  U5        Mb     [         R(                  " U[         R                  SS9n[         R(                  " U[         R                  SS9n[         R*                  " USS9nSUSU& [         R*                  " X4SS9nU USU& [         R,                  " ['        U5      [         R.                  SS9n[0        R2                  " UUXU5        [5        [7        UX5      5      n[9        U5        [         R:                  " U[         R                  S9n[         R<                  " U[>        S9n/ nU(       a  [         R,                  " X-
  5      n	[         R,                  " U[>        SS9n[A        XK5       GH  n [C        U5      u  nnnUU   (       a  UU   (       a  OM&  UUsUU'   UU'   UR#                  UU45        S=UU'   UU'   U(       a  UW	UU-
  '   UU   UU   -   UU'   UU   UU   -   UU'   / nURE                  S5        SUU'   [0        RF                  " UU   UUU5        [0        RF                  " UU   UUU5        U Vs/ s H  nUU   R#                  U5      PM       nUR#                  U5        [         R(                  " U[         R                  SS9n[         R,                  " UR                  [         R                  SS9nURE                  U5        ['        U5      n[         R,                  " U[         R.                  SS9n[0        R2                  " UUXU5        [A        U5       Vs/ s H  n[I        UUU   UUU   45      PM       nGM     Un U V!s/ s H  n!U!SSS2   PM     nn![         R(                  " U5      nU(       a   [         RJ                  " SW	-  5      n	UU
U UU	4$ UU
U U4$ s  snf s  snf s  snf s  sn!f )a   Ward clustering based on a Feature matrix.

Recursively merges the pair of clusters that minimally increases
within-cluster variance.

The inertia matrix uses a Heapq-based representation.

This is the structured version, that takes into account some topological
structure between samples.

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

Parameters
----------
X : array-like of shape (n_samples, n_features)
    Feature matrix representing `n_samples` samples to be clustered.

connectivity : {array-like, sparse matrix}, default=None
    Connectivity matrix. Defines for each sample the neighboring samples
    following a given structure of the data. The matrix is assumed to
    be symmetric and only the upper triangular half is used.
    Default is None, i.e, the Ward algorithm is unstructured.

n_clusters : int, default=None
    `n_clusters` should be less than `n_samples`.  Stop early the
    construction of the tree at `n_clusters.` This is useful to decrease
    computation time if the number of clusters is not small compared to the
    number of samples. In this case, the complete tree is not computed, thus
    the 'children' output is of limited use, and the 'parents' output should
    rather be used. This option is valid only when specifying a connectivity
    matrix.

return_distance : bool, default=False
    If `True`, return the distance between the clusters.

Returns
-------
children : ndarray of shape (n_nodes-1, 2)
    The children of each non-leaf node. Values less than `n_samples`
    correspond to leaves of the tree which are the original samples.
    A node `i` greater than or equal to `n_samples` is a non-leaf
    node and has children `children_[i - n_samples]`. Alternatively
    at the i-th iteration, children[i][0] and children[i][1]
    are merged to form node `n_samples + i`.

n_connected_components : int
    The number of connected components in the graph.

n_leaves : int
    The number of leaves in the tree.

parents : ndarray of shape (n_nodes,) or None
    The parent of each node. Only returned when a connectivity matrix
    is specified, elsewhere 'None' is returned.

distances : ndarray of shape (n_nodes-1,)
    Only returned if `return_distance` is set to `True` (for compatibility).
    The distances between the centers of the nodes. `distances[i]`
    corresponds to a weighted Euclidean distance between
    the nodes `children[i, 1]` and `children[i, 2]`. If the nodes refer to
    leaves of the tree, then `distances[i]` is their unweighted Euclidean
    distance. Distances are updated in the following way
    (from scipy.hierarchy.linkage):

    The new entry :math:`d(u,v)` is computed as follows,

    .. math::

       d(u,v) = \sqrt{\frac{|v|+|s|}
                           {T}d(v,s)^2
                    + \frac{|v|+|t|}
                           {T}d(v,t)^2
                    - \frac{|v|}
                           {T}d(s,t)^2}

    where :math:`u` is the newly joined cluster consisting of
    clusters :math:`s` and :math:`t`, :math:`v` is an unused
    cluster in the forest, :math:`T=|v|+|s|+|t|`, and
    :math:`|*|` is the cardinality of its argument. This is also
    known as the incremental algorithm.

Examples
--------
>>> import numpy as np
>>> from sklearn.cluster import ward_tree
>>> X = np.array([[1, 2], [1, 4], [1, 0],
...               [4, 2], [4, 4], [4, 0]])
>>> children, n_connected_components, n_leaves, parents = ward_tree(X)
>>> children
array([[0, 1],
       [3, 5],
       [2, 6],
       [4, 7],
       [8, 9]])
>>> n_connected_components
1
>>> n_leaves
6
r   r   Nr   	hierarchyPartial build of the tree is implemented only for structured clustering (i.e. with explicit connectivity). The algorithm will build the full tree and only retain the lower branches required for the specified number of clustersr   r"   W)requirements	euclideanr4   z]Cannot provide more clusters than samples. %i n_clusters was asked, and there are %i samples.C)r?   order)rw   r>   Frn   g       @)&rE   asarrayndimreshaper+   scipy.clusterrp   r2   r3   requirewardrD   rT   r8   r,   rU   rowsappendextendlenarrayzerosemptyrF   rP   compute_ward_distlistzipr   rS   onesboolranger   fill_get_parentsr   sqrt)"r%   r$   rW   rX   r5   
n_featuresrp   outr]   rb   r'   rV   	coord_row	coord_colAindrM   r_   	moments_1	moments_2inertiar^   	used_nodechildrennot_visitedkinertjrN   n_additionsiniidxn_leavescs"                                     r7   	ward_treer      s   Z 	

1Avv{JJq'"GGI+!MM; 
 JJqs+nnQ2A2J%%bgg.	AqD	IaD);;aD00+<	+,(L i-!#!(45 
 i-*, II
Al//0S	 )#QSq#)H	
 	 1 "''=I"''=I ,IIjy'.c:IIjyhhs9~RZZsCG##Iy)PWX3w	56GG YYwbgg.Ft,IHHHW01	((7$c:K 9&!'*KE1a|	!   !!q	6!9A&++	!y|',Ia)m$ !|il2	! |il2	! 	A""1Q4FKH""1Q4FKH%./Yc3q	Y/	HHYbggSA	HHY__BGG3G	q)nhh{"**C@''	9iTWX FK;EWXEWc'CHa38	9EWXE 'J H!)*A$B$H*xx!HGGC)O,	/69LL/6AA_ *n 	0 	Y
 +s   
T.T.T3+T8T=c           
        ^% [         R                  " U 5      n U R                  S:X  a  [         R                  " U S5      n U R                  u  pg[
        R                  [
        R                  SS.n X   n	US:X  a:  [         R                  " [         R                  " U SS	9) 5      (       a  [        S
5      eUGc  SSKJn  Ub  [        R                  " SSS9  US:X  ac  U R                  S   U R                  S   :w  a  [        SU R                   35      e[         R                   " U R                  S   SS9u  pXU4   n OTUS:X  a  SnOKUS;   a  SnOB[#        U5      (       a2  U" U 5      n [         R                   " U R                  S   SS9u  pXU4   n US:X  a  US:w  a  [#        U5      (       d  U[$        ;   a  [&        R(                  " U5      n[         R*                  " U [         R,                  S9n [
        R.                  " X5      nU[         R0                  " UR2                  S   SS9SS24   n[
        R4                  " U5      nOUR7                  XUS9nUSS2SS24   R9                  [:        SS9nU(       a  USS2S4   nUSUSU4$ USUS4$ [=        XUS9u  nnUR?                  5       nUR@                  URB                  :g  nUR@                  U   Ul         URB                  U   Ul!        URD                  U   Ul"        AUS:X  a7  XR@                  URB                  4   R9                  [         RF                  SS9nO#[I        XR@                     XRB                     US9nUUl"        Uc	  SU-  S-
  nOX&::  d   eSU-  U-
  nUS:X  a  [K        UUUUUU5      $ U(       a  [         RL                  " UU-
  5      n[         RL                  " U[N        S9n[Q        5       nURS                  5       n[U        [W        URD                  URX                  5      5       H  u  m%u  nn[[        [         R                  " U[         R\                  S9[         R                  " U[         RF                  S95      UT%'   UR_                  U%4S  j[W        UU5       5       5        M     A[a        U5        [         Rb                  " U[         R\                  S9n[         Rd                  " U[         R\                  S9n/ n[g        UU5       GH  n [i        U5      nUURj                     (       a  UURl                     (       a  OM6  URj                  nURl                  nU(       a  URn                  UUU-
  '   U=UU'   UU'   URq                  X45        UU   nUU   n UU -   UU'   S=UU'   UU'   U	" UU   UU   UUU 5      n!U! H=  u  n"n#UU"   Rq                  UU#5        [s        U[
        Rt                  " U#UU"5      5        M?     U!UU'   S=UU'   UU'   GM     Un$[         Rv                  " U5      SS2SSS!24   nU(       a  UUU$UU4$ UUU$U4$ ! [         a(  n
[        SUR                  5       < SU< S35      U
eSn
A
ff = f)"a  Linkage agglomerative clustering based on a Feature matrix.

The inertia matrix uses a Heapq-based representation.

This is the structured version, that takes into account some topological
structure between samples.

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

Parameters
----------
X : array-like of shape (n_samples, n_features)
    Feature matrix representing `n_samples` samples to be clustered.

connectivity : sparse matrix, default=None
    Connectivity matrix. Defines for each sample the neighboring samples
    following a given structure of the data. The matrix is assumed to
    be symmetric and only the upper triangular half is used.
    Default is `None`, i.e, the Ward algorithm is unstructured.

n_clusters : int, default=None
    Stop early the construction of the tree at `n_clusters`. This is
    useful to decrease computation time if the number of clusters is
    not small compared to the number of samples. In this case, the
    complete tree is not computed, thus the 'children' output is of
    limited use, and the 'parents' output should rather be used.
    This option is valid only when specifying a connectivity matrix.

linkage : {"average", "complete", "single"}, default="complete"
    Which linkage criteria to use. The linkage criterion determines which
    distance to use between sets of observation.
        - "average" uses the average of the distances of each observation of
          the two sets.
        - "complete" or maximum linkage uses the maximum distances between
          all observations of the two sets.
        - "single" uses the minimum of the distances between all
          observations of the two sets.

affinity : str or callable, default='euclidean'
    Which metric to use. Can be 'euclidean', 'manhattan', or any
    distance known to paired distance (see metric.pairwise).

return_distance : bool, default=False
    Whether or not to return the distances between the clusters.

Returns
-------
children : ndarray of shape (n_nodes-1, 2)
    The children of each non-leaf node. Values less than `n_samples`
    correspond to leaves of the tree which are the original samples.
    A node `i` greater than or equal to `n_samples` is a non-leaf
    node and has children `children_[i - n_samples]`. Alternatively
    at the i-th iteration, children[i][0] and children[i][1]
    are merged to form node `n_samples + i`.

n_connected_components : int
    The number of connected components in the graph.

n_leaves : int
    The number of leaves in the tree.

parents : ndarray of shape (n_nodes, ) or None
    The parent of each node. Only returned when a connectivity matrix
    is specified, elsewhere 'None' is returned.

distances : ndarray of shape (n_nodes-1,)
    Returned when `return_distance` is set to `True`.

    distances[i] refers to the distance between children[i][0] and
    children[i][1] when they are merged.

See Also
--------
ward_tree : Hierarchical clustering with ward linkage.
r   rm   N)completeaveragesinglez1Unknown linkage option, linkage should be one of z, but z
 was givencosine)axisz;Cosine affinity cannot be used when X contains zero vectorsr   ro   rq   r   r"   precomputedz6Distance matrix should be square, got matrix of shape )r   l2rt   )l1	manhattan	cityblockr   r>   r@   rA   )methodr)   Fr<   ru   )r)   c              3   h   >#    U  H'  u  pUT:  d  M  [         R                  " UTU5      v   M)     g 7fN)rP   WeightedEdge).0rdr   s      r7   	<genexpr>linkage_tree.<locals>.<genexpr>  s4      
>LdaPQTWPW1M&&q#q11ns   22rn   )<rE   rx   ry   rz   r+   rP   	max_mergeaverage_mergeKeyErrorr,   keysanyr{   rp   r2   r3   triu_indicescallabler   r   
get_metricascontiguousarraydoublemst_linkage_corerO   r-   single_linkage_labellinkagerD   rR   r8   rK   rM   rN   rH   rF   r   rc   r   objectr   r1   rU   r   r~   r   rT   r   r   rS   r   r   r   abweightr   r   r   r   )&r%   r$   rW   r   r4   rX   r5   r   linkage_choices	join_funcerp   r_   r   dist_metricrZ   r   r]   rb   r'   	diag_maskrV   r   r   rH   rM   r^   r   r   r   edgen_in_jr   rN   r   r   r   s&                                        @r7   linkage_treer     sF   f 	

1Avv{JJq'"GGI "++ ..O
#,	 8qq(9'9 : :VWW+!MM; 
 }$ wwqzQWWQZ' LQWWIV  ??1771:3DAQ$A"H,,"HhA??1771:3DAQ$AxM)X&&,, )33H=K $$Qbii8A00@Cbjjq<a?@C  44S9C##Ah#GC2A2J%%c%6	AqD	IaD);;!Y,,+<	(,(L(  %%'L  L$4$44I#''	2L#''	2L$)))4L= &&(8(889@@RW@X	 %#3#3!4X
	 "Li-!#&&&i-*,(#"
 	
 HHWy01	
'AfG  %%'L%c,*;*;\=N=N&OP[dCJJs"''*BJJt2::,N
#
 	 
>A#tn
 	
 Q 	G YYwbgg.Frww/IH 9g&7#D Ytvv%6  FFFF'+{{Ia)m$ !!q	F1IllSy	!&++	!y| adAaD)S#>	FCcFMM!Q Wm88AsCD	  
 !!qt? 'D H xx!!TrT'*H/69LL+Xv==e  ##%w0
 	s   0X? ?
Y1	#Y,,Y1c                  "    SUS'   [        U 0 UD6$ )Nr   r   r   argskwargss     r7   _complete_linkager     s    "F9(((r9   c                  "    SUS'   [        U 0 UD6$ )Nr   r   r   r   s     r7   _average_linkager     s    !F9(((r9   c                  "    SUS'   [        U 0 UD6$ )Nr   r   r   r   s     r7   _single_linkager     s     F9(((r9   )r}   r   r   r   c                 x   X:  a  [        SU  SU S35      e[        US   5      S-   * /n[        U S-
  5       H,  nXS   * U-
     n[        X5S   * 5        [	        X5S   * 5        M.     [
        R                  " U[
        R                  S9n[        U5       H  u  pxXv[        R                  " U* X5      '   M!     U$ )a  Function cutting the ward tree for a given number of clusters.

Parameters
----------
n_clusters : int or ndarray
    The number of clusters to form.

children : ndarray of shape (n_nodes-1, 2)
    The children of each non-leaf node. Values less than `n_samples`
    correspond to leaves of the tree which are the original samples.
    A node `i` greater than or equal to `n_samples` is a non-leaf
    node and has children `children_[i - n_samples]`. Alternatively
    at the i-th iteration, children[i][0] and children[i][1]
    are merged to form node `n_samples + i`.

n_leaves : int
    Number of leaves of the tree.

Returns
-------
labels : array [n_samples]
    Cluster labels for each point.
z+Cannot extract more clusters than samples: z% clusters were given for a tree with z leaves.rn   r   r   r>   )r,   maxr   r   r   rE   r   rT   rU   rP   _hc_get_descendent)	rW   r   r   nodes_these_childrenlabelr_   nodes	            r7   _hc_cutr     s    0 9l?zS
 	
 8B< 1$%&E:>"!8)h"67**+E1--. # HHXRWW-EU#MNm..uhIJ $Lr9   c                   @  ^  \ rS rSr% Sr\" \SSSS9S/\" \" \	5      S1-  5      \
/\\" S5      S/S	S
\
S/\" S15      S/\" \" \R                  5       5      5      /\" \SSSS9S/S/S.r\\S'    SSSSSSSSS.S jjr\" SS9SS j5       rS rSU 4S jjrSrU =r$ )AgglomerativeClusteringi  a  
Agglomerative Clustering.

Recursively merges pair of clusters of sample data; uses linkage distance.

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

Parameters
----------
n_clusters : int or None, default=2
    The number of clusters to find. It must be ``None`` if
    ``distance_threshold`` is not ``None``.

metric : str or callable, default="euclidean"
    Metric used to compute the linkage. Can be "euclidean", "l1", "l2",
    "manhattan", "cosine", or "precomputed". If linkage is "ward", only
    "euclidean" is accepted. If "precomputed", a distance matrix is needed
    as input for the fit method. If connectivity is None, linkage is
    "single" and affinity is not "precomputed" any valid pairwise distance
    metric can be assigned.

    For an example of agglomerative clustering with different metrics, see
    :ref:`sphx_glr_auto_examples_cluster_plot_agglomerative_clustering_metrics.py`.

    .. versionadded:: 1.2

memory : str or object with the joblib.Memory interface, default=None
    Used to cache the output of the computation of the tree.
    By default, no caching is done. If a string is given, it is the
    path to the caching directory.

connectivity : array-like, sparse matrix, or callable, default=None
    Connectivity matrix. Defines for each sample the neighboring
    samples following a given structure of the data.
    This can be a connectivity matrix itself or a callable that transforms
    the data into a connectivity matrix, such as derived from
    `kneighbors_graph`. Default is ``None``, i.e, the
    hierarchical clustering algorithm is unstructured.

    For an example of connectivity matrix using
    :class:`~sklearn.neighbors.kneighbors_graph`, see
    :ref:`sphx_glr_auto_examples_cluster_plot_agglomerative_clustering.py`.

compute_full_tree : 'auto' or bool, default='auto'
    Stop early the construction of the tree at ``n_clusters``. This is
    useful to decrease computation time if the number of clusters is not
    small compared to the number of samples. This option is useful only
    when specifying a connectivity matrix. Note also that when varying the
    number of clusters and using caching, it may be advantageous to compute
    the full tree. It must be ``True`` if ``distance_threshold`` is not
    ``None``. By default `compute_full_tree` is "auto", which is equivalent
    to `True` when `distance_threshold` is not `None` or that `n_clusters`
    is inferior to the maximum between 100 or `0.02 * n_samples`.
    Otherwise, "auto" is equivalent to `False`.

linkage : {'ward', 'complete', 'average', 'single'}, default='ward'
    Which linkage criterion to use. The linkage criterion determines which
    distance to use between sets of observation. The algorithm will merge
    the pairs of cluster that minimize this criterion.

    - 'ward' minimizes the variance of the clusters being merged.
    - 'average' uses the average of the distances of each observation of
      the two sets.
    - 'complete' or 'maximum' linkage uses the maximum distances between
      all observations of the two sets.
    - 'single' uses the minimum of the distances between all observations
      of the two sets.

    .. versionadded:: 0.20
        Added the 'single' option

    For examples comparing different `linkage` criteria, see
    :ref:`sphx_glr_auto_examples_cluster_plot_linkage_comparison.py`.

distance_threshold : float, default=None
    The linkage distance threshold at or above which clusters will not be
    merged. If not ``None``, ``n_clusters`` must be ``None`` and
    ``compute_full_tree`` must be ``True``.

    .. versionadded:: 0.21

compute_distances : bool, default=False
    Computes distances between clusters even if `distance_threshold` is not
    used. This can be used to make dendrogram visualization, but introduces
    a computational and memory overhead.

    .. versionadded:: 0.24

    For an example of dendrogram visualization, see
    :ref:`sphx_glr_auto_examples_cluster_plot_agglomerative_dendrogram.py`.

Attributes
----------
n_clusters_ : int
    The number of clusters found by the algorithm. If
    ``distance_threshold=None``, it will be equal to the given
    ``n_clusters``.

labels_ : ndarray of shape (n_samples)
    Cluster labels for each point.

n_leaves_ : int
    Number of leaves in the hierarchical tree.

n_connected_components_ : int
    The estimated number of connected components in the graph.

    .. versionadded:: 0.21
        ``n_connected_components_`` was added to replace ``n_components_``.

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

children_ : array-like of shape (n_samples-1, 2)
    The children of each non-leaf node. Values less than `n_samples`
    correspond to leaves of the tree which are the original samples.
    A node `i` greater than or equal to `n_samples` is a non-leaf
    node and has children `children_[i - n_samples]`. Alternatively
    at the i-th iteration, children[i][0] and children[i][1]
    are merged to form node `n_samples + i`.

distances_ : array-like of shape (n_nodes-1,)
    Distances between nodes in the corresponding place in `children_`.
    Only computed if `distance_threshold` is used or `compute_distances`
    is set to `True`.

See Also
--------
FeatureAgglomeration : Agglomerative clustering but for features instead of
    samples.
ward_tree : Hierarchical clustering with ward linkage.

Examples
--------
>>> from sklearn.cluster import AgglomerativeClustering
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
...               [4, 2], [4, 4], [4, 0]])
>>> clustering = AgglomerativeClustering().fit(X)
>>> clustering
AgglomerativeClustering()
>>> clustering.labels_
array([1, 1, 1, 0, 0, 0])

For a comparison of Agglomerative clustering with other clustering algorithms, see
:ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py`
r   Nr`   rf   r   cacherd   re   autorh   r   )rW   r)   memoryr$   compute_full_treer   distance_thresholdcompute_distances_parameter_constraintsrt   r}   F)r)   r   r$   r   r   r   r   c                d    Xl         Xpl        X0l        X@l        XPl        X`l        X l        Xl        g r   )rW   r   r   r$   r   r   r)   r   )	selfrW   r)   r   r$   r   r   r   r   s	            r7   __init__ AgglomerativeClustering.__init__  s0     %"4(!2!2r9   Tri   c                 8    [        XSS9nU R                  U5      $ )a  Fit the hierarchical clustering from features, or distance matrix.

Parameters
----------
X : array-like, shape (n_samples, n_features) or                 (n_samples, n_samples)
    Training instances to cluster, or distances between instances if
    ``metric='precomputed'``.

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

Returns
-------
self : object
    Returns the fitted instance.
r   )ensure_min_samples)r   _fit)r   r%   ys      r7   fitAgglomerativeClustering.fit  s    & $a8yy|r9   c                    [        U R                  5      nU R                  SL U R                  SL -  (       d  [	        S5      eU R                  b  U R
                  (       d  [	        S5      eU R                  S:X  a(  U R                  S:w  a  [	        U R                   S35      e[        U R                     nU R                  nU R                  b7  [        U R                  5      (       a  U R                  U5      n[        U/ SQS9n[        U5      nU R
                  nU R                  c  S	nUS
:X  a,  U R                  b  S	nOU R                  [        SSU-  5      :  nU R                  nU(       a  Sn0 nU R                  S:w  a  U R                  US'   U R                  US'   U R                  n	U	SL=(       d    U R                  n
UR                  U5      " U4UUU
S.UD6nUSS u  U l        U l        U l        nU
(       a
  US   U l        U R                  b,  [(        R*                  " U R&                  U	:  5      S-   U l        OU R                  U l        U(       a2  [/        U R,                  U R                   U R$                  5      U l        U $ [2        R4                  " USS9n[(        R6                  " USU 5      n[(        R8                  " [(        R:                  " U5      U5      U l        U $ )a  Fit without validation

Parameters
----------
X : ndarray of shape (n_samples, n_features) or (n_samples, n_samples)
    Training instances to cluster, or distances between instances if
    ``metric='precomputed'``.

Returns
-------
self : object
    Returns the fitted instance.
Nz_Exactly one of n_clusters and distance_threshold has to be set, and the other needs to be None.z<compute_full_tree must be True if distance_threshold is set.r}   rt   zE was provided as metric. Ward can only work with euclidean distances.)csrcoor!   )accept_sparseTr   d   g{Gz?r   r4   rk      rn   r   Fr<   )r   r   rW   r   r,   r   r   r)   _TREE_BUILDERSr$   r   r   r   r   r   r   r]   n_connected_components_	n_leaves_
distances_rE   count_nonzeron_clusters_r   labels_rP   hc_get_headsr=   searchsortedunique)r   r%   r   tree_builderr$   r5   r   rW   r   r   rX   r   parentsr6   s                 r7   r   AgglomerativeClustering._fit  s    dkk*D(T-D-D-LM$  "".t7M7MN  <<6!dkk[&@;;-  1 1 
 &dll3((())**#003&,AL F	 22$ $&&&2$(!
 %)OOc#ti?O6P$P!__
J <<6! $F9!%F:!44-T9Td>T>Tll<(
%!+	

 
 SVQS
O5t~w !"gDO"".  4F!FG!K   $D "4#3#3T^^T^^TDL  #//eDFWWVJY/0F??299V+<fEDLr9   c                 "   > [         TU ]  X5      $ )a-  Fit and return the result of each sample's clustering assignment.

In addition to fitting, this method also return the result of the
clustering assignment for each sample in the training set.

Parameters
----------
X : array-like of shape (n_samples, n_features) or                 (n_samples, n_samples)
    Training instances to cluster, or distances between instances if
    ``affinity='precomputed'``.

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

Returns
-------
labels : ndarray of shape (n_samples,)
    Cluster labels.
)superfit_predictr   r%   r   	__class__s      r7   r  #AgglomerativeClustering.fit_predictG  s    * w"1((r9   )r]   r   r   r$   r   r   r  r   r   r)   rW   r  r   r   r   r   )__name__
__module____qualname____firstlineno____doc__r   r   r   setr   r   strr   r   r   r   r   dict__annotations__r   r   r   r   r  __static_attributes____classcell__r  s   @r7   r   r     s    Zz  !T&A4Hs>*m_<=
 
7+T2%$G(&2I>s>#6#6#89:;'afEtL'[$D   3  3* 5 6*dL) )r9   r   c                   `  ^  \ rS rSr% Sr\" \SSSS9S/\" \" \	5      S1-  5      \
/\\" S5      S/S	S
\
S/\" S15      S/\" \" \R                  5       5      5      /\
/\" \SSSS9S/S/S.	r\\S'    SSSSSS\R(                  SSS.U 4S jjjr\" SS9SU 4S jj5       r\S 5       rSrU =r$ )FeatureAgglomerationi_  a  Agglomerate features.

Recursively merges pair of clusters of features.

Refer to
:ref:`sphx_glr_auto_examples_cluster_plot_feature_agglomeration_vs_univariate_selection.py`
for an example comparison of :class:`FeatureAgglomeration` strategy with a
univariate feature selection strategy (based on ANOVA).

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

Parameters
----------
n_clusters : int or None, default=2
    The number of clusters to find. It must be ``None`` if
    ``distance_threshold`` is not ``None``.

metric : str or callable, default="euclidean"
    Metric used to compute the linkage. Can be "euclidean", "l1", "l2",
    "manhattan", "cosine", or "precomputed". If linkage is "ward", only
    "euclidean" is accepted. If "precomputed", a distance matrix is needed
    as input for the fit method.

    .. versionadded:: 1.2

memory : str or object with the joblib.Memory interface, default=None
    Used to cache the output of the computation of the tree.
    By default, no caching is done. If a string is given, it is the
    path to the caching directory.

connectivity : array-like, sparse matrix, or callable, default=None
    Connectivity matrix. Defines for each feature the neighboring
    features following a given structure of the data.
    This can be a connectivity matrix itself or a callable that transforms
    the data into a connectivity matrix, such as derived from
    `kneighbors_graph`. Default is `None`, i.e, the
    hierarchical clustering algorithm is unstructured.

compute_full_tree : 'auto' or bool, default='auto'
    Stop early the construction of the tree at `n_clusters`. This is useful
    to decrease computation time if the number of clusters is not small
    compared to the number of features. This option is useful only when
    specifying a connectivity matrix. Note also that when varying the
    number of clusters and using caching, it may be advantageous to compute
    the full tree. It must be ``True`` if ``distance_threshold`` is not
    ``None``. By default `compute_full_tree` is "auto", which is equivalent
    to `True` when `distance_threshold` is not `None` or that `n_clusters`
    is inferior to the maximum between 100 or `0.02 * n_samples`.
    Otherwise, "auto" is equivalent to `False`.

linkage : {"ward", "complete", "average", "single"}, default="ward"
    Which linkage criterion to use. The linkage criterion determines which
    distance to use between sets of features. The algorithm will merge
    the pairs of cluster that minimize this criterion.

    - "ward" minimizes the variance of the clusters being merged.
    - "complete" or maximum linkage uses the maximum distances between
      all features of the two sets.
    - "average" uses the average of the distances of each feature of
      the two sets.
    - "single" uses the minimum of the distances between all features
      of the two sets.

pooling_func : callable, default=np.mean
    This combines the values of agglomerated features into a single
    value, and should accept an array of shape [M, N] and the keyword
    argument `axis=1`, and reduce it to an array of size [M].

distance_threshold : float, default=None
    The linkage distance threshold at or above which clusters will not be
    merged. If not ``None``, ``n_clusters`` must be ``None`` and
    ``compute_full_tree`` must be ``True``.

    .. versionadded:: 0.21

compute_distances : bool, default=False
    Computes distances between clusters even if `distance_threshold` is not
    used. This can be used to make dendrogram visualization, but introduces
    a computational and memory overhead.

    .. versionadded:: 0.24

Attributes
----------
n_clusters_ : int
    The number of clusters found by the algorithm. If
    ``distance_threshold=None``, it will be equal to the given
    ``n_clusters``.

labels_ : array-like of (n_features,)
    Cluster labels for each feature.

n_leaves_ : int
    Number of leaves in the hierarchical tree.

n_connected_components_ : int
    The estimated number of connected components in the graph.

    .. versionadded:: 0.21
        ``n_connected_components_`` was added to replace ``n_components_``.

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

children_ : array-like of shape (n_nodes-1, 2)
    The children of each non-leaf node. Values less than `n_features`
    correspond to leaves of the tree which are the original samples.
    A node `i` greater than or equal to `n_features` is a non-leaf
    node and has children `children_[i - n_features]`. Alternatively
    at the i-th iteration, children[i][0] and children[i][1]
    are merged to form node `n_features + i`.

distances_ : array-like of shape (n_nodes-1,)
    Distances between nodes in the corresponding place in `children_`.
    Only computed if `distance_threshold` is used or `compute_distances`
    is set to `True`.

See Also
--------
AgglomerativeClustering : Agglomerative clustering samples instead of
    features.
ward_tree : Hierarchical clustering with ward linkage.

Examples
--------
>>> import numpy as np
>>> from sklearn import datasets, cluster
>>> digits = datasets.load_digits()
>>> images = digits.images
>>> X = np.reshape(images, (len(images), -1))
>>> agglo = cluster.FeatureAgglomeration(n_clusters=32)
>>> agglo.fit(X)
FeatureAgglomeration(n_clusters=32)
>>> X_reduced = agglo.transform(X)
>>> X_reduced.shape
(1797, 32)
r   Nr`   rf   r   r   rd   re   r   rh   r   )	rW   r)   r   r$   r   r   pooling_funcr   r   r   rt   r}   F)r)   r   r$   r   r   r  r   r   c                :   > [         T
U ]  UUUUUUUU	S9  Xpl        g )N)rW   r   r$   r   r   r)   r   r   )r  r   r  )r   rW   r)   r   r$   r   r   r  r   r   r  s             r7   r   FeatureAgglomeration.__init__  s7     	!%/1/ 	 		
 )r9   Tri   c                 p   > [        XSS9n[        TU ]	  UR                  5        U R                  U l        U $ )a	  Fit the hierarchical clustering on the data.

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

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

Returns
-------
self : object
    Returns the transformer.
r   )ensure_min_features)r   r  r   r-   r  _n_features_outr  s      r7   r   FeatureAgglomeration.fit  s4    " $q9QSS#//r9   c                     [         e)zAFit and return the result of each sample's clustering assignment.)AttributeError)r   s    r7   r   FeatureAgglomeration.fit_predict2  s
     r9   )r$  r  r  r   )r  r  r  r  r  r   r   r   r  r   r   r  r   r   r   r   r   r  r  rE   meanr   r   r   propertyr  r  r  r  s   @r7   r  r  _  s   Pf  !T&A4Hs>*m_<=
 
7+T2%$G(&2I>s>#6#6#89:;!
'afEtL'[$D " )  WW) )2 5 6*  r9   r  )NNr   rt   F);r  r2   heapqr   r   r   r   numbersr   r   numpyrE   scipyr	   rC   r
   baser   r   r   r   metricsr   metrics._dist_metricsr   metrics.pairwiser   r   utilsr   utils._fast_dictr   utils._param_validationr   r   r   r   utils.graphr   utils.validationr   r    r   rP   _feature_agglomerationr   r8   rc   r   r   r   r   r   r  r   r   r   r   r9   r7   <module>r;     s     9 9 "   5  % 4 ?  +  4 : 2 :I0X5@x ^=!T&A4H%;	 #' "&$ gBgBZ Q>j)
)
)
 		,dQ)lM Q)h
V#%;=TVr9   