
    -i+f                    (   S r SSKrSSKrSSKrSSKJr  SSKJrJr  SSK	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  SSKJr  SSKJrJrJr  SSKJrJrJrJ r J!r!J"r"J#r#  SSK$J%r%  SSK&J'r'  SSK(J)r)  SSK*J+r+J,r,J-r-J.r.J/r/J0r0  SSK1J2r2  SSK3J4r4J5r5  SSK6J7r7J8r8  SSK9J:r:J;r;  SSK<J=r=J>r>  SSK?J@r@  SSKAJBrBJCrC  S rDSSSSSSSS .S! jrES" rF\0" S#S$// S%QS#S/S&/S#S/S'.SS(9 StSSSS).S* jj5       rGSuS+ jrH\0" S#/S#S/S&/\-" SS,9/S&/S-.SS(9 StS\
R                  SS..S/ jj5       rJSvS0 jrKS1 rLS2 rM/ S3QrN\8\7" S45      :  a  \NS5/-  rN\8\7" S65      :  a  \NS7/-  rN\8\7" S85      :  a  \NS9/-  rNS:/rO\0" S#S$/S#S$/\." \SS15      /\/" \P" \N5      R                  \@R                  " 5       5      5      \S/\TS/S;.SS(9SS<SS=.S> j5       rU\0" S#S$/S#S$/\." \SS15      /\/" \P" \N5      R                  \@R                  " 5       5      5      \S/\TS/S;.SS(9SS<SS=.S? j5       rV\0" S#S$// S%QS@.SS(9StSA j5       rW\0" S#S$// S%QS@.SS(9StSB j5       rX\0" S#S$// S%QS@.SS(9StSC j5       rY\0" S#S$/S#S$/S@.SS(9SD 5       rZ\0" S#S$/S#S$/S@.SS(9SE 5       r[\0" S#S$/S#S$/S@.SS(9SF 5       r\\\\Z\Z\[\[\[SG.r]\0" S#/S#/\/" \P" \]5      5      \S/SH.SS(9S<SI.SJ j5       r^\0" S#S$// S%QS&/SK.SS(9SwSL j5       r_\0" S#S$// S%Q\," \SSSMSN9/\," \SSSMSN9S\+" \
R                  5      /\," \SSSOSN9/SP.SS(9SxSQ j5       ra\0" S#S$// S%Q\," \SSSMSN9S\+" \
R                  5      /\," \SSSOSN9/SR.SS(9SySS j5       rb\0" S#S$// S%Q\," \SSSMSN9S\+" \
R                  5      /ST.SS(9SzSU j5       rc\0" S#S$// S%Q\," \SSSOSN9\+" \
R                  5      S/ST.SS(9SzSV j5       rd\0" S#S$// S%QS&/SK.SS(9SwSW j5       re\0" S#/S#S/S@.SS(9StSX j5       rf\0" S#/S#S/\," \SSSOSN9\+" \
R                  5      /ST.SS(9S{SY j5       rg\X\Y\G\W\G\X\XS\JSZ.	rhS[ riS\ rjS] rkS|S^ jrlS_ rmStS` jrn\0" S#S$// S%Q\SS/\/" Sa1R                  \N5      5      \S/\S/\," \SSSMSN9S/Sb.SS(9 StSS<SSSc.Sd jj5       ro\0" S#S$// S%Q\/" \P" \N5      Sa1-  5      \S/\S/S&\/" Se15      \+" \/" S15      5      /S&\/" Se15      \+" S5      /Sf.SS(9  S}SSSSg.Sh jj5       rp/ SiQrq\8\7" S45      :  a  \qS5/-  rq\8\7" S65      :  a  \qS7/-  rq\8\7" S85      :  a  \qS9/-  rq\f\g\_\a\a\c\d\b\eSj.	rrSk rsSl\t" Sm/5      SlSl\t" / SnQ5      \t" / SnQ5      \t" Sm/5      \t" Sm/5      \t" SmSo/5      Sp.	ru\0" S#S$// S%Q\/" \P" \r5      Sa1-  5      \S/S&/\S/Sq.SS(9 S~SSSr.Ss jj5       rvg)z?Metrics for pairwise distances and affinity of sets of samples.    N)partial)IntegralReal)effective_n_jobs)
csr_matrixissparse)distance   )config_context)DataConversionWarning)	normalize)check_arraygen_batchesgen_even_slices)_fill_or_add_to_diagonal_find_matching_floating_dtype_is_numpy_namespace_max_precision_float_dtype_modify_in_place_if_numpyget_namespaceget_namespace_and_device)get_chunk_n_rows)	_get_mask)is_scalar_nan)HiddenIntervalMissingValuesOptions
StrOptionsvalidate_params)_deprecate_force_all_finite)	row_normssafe_sparse_dot)parse_versionsp_base_version)Paralleldelayed)_num_samplescheck_non_negative   )ArgKmin)_chi2_kernel_fast_sparse_manhattanc                    [        U 5      (       d5  [        U [        R                  5      (       d  [        R                  " U 5      n Uc  U R
                  nO^[        U5      (       dB  [        U[        R                  5      (       d#  [        R                  " U5      nUR
                  nOUR
                  nU R
                  Us=:X  a  [        R                  :X  a  O  O[        R                  nO[        nXU4$ )ze
1. If dtype of X and Y is float32, then dtype float32 is returned.
2. Else dtype float is returned.
)r   
isinstancenpndarrayasarraydtypefloat32float)XYY_dtyper3   s       K/var/www/html/venv/lib/python3.13/site-packages/sklearn/metrics/pairwise.py_return_float_dtyper:   3   s    
 A;;z!RZZ88JJqMy''a[[Arzz!:!:JJqM''''ww''RZZ'

;    Finfer_floatcsr
deprecatedT)precomputedr3   accept_sparseforce_all_finiteensure_all_finite	ensure_2dcopyc          
         [        XV5      n[        X5      u  p[        [        U 5      [        U5      /5      (       d  [	        U	5      (       a  [        X5      u  pnO
[        XU	S9nSnUS:X  a  UnXL d  Uc  [        U UUUUUUS9=pO[        U UUUUUUS9n [        UUUUUUUS9nU(       a\  U R                  S   UR                  S   :w  a8  [        SU R                  S   U R                  S   UR                  S   4-  5      e X4$ U(       aJ  U R                  S   UR                  S   :w  a*  [        SU R                  S   UR                  S   4-  5      eX4$ )	a<  Set X and Y appropriately and checks inputs.

If Y is None, it is set as a pointer to X (i.e. not a copy).
If Y is given, this does not happen.
All distance metrics should use this function first to assert that the
given parameters are correct and safe to use.

Specifically, this function first ensures that both X and Y are arrays,
then checks that they are at least two dimensional while ensuring that
their elements are floats (or dtype if provided). Finally, the function
checks that the size of the second dimension of the two arrays is equal, or
the equivalent check for a precomputed distance matrix.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)

precomputed : bool, default=False
    True if X is to be treated as precomputed distances to the samples in
    Y.

dtype : str, type, list of type or None default="infer_float"
    Data type required for X and Y. If "infer_float", the dtype will be an
    appropriate float type selected by _return_float_dtype. If None, the
    dtype of the input is preserved.

    .. versionadded:: 0.18

accept_sparse : str, bool or list/tuple of str, default='csr'
    String[s] representing allowed sparse matrix formats, such as 'csc',
    'csr', etc. If the input is sparse but not in the allowed format,
    it will be converted to the first listed format. True allows the input
    to be any format. False means that a sparse matrix input will
    raise an error.

force_all_finite : bool or 'allow-nan', default=True
    Whether to raise an error on np.inf, np.nan, pd.NA in array. The
    possibilities are:

    - True: Force all values of array to be finite.
    - False: accepts np.inf, np.nan, pd.NA in array.
    - 'allow-nan': accepts only np.nan and pd.NA values in array. Values
      cannot be infinite.

    .. versionadded:: 0.22
       ``force_all_finite`` accepts the string ``'allow-nan'``.

    .. versionchanged:: 0.23
       Accepts `pd.NA` and converts it into `np.nan`.

    .. deprecated:: 1.6
       `force_all_finite` was renamed to `ensure_all_finite` and will be removed
       in 1.8.

ensure_all_finite : bool or 'allow-nan', default=True
    Whether to raise an error on np.inf, np.nan, pd.NA in array. The
    possibilities are:

    - True: Force all values of array to be finite.
    - False: accepts np.inf, np.nan, pd.NA in array.
    - 'allow-nan': accepts only np.nan and pd.NA values in array. Values
      cannot be infinite.

    .. versionadded:: 1.6
       `force_all_finite` was renamed to `ensure_all_finite`.

ensure_2d : bool, default=True
    Whether to raise an error when the input arrays are not 2-dimensional. Setting
    this to `False` is necessary when using a custom metric with certain
    non-numerical inputs (e.g. a list of strings).

    .. versionadded:: 1.5

copy : bool, default=False
    Whether a forced copy will be triggered. If copy=False, a copy might
    be triggered by a conversion.

    .. versionadded:: 0.22

Returns
-------
safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    An array equal to X, guaranteed to be a numpy array.

safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
    An array equal to Y if Y was not None, guaranteed to be a numpy array.
    If Y was None, safe_Y will be a pointer to X.
xpcheck_pairwise_arraysr<   )r@   r3   rD   rB   	estimatorrC   r*   r   zVPrecomputed metric requires shape (n_queries, n_indexed). Got (%d, %d) for %d indexed.zTIncompatible dimension for X and Y matrices: X.shape[1] == %d while Y.shape[1] == %d)
r!   r   anyr   r   r:   r   r   shape
ValueError)r6   r7   r?   r3   r@   rA   rB   rC   rD   rG   _dtype_floatrI   s                r9   rH   rH   K   s   L 44DX!EB
HQK!%&&*=b*A*A/5k3AR@'Iv'/
 	
A '/
 '/
 771:#"%&WWQZQWWQZ$HI  $ 4K 
qwwqzQWWQZ/ 69:QWWQZ8PQ
 	

 4Kr;   c                     [        X5      u  pU R                  UR                  :w  a(  [        SU R                  < SUR                  < S35      eX4$ )a  Set X and Y appropriately and checks inputs for paired distances.

All paired distance metrics should use this function first to assert that
the given parameters are correct and safe to use.

Specifically, this function first ensures that both X and Y are arrays,
then checks that they are at least two dimensional while ensuring that
their elements are floats. Finally, the function checks that the size
of the dimensions of the two arrays are equal.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)

Returns
-------
safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    An array equal to X, guaranteed to be a numpy array.

safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
    An array equal to Y if Y was not None, guaranteed to be a numpy array.
    If Y was None, safe_Y will be a pointer to X.
z8X and Y should be of same shape. They were respectively z and z long.)rH   rK   rL   r6   r7   s     r9   check_paired_arraysrQ      sH    4 !&DAww!''ww!
 	
 4Kr;   
array-likesparse matrix)rR   rS   Nboolean)r6   r7   Y_norm_squaredsquaredX_norm_squared)prefer_skip_nested_validation)rU   rV   rW   c                   [        X5      u  pV[        X5      u  pUb  [        USS9nUR                  nUR                  U R                  S   4:X  a  UR	                  US5      nUR                  SU R                  S   4:X  a  UR
                  nUR                  U R                  S   S4:w  a  [        SU R                   SU S35      eUb  [        USS9nUR                  nUR                  UR                  S   4:X  a  UR	                  US	5      nUR                  UR                  S   S4:X  a  UR
                  nUR                  SUR                  S   4:w  a  [        S
UR                   SU S35      e[        XXBU5      $ )a	  
Compute the distance matrix between each pair from a feature array X and Y.

For efficiency reasons, the euclidean distance between a pair of row
vector x and y is computed as::

    dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y))

This formulation has two advantages over other ways of computing distances.
First, it is computationally efficient when dealing with sparse data.
Second, if one argument varies but the other remains unchanged, then
`dot(x, x)` and/or `dot(y, y)` can be pre-computed.

However, this is not the most precise way of doing this computation,
because this equation potentially suffers from "catastrophic cancellation".
Also, the distance matrix returned by this function may not be exactly
symmetric as required by, e.g., :mod:`scipy.spatial.distance` functions.

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    An array where each row is a sample and each column is a feature.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features),             default=None
    An array where each row is a sample and each column is a feature.
    If `None`, method uses `Y=X`.

Y_norm_squared : array-like of shape (n_samples_Y,) or (n_samples_Y, 1)             or (1, n_samples_Y), default=None
    Pre-computed dot-products of vectors in Y (e.g.,
    ``(Y**2).sum(axis=1)``)
    May be ignored in some cases, see the note below.

squared : bool, default=False
    Return squared Euclidean distances.

X_norm_squared : array-like of shape (n_samples_X,) or (n_samples_X, 1)             or (1, n_samples_X), default=None
    Pre-computed dot-products of vectors in X (e.g.,
    ``(X**2).sum(axis=1)``)
    May be ignored in some cases, see the note below.

Returns
-------
distances : ndarray of shape (n_samples_X, n_samples_Y)
    Returns the distances between the row vectors of `X`
    and the row vectors of `Y`.

See Also
--------
paired_distances : Distances between pairs of elements of X and Y.

Notes
-----
To achieve a better accuracy, `X_norm_squared` and `Y_norm_squared` may be
unused if they are passed as `np.float32`.

Examples
--------
>>> from sklearn.metrics.pairwise import euclidean_distances
>>> X = [[0, 1], [1, 1]]
>>> # distance between rows of X
>>> euclidean_distances(X, X)
array([[0., 1.],
       [1., 0.]])
>>> # get distance to origin
>>> euclidean_distances(X, [[0, 0]])
array([[1.        ],
       [1.41421356]])
F)rC   r   r*   r*   z'Incompatible dimensions for X of shape z and X_norm_squared of shape .r*   r[   z'Incompatible dimensions for Y of shape z and Y_norm_squared of shape )r   rH   r   rK   reshapeTrL   _euclidean_distances)r6   r7   rU   rV   rW   rG   rM   original_shapes           r9   euclidean_distancesrb     s   l !EB &DA!$^uE'--AGGAJ=0ZZ@NAqwwqz?2+--NAGGAJ?29!'' C++9*:!= 
 !$^uE'--AGGAJ=0ZZ@NAGGAJ?2+--NAqwwqz?29!'' C++9*:!= 
  ngNNr;   c                 >   [        X5      u  pVnUb-  UR                  UR                  :w  a  UR                  US5      nO.U R                  UR                  :w  a  [	        U SS9SS2S4   nOSnXL a  Uc  SOUR
                  n	O^Ub-  UR                  UR                  :w  a  UR                  US5      n	O.UR                  UR                  :w  a  [	        USS9SSS24   n	OSn	U R                  UR                  :X  d  UR                  UR                  :X  a  [        XX5      n
OS[        XR
                  SS9-  n
X-  n
X-  n
UR                  SXzR                  S	9n[        XUR                  XU
S
9n
XL a  [        U
SUSS9  U(       a  U
$ [        XUR                  XS
9n
U
$ )a  Computational part of euclidean_distances

Assumes inputs are already checked.

If norms are passed as float32, they are unused. If arrays are passed as
float32, norms needs to be recomputed on upcast chunks.
TODO: use a float64 accumulator in row_norms to avoid the latter.
NrZ   TrV   r]   dense_outputr   )devicer3   outF)rG   	add_value)r   r3   r4   r^   r"   r_   _euclidean_distances_upcastr#   r2   r   maximumr   sqrt)r6   r7   rW   rU   rV   rG   rM   device_XXYY	distancesxp_zeros               r9   r`   r`     sy    .a3NB7!n&:&:bjj&HZZ0	
BJJ	q$'40vZTRTT%.*>*>"***LNG4BWW

"1d+D!G4BBww"**2:: 5 0q=	 CCdCC			jj7//jBG)
JJ		I 	v A"F)"ggyPIr;   )numeric_only)r6   r7   rV   missing_valuesrD   )rV   ru   rD   c                   [        U5      (       a  SOSn[        XSXTS9u  p[        X5      nXL a  UO
[        X5      nSX'   SX'   [        XSS9nX -  n	X-  n
U[        R
                  " XR                  5      -  nU[        R
                  " XjR                  5      -  n[        R                  " USSUS9  XL a  [        R                  " US	5        S
U-
  nXL a  UOU) n[        R
                  " XR                  5      n[        R                  XS:H  '   [        R                  " S
XS9  X-  nXR                  S
   -  nU(       d  [        R                  " XS9  U$ )a	  Calculate the euclidean distances in the presence of missing values.

Compute the euclidean distance between each pair of samples in X and Y,
where Y=X is assumed if Y=None. When calculating the distance between a
pair of samples, this formulation ignores feature coordinates with a
missing value in either sample and scales up the weight of the remaining
coordinates:

.. code-block:: text

    dist(x,y) = sqrt(weight * sq. distance from present coordinates)

where:

.. code-block:: text

    weight = Total # of coordinates / # of present coordinates

For example, the distance between ``[3, na, na, 6]`` and ``[1, na, 4, 5]`` is:

.. math::
    \sqrt{\frac{4}{2}((3-1)^2 + (6-5)^2)}

If all the coordinates are missing or if there are no common present
coordinates then NaN is returned for that pair.

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

.. versionadded:: 0.22

Parameters
----------
X : array-like of shape (n_samples_X, n_features)
    An array where each row is a sample and each column is a feature.

Y : array-like of shape (n_samples_Y, n_features), default=None
    An array where each row is a sample and each column is a feature.
    If `None`, method uses `Y=X`.

squared : bool, default=False
    Return squared Euclidean distances.

missing_values : np.nan, float or int, default=np.nan
    Representation of missing value.

copy : bool, default=True
    Make and use a deep copy of X and Y (if Y exists).

Returns
-------
distances : ndarray of shape (n_samples_X, n_samples_Y)
    Returns the distances between the row vectors of `X`
    and the row vectors of `Y`.

See Also
--------
paired_distances : Distances between pairs of elements of X and Y.

References
----------
* John K. Dixon, "Pattern Recognition with Partly Missing Data",
  IEEE Transactions on Systems, Man, and Cybernetics, Volume: 9, Issue:
  10, pp. 617 - 621, Oct. 1979.
  http://ieeexplore.ieee.org/abstract/document/4310090/

Examples
--------
>>> from sklearn.metrics.pairwise import nan_euclidean_distances
>>> nan = float("NaN")
>>> X = [[0, 1], [1, nan]]
>>> nan_euclidean_distances(X, X) # distance between rows of X
array([[0.        , 1.41421356],
       [1.41421356, 0.        ]])

>>> # get distance to origin
>>> nan_euclidean_distances(X, [[0, 0]])
array([[1.        ],
       [1.41421356]])
	allow-nanTF)r@   rB   rD   r   rd   Nri           r*   )r   rH   r   rb   r0   dotr_   clipfill_diagonalnanrm   rK   rn   )r6   r7   rV   ru   rD   rB   	missing_X	missing_Yrr   rp   rq   	present_X	present_Ypresent_counts                 r9   nan_euclidean_distancesr     s@   z (5^'D'D$ 	E5FDA !,I V	1)EI ALAL#A$7I 
B	
BKK((I	44((IGGIq$I.v 	C(IIV	)IFF9kk2M$&FFIq !JJq-3II
	)r;   c           	         [        X5      u  pVnU R                  S   nUR                  S   n	U R                  S   n
UR                  X4UR                  US9nUc  [	        U 5      (       a-  U R
                  [        R                  " U R                  5      -  OSn[	        U5      (       a-  UR
                  [        R                  " UR                  5      -  OSn[        X-  X-  -   U
-  X-  U-  U	-  -   S-  S5      nX-   U
-  nU* [        R                  " US-  SU-  -   5      -   S-  n[        [        U5      S5      n[        X5      n[        XWS	9n[        U5       H  u  nnUR                  U USS24   U5      nUc  [!        US
S9SS2S4   nOUU   n[        X5      n[        U5       H  u  nnXL a  UU:  a  UUU4   R"                  nOYUR                  UUSS24   U5      nUc  [!        US
S9SSS24   nO	USS2U4   nS[%        UUR"                  S
S9-  nUU-  nUU-  nUR                  UUR                  SS9UUU4'   M     M     U$ )zEuclidean distances between X and Y.

Assumes X and Y have float32 dtype.
Assumes XX and YY have float64 dtype or are None.

X and Y are upcast to float64 by chunks, which size is chosen to limit
memory increase by approximately 10% (at least 10MiB).
r   r*   r3   rh   N
   i   r
      )rG   rh   Trd   re   rf   FrD   )r   rK   emptyr4   r   nnzr0   prodmaxmathrn   intr   r   	enumerateastyper"   r_   r#   )r6   rp   r7   rq   
batch_sizerG   rM   ro   n_samples_Xn_samples_Y
n_featuresrr   	x_density	y_densitymaxmemtmp	x_batchesxp_max_floatix_sliceX_chunkXX_chunk	y_batchesjy_slicedY_chunkYY_chunks                               r9   rl   rl   F  sc    .a3NB7''!*K''!*KJ+32::gVI08AEEBGGAGG,,	08AEEBGGAGG,,	 (9+BBjP*Y6DF 	
 
 $
2dTYYsAvF
':;;q@
Z!,
K4I-DL	*
7))AgqjM<8: $74@H'{H8	#I.JAwv!a% gw./11 ))AgqjM<@:($?aHH!!W*~H'))$OOXX*,))Arzz)*NIgw&'# / +8 r;   c                 v    U R                  SS9nU [        R                  " U R                  S   5      U4   nX#4$ )Nr*   axisr   )argminr0   arangerK   )diststartindicesvaluess       r9   _argmin_min_reducer     s<     kkqk!G"))DJJqM*G34F?r;   c                      U R                  SS9$ )Nr*   r   )r   )r   r   s     r9   _argmin_reducer     s     ;;A;r;   )	euclideanl2l1	manhattan	cityblock
braycurtiscanberra	chebyshevcorrelationcosinedicehammingjaccardmahalanobismatching	minkowskirogerstanimoto
russellrao
seuclideansokalsneathsqeuclideanyule
wminkowskinan_euclidean	haversinez1.17sokalmichenerz1.11	kulsinskiz1.9r   r   )r6   r7   r   metricmetric_kwargsr   )r   r   r   c          
         US:X  a  SOSn[        XUS9u  pUS:X  a  XpUc  0 n[        R                  " XU5      (       a`  UR                  SS5      (       a
  US	:X  a  S
n0 n[        R                  " U USUUSSS9u  pgUR                  5       nUR                  5       nXv4$ [        SS9   [        [        X4[        US.UD66 u  pvSSS5        [        R                  " W5      n[        R                  " W5      nXv4$ ! , (       d  f       N== f)a  Compute minimum distances between one point and a set of points.

This function computes for each row in X, the index of the row of Y which
is closest (according to the specified distance). The minimal distances are
also returned.

This is mostly equivalent to calling::

    (pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis),
     pairwise_distances(X, Y=Y, metric=metric).min(axis=axis))

but uses much less memory, and is faster for large arrays.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    Array containing points.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
    Array containing points.

axis : int, default=1
    Axis along which the argmin and distances are to be computed.

metric : str or callable, default='euclidean'
    Metric to use for distance computation. Any metric from scikit-learn
    or :mod:`scipy.spatial.distance` can be used.

    If metric is a callable function, it is called on each
    pair of instances (rows) and the resulting value recorded. The callable
    should take two arrays as input and return one value indicating the
    distance between them. This works for Scipy's metrics, but is less
    efficient than passing the metric name as a string.

    Distance matrices are not supported.

    Valid values for metric are:

    - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
      'manhattan', 'nan_euclidean']

    - from :mod:`scipy.spatial.distance`: ['braycurtis', 'canberra', 'chebyshev',
      'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
      'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao',
      'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
      'yule']

    See the documentation for :mod:`scipy.spatial.distance` for details on these
    metrics.

    .. note::
       `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11.

    .. note::
       `'matching'` has been removed in SciPy 1.9 (use `'hamming'` instead).

metric_kwargs : dict, default=None
    Keyword arguments to pass to specified metric function.

Returns
-------
argmin : ndarray
    Y[argmin[i], :] is the row in Y that is closest to X[i, :].

distances : ndarray
    The array of minimum distances. `distances[i]` is the distance between
    the i-th row in X and the argmin[i]-th row in Y.

See Also
--------
pairwise_distances : Distances between every pair of samples of X and Y.
pairwise_distances_argmin : Same as `pairwise_distances_argmin_min` but only
    returns the argmins.

Examples
--------
>>> from sklearn.metrics.pairwise import pairwise_distances_argmin_min
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> argmin, distances = pairwise_distances_argmin_min(X, Y)
>>> argmin
array([0, 1])
>>> distances
array([1., 1.])
r   rw   TrB   r   NrV   Fr   r   r*   autor6   r7   kr   r   strategyreturn_distanceassume_finitereduce_funcr   )rH   r+   is_usable_forgetcomputeflattenr   zippairwise_distances_chunkedr   r0   concatenate)r6   r7   r   r   r   rB   r   r   s           r9   pairwise_distances_argmin_minr     s#   J (.'@d 9JKDAqy1Q6** Y..6[3H"FM!//' 
 !//#( ? $/!+&8KXOG 0 ..)'? 0/s   )C<<
D
c                   US:X  a  SOSn[        XUS9u  pUS:X  a  XpUc  0 n[        R                  " XU5      (       aM  UR                  SS5      (       a
  US	:X  a  S
n0 n[        R                  " U USUUSSS9nUR                  5       nU$ [        SS9   [        R                  " [        [        X4[        US.UD65      5      nSSS5        U$ ! , (       d  f       W$ = f)a
  Compute minimum distances between one point and a set of points.

This function computes for each row in X, the index of the row of Y which
is closest (according to the specified distance).

This is mostly equivalent to calling::

    pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis)

but uses much less memory, and is faster for large arrays.

This function works with dense 2D arrays only.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    Array containing points.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
    Arrays containing points.

axis : int, default=1
    Axis along which the argmin and distances are to be computed.

metric : str or callable, default="euclidean"
    Metric to use for distance computation. Any metric from scikit-learn
    or :mod:`scipy.spatial.distance` can be used.

    If metric is a callable function, it is called on each
    pair of instances (rows) and the resulting value recorded. The callable
    should take two arrays as input and return one value indicating the
    distance between them. This works for Scipy's metrics, but is less
    efficient than passing the metric name as a string.

    Distance matrices are not supported.

    Valid values for metric are:

    - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
      'manhattan', 'nan_euclidean']

    - from :mod:`scipy.spatial.distance`: ['braycurtis', 'canberra', 'chebyshev',
      'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
      'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao',
      'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
      'yule']

    See the documentation for :mod:`scipy.spatial.distance` for details on these
    metrics.

    .. note::
       `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11.

    .. note::
       `'matching'` has been removed in SciPy 1.9 (use `'hamming'` instead).

metric_kwargs : dict, default=None
    Keyword arguments to pass to specified metric function.

Returns
-------
argmin : numpy.ndarray
    Y[argmin[i], :] is the row in Y that is closest to X[i, :].

See Also
--------
pairwise_distances : Distances between every pair of samples of X and Y.
pairwise_distances_argmin_min : Same as `pairwise_distances_argmin` but also
    returns the distances.

Examples
--------
>>> from sklearn.metrics.pairwise import pairwise_distances_argmin
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> pairwise_distances_argmin(X, Y)
array([0, 1])
r   rw   Tr   r   NrV   Fr   r   r*   r   r   r   r   )rH   r+   r   r   r   r   r   r0   r   listr   r   )r6   r7   r   r   r   rB   r   s          r9   pairwise_distances_argminr   ^  s   x (.'@d 9JKDAqy1Q6** Y..6[3H"FM//'!
 //#, N $/nn /*8KXG 0 N 0/ Ns   1C
C rP   c                 N    SSK Jn  UR                  S5      R                  X5      $ )a  Compute the Haversine distance between samples in X and Y.

The Haversine (or great circle) distance is the angular distance between
two points on the surface of a sphere. The first coordinate of each point
is assumed to be the latitude, the second is the longitude, given
in radians. The dimension of the data must be 2.

.. math::
   D(x, y) = 2\arcsin[\sqrt{\sin^2((x_{lat} - y_{lat}) / 2)
                            + \cos(x_{lat})\cos(y_{lat})\
                            sin^2((x_{lon} - y_{lon}) / 2)}]

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, 2)
    A feature array.

Y : {array-like, sparse matrix} of shape (n_samples_Y, 2), default=None
    An optional second feature array. If `None`, uses `Y=X`.

Returns
-------
distances : ndarray of shape (n_samples_X, n_samples_Y)
    The distance matrix.

Notes
-----
As the Earth is nearly spherical, the haversine formula provides a good
approximation of the distance between two points of the Earth surface, with
a less than 1% error on average.

Examples
--------
We want to calculate the distance between the Ezeiza Airport
(Buenos Aires, Argentina) and the Charles de Gaulle Airport (Paris,
France).

>>> from sklearn.metrics.pairwise import haversine_distances
>>> from math import radians
>>> bsas = [-34.83333, -58.5166646]
>>> paris = [49.0083899664, 2.53844117956]
>>> bsas_in_radians = [radians(_) for _ in bsas]
>>> paris_in_radians = [radians(_) for _ in paris]
>>> result = haversine_distances([bsas_in_radians, paris_in_radians])
>>> result * 6371000/1000  # multiply by Earth radius to get kilometers
array([[    0.        , 11099.54035582],
       [11099.54035582,     0.        ]])
r
   )DistanceMetricr   )metricsr   
get_metricpairwise)r6   r7   r   s      r9   haversine_distancesr     s$    j )$$[1::1@@r;   c           	         [        X5      u  p[        U 5      (       d  [        U5      (       a  [        U SS9n [        USS9nU R                  5         UR                  5         [        R
                  " U R                  S   UR                  S   45      n[        U R                  U R                  U R                  UR                  UR                  UR                  U5        U$ [        R                  " XS5      $ )a  Compute the L1 distances between the vectors in X and Y.

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    An array where each row is a sample and each column is a feature.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None
    An array where each row is a sample and each column is a feature.
    If `None`, method uses `Y=X`.

Returns
-------
distances : ndarray of shape (n_samples_X, n_samples_Y)
    Pairwise L1 distances.

Notes
-----
When X and/or Y are CSR sparse matrices and they are not already
in canonical format, this function modifies them in-place to
make them canonical.

Examples
--------
>>> from sklearn.metrics.pairwise import manhattan_distances
>>> manhattan_distances([[3]], [[3]])
array([[0.]])
>>> manhattan_distances([[3]], [[2]])
array([[1.]])
>>> manhattan_distances([[2]], [[3]])
array([[1.]])
>>> manhattan_distances([[1, 2], [3, 4]],         [[1, 2], [0, 3]])
array([[0., 2.],
       [4., 4.]])
Fr   r   r   )rH   r   r   sum_duplicatesr0   zerosrK   r-   datar   indptrr	   cdist)r6   r7   Ds      r9   manhattan_distancesr   &  s    \ !&DA{{hqkkqu%qu%		HHaggaj!''!*-.!&&!))QXXqvvqyy!((TUV>>!,,r;   c                     [        X5      u  p#[        X5      nUS-  nUS-  nUR                  USS5      nXL d  Uc  [        USUSS9  U$ )ag  Compute cosine distance between samples in X and Y.

Cosine distance is defined as 1.0 minus the cosine similarity.

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    Matrix `X`.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features),             default=None
    Matrix `Y`.

Returns
-------
distances : ndarray of shape (n_samples_X, n_samples_Y)
    Returns the cosine distance between samples in X and Y.

See Also
--------
cosine_similarity : Compute cosine similarity between samples in X and Y.
scipy.spatial.distance.cosine : Dense matrices only.

Examples
--------
>>> from sklearn.metrics.pairwise import cosine_distances
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> cosine_distances(X, Y)
array([[1.   , 1.   ],
       [0.422, 0.183]])
r[   r*   rx   g       @F)rk   )r   cosine_similarityrz   r   )r6   r7   rG   rM   Ss        r9   cosine_distancesr   b  s_    T !EB 	!AGAFA
3Av 	!Cu=Hr;   c                 6    [        X5      u  p[        X-
  5      $ )a  Compute the paired euclidean distances between X and Y.

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    Input array/matrix X.

Y : {array-like, sparse matrix} of shape (n_samples, n_features)
    Input array/matrix Y.

Returns
-------
distances : ndarray of shape (n_samples,)
    Output array/matrix containing the calculated paired euclidean
    distances.

Examples
--------
>>> from sklearn.metrics.pairwise import paired_euclidean_distances
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> paired_euclidean_distances(X, Y)
array([1., 1.])
)rQ   r"   rP   s     r9   paired_euclidean_distancesr     s    > q$DAQUr;   c                 B   [        X5      u  pX-
  n[        U5      (       a\  [        R                  " UR                  5      Ul        [        R
                  " [        R                  " UR                  SS95      5      $ [        R                  " U5      R                  SS9$ )a  Compute the paired L1 distances between X and Y.

Distances are calculated between (X[0], Y[0]), (X[1], Y[1]), ...,
(X[n_samples], Y[n_samples]).

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    An array-like where each row is a sample and each column is a feature.

Y : {array-like, sparse matrix} of shape (n_samples, n_features)
    An array-like where each row is a sample and each column is a feature.

Returns
-------
distances : ndarray of shape (n_samples,)
    L1 paired distances between the row vectors of `X`
    and the row vectors of `Y`.

Examples
--------
>>> from sklearn.metrics.pairwise import paired_manhattan_distances
>>> import numpy as np
>>> X = np.array([[1, 1, 0], [0, 1, 0], [0, 0, 1]])
>>> Y = np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]])
>>> paired_manhattan_distances(X, Y)
array([1., 2., 1.])
r*   r   r[   )rQ   r   r0   absr   squeezearraysum)r6   r7   diffs      r9   paired_manhattan_distancesr     st    F q$DA5D~~FF499%	zz"((4888#3455vvd|R((r;   c                 `    [        X5      u  pS[        [        U 5      [        U5      -
  SS9-  $ )a  
Compute the paired cosine distances between X and Y.

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    An array where each row is a sample and each column is a feature.

Y : {array-like, sparse matrix} of shape (n_samples, n_features)
    An array where each row is a sample and each column is a feature.

Returns
-------
distances : ndarray of shape (n_samples,)
    Returns the distances between the row vectors of `X`
    and the row vectors of `Y`, where `distances[i]` is the
    distance between `X[i]` and `Y[i]`.

Notes
-----
The cosine distance is equivalent to the half the squared
euclidean distance if each sample is normalized to unit norm.

Examples
--------
>>> from sklearn.metrics.pairwise import paired_cosine_distances
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> paired_cosine_distances(X, Y)
array([0.5       , 0.184])
g      ?Trd   )rQ   r"   r   rP   s     r9   paired_cosine_distancesr     s0    L q$DA9Q<)A,6EEEr;   )r   r   r   r   r   r   )r6   r7   r   )r   c                
   U[         ;   a  [         U   nU" X5      $ [        U5      (       aX  [        X5      u  p[        R                  " [        U 5      5      n[        [        U 5      5       H  nU" X   X   5      XV'   M     U$ g)aI  
Compute the paired distances between X and Y.

Compute the distances between (X[0], Y[0]), (X[1], Y[1]), etc...

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

Parameters
----------
X : ndarray of shape (n_samples, n_features)
    Array 1 for distance computation.

Y : ndarray of shape (n_samples, n_features)
    Array 2 for distance computation.

metric : str or callable, default="euclidean"
    The metric to use when calculating distance between instances in a
    feature array. If metric is a string, it must be one of the options
    specified in PAIRED_DISTANCES, including "euclidean",
    "manhattan", or "cosine".
    Alternatively, if metric is a callable function, it is called on each
    pair of instances (rows) and the resulting value recorded. The callable
    should take two arrays from `X` as input and return a value indicating
    the distance between them.

**kwds : dict
    Unused parameters.

Returns
-------
distances : ndarray of shape (n_samples,)
    Returns the distances between the row vectors of `X`
    and the row vectors of `Y`.

See Also
--------
sklearn.metrics.pairwise_distances : Computes the distance between every pair of
    samples.

Examples
--------
>>> from sklearn.metrics.pairwise import paired_distances
>>> X = [[0, 1], [1, 1]]
>>> Y = [[0, 1], [2, 1]]
>>> paired_distances(X, Y)
array([0., 1.])
N)PAIRED_DISTANCEScallablerQ   r0   r   lenrange)r6   r7   r   kwdsfuncrr   r   s          r9   paired_distancesr    sz    r !!'Az	&		"1(HHSV$	s1vA!!$-IL  
r;   r6   r7   rg   c                 D    [        X5      u  p[        XR                  US9$ )ak  
Compute the linear kernel between X and Y.

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    A feature array.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None
    An optional second feature array. If `None`, uses `Y=X`.

dense_output : bool, default=True
    Whether to return dense output even when the input is sparse. If
    ``False``, the output is sparse if both input arrays are sparse.

    .. versionadded:: 0.20

Returns
-------
kernel : ndarray of shape (n_samples_X, n_samples_Y)
    The Gram matrix of the linear kernel, i.e. `X @ Y.T`.

Examples
--------
>>> from sklearn.metrics.pairwise import linear_kernel
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> linear_kernel(X, Y)
array([[0., 0.],
       [1., 2.]])
rf   )rH   r#   r_   r  s      r9   linear_kernelr
  d  s"    T !&DA1cc==r;   left)closedneither)r6   r7   degreegammacoef0c                     [        X5      u  pUc  SU R                  S   -  n[        XR                  SS9nXS-  nXT-  nXR-  nU$ )a  
Compute the polynomial kernel between X and Y.

.. code-block:: text

    K(X, Y) = (gamma <X, Y> + coef0) ^ degree

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    A feature array.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None
    An optional second feature array. If `None`, uses `Y=X`.

degree : float, default=3
    Kernel degree.

gamma : float, default=None
    Coefficient of the vector inner product. If None, defaults to 1.0 / n_features.

coef0 : float, default=1
    Constant offset added to scaled inner product.

Returns
-------
kernel : ndarray of shape (n_samples_X, n_samples_Y)
    The polynomial kernel.

Examples
--------
>>> from sklearn.metrics.pairwise import polynomial_kernel
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> polynomial_kernel(X, Y, degree=2)
array([[1.     , 1.     ],
       [1.77, 2.77]])
      ?r*   Trf   )rH   rK   r#   r_   )r6   r7   r  r  r  Ks         r9   polynomial_kernelr    sR    n !&DA}aggaj 33T2AJAJALAHr;   )r6   r7   r  r  c                     [        X5      u  pE[        X5      u  pUc  SU R                  S   -  n[        XR                  SS9nXb-  nXc-  n[        XDR                  XfS9nU$ )a  Compute the sigmoid kernel between X and Y.

.. code-block:: text

    K(X, Y) = tanh(gamma <X, Y> + coef0)

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    A feature array.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None
    An optional second feature array. If `None`, uses `Y=X`.

gamma : float, default=None
    Coefficient of the vector inner product. If None, defaults to 1.0 / n_features.

coef0 : float, default=1
    Constant offset added to scaled inner product.

Returns
-------
kernel : ndarray of shape (n_samples_X, n_samples_Y)
    Sigmoid kernel between two arrays.

Examples
--------
>>> from sklearn.metrics.pairwise import sigmoid_kernel
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> sigmoid_kernel(X, Y)
array([[0.76, 0.76],
       [0.87, 0.93]])
r  r*   Trf   ri   )r   rH   rK   r#   r_   r   tanh)r6   r7   r  r  rG   rM   r  s          r9   sigmoid_kernelr    sg    d !EB &DA}aggaj 33T2AJAJA!"ggq8AHr;   )r6   r7   r  c                     [        X5      u  p4[        X5      u  pUc  SU R                  S   -  n[        XSS9nXR* -  n[	        X3R
                  XUS9nU$ )a/  Compute the rbf (gaussian) kernel between X and Y.

.. code-block:: text

    K(x, y) = exp(-gamma ||x-y||^2)

for each pair of rows x in X and y in Y.

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    A feature array.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None
    An optional second feature array. If `None`, uses `Y=X`.

gamma : float, default=None
    If None, defaults to 1.0 / n_features.

Returns
-------
kernel : ndarray of shape (n_samples_X, n_samples_Y)
    The RBF kernel.

Examples
--------
>>> from sklearn.metrics.pairwise import rbf_kernel
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> rbf_kernel(X, Y)
array([[0.71, 0.51],
       [0.51, 0.71]])
r  r*   Trd   ri   )r   rH   rK   rb   r   expr6   r7   r  rG   rM   r  s         r9   
rbf_kernelr    s^    ` !EB &DA}aggaj A$/AKA!"ffa7AHr;   c                     [        X5      u  pUc  SU R                  S   -  nU* [        X5      -  n[        R                  " X35        U$ )a  Compute the laplacian kernel between X and Y.

The laplacian kernel is defined as:

.. code-block:: text

    K(x, y) = exp(-gamma ||x-y||_1)

for each pair of rows x in X and y in Y.
Read more in the :ref:`User Guide <laplacian_kernel>`.

.. versionadded:: 0.17

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    A feature array.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None
    An optional second feature array. If `None`, uses `Y=X`.

gamma : float, default=None
    If None, defaults to 1.0 / n_features. Otherwise it should be strictly positive.

Returns
-------
kernel : ndarray of shape (n_samples_X, n_samples_Y)
    The kernel matrix.

Examples
--------
>>> from sklearn.metrics.pairwise import laplacian_kernel
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> laplacian_kernel(X, Y)
array([[0.71, 0.51],
       [0.51, 0.71]])
r  r*   )rH   rK   r   r0   r  )r6   r7   r  r  s       r9   laplacian_kernelr  O  sJ    f !&DA}aggaj 	$Q**AFF1LHr;   c                 ~    [        X5      u  p[        U SS9nXL a  UnO
[        USS9n[        X4R                  US9nU$ )a  Compute cosine similarity between samples in X and Y.

Cosine similarity, or the cosine kernel, computes similarity as the
normalized dot product of X and Y:

.. code-block:: text

    K(X, Y) = <X, Y> / (||X||*||Y||)

On L2-normalized data, this function is equivalent to linear_kernel.

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
    Input data.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features),             default=None
    Input data. If ``None``, the output will be the pairwise
    similarities between all samples in ``X``.

dense_output : bool, default=True
    Whether to return dense output even when the input is sparse. If
    ``False``, the output is sparse if both input arrays are sparse.

    .. versionadded:: 0.17
       parameter ``dense_output`` for dense output.

Returns
-------
similarities : ndarray or sparse matrix of shape (n_samples_X, n_samples_Y)
    Returns the cosine similarity between samples in X and Y.

Examples
--------
>>> from sklearn.metrics.pairwise import cosine_similarity
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> cosine_similarity(X, Y)
array([[0.   , 0.   ],
       [0.577, 0.816]])
Tr   rf   )rH   r   r#   r_   )r6   r7   rg   X_normalizedY_normalizedr  s         r9   r   r     sH    j !&DAQT*Lv# .nn<PAHr;   c           	         [        X5      u  p#n[        XSS9u  pUR                  U S:  5      (       a  [        S5      eXLa$  UR                  US:  5      (       a  [        S5      e[	        U5      (       aI  [
        R                  " U R                  S   UR                  S   4U R                  S9n[        XU5        U$ [        XUS9nU SS2SSS24   nUSSS2SS24   nXx-
  S	-  * n	Xx-   n
UR                  U
S:H  UR                  SXdS
9U	5      n	UR                  U
S:H  UR                  SXdS
9U
5      n
UR                  X-  S	S9$ )a   Compute the additive chi-squared kernel between observations in X and Y.

The chi-squared kernel is computed between each pair of rows in X and Y.  X
and Y have to be non-negative. This kernel is most commonly applied to
histograms.

The chi-squared kernel is given by:

.. code-block:: text

    k(x, y) = -Sum [(x - y)^2 / (x + y)]

It can be interpreted as a weighted difference per entry.

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

Parameters
----------
X : array-like of shape (n_samples_X, n_features)
    A feature array.

Y : array-like of shape (n_samples_Y, n_features), default=None
    An optional second feature array. If `None`, uses `Y=X`.

Returns
-------
kernel : array-like of shape (n_samples_X, n_samples_Y)
    The kernel matrix.

See Also
--------
chi2_kernel : The exponentiated version of the kernel, which is usually
    preferable.
sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation
    to this kernel.

Notes
-----
As the negative of a distance, this kernel is only conditionally positive
definite.

References
----------
* Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C.
  Local features and kernels for classification of texture and object
  categories: A comprehensive study
  International Journal of Computer Vision 2007
  https://hal.archives-ouvertes.fr/hal-00171412/document

Examples
--------
>>> from sklearn.metrics.pairwise import additive_chi2_kernel
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> additive_chi2_kernel(X, Y)
array([[-1., -2.],
       [-2., -1.]])
F)r@   r   zX contains negative values.zY contains negative values.r3   rF   Nr
   r   r*   r   )r   rH   rJ   rL   r   r0   r   rK   r3   r,   r   wherer2   r   )r6   r7   rG   rM   ro   resultr3   xbybnomdenoms              r9   additive_chi2_kernelr)    s=   ~ .a3NB7 U;DA	vva!e}}677zbffQUmm67721771:qwwqz2!''B!'-ar:q$z]tQz]Qhhuz2::au:#MsS!RZZZ%OQVWvvckv**r;   c                     [        X5      u  p4[        X5      nXR-  n[        U5      (       a  [        R                  " XUS9$ UR	                  U5      $ )a  Compute the exponential chi-squared kernel between X and Y.

The chi-squared kernel is computed between each pair of rows in X and Y.  X
and Y have to be non-negative. This kernel is most commonly applied to
histograms.

The chi-squared kernel is given by:

.. code-block:: text

    k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)])

It can be interpreted as a weighted difference per entry.

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

Parameters
----------
X : array-like of shape (n_samples_X, n_features)
    A feature array.

Y : array-like of shape (n_samples_Y, n_features), default=None
    An optional second feature array. If `None`, uses `Y=X`.

gamma : float, default=1
    Scaling parameter of the chi2 kernel.

Returns
-------
kernel : ndarray of shape (n_samples_X, n_samples_Y)
    The kernel matrix.

See Also
--------
additive_chi2_kernel : The additive version of this kernel.
sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation
    to the additive version of this kernel.

References
----------
* Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C.
  Local features and kernels for classification of texture and object
  categories: A comprehensive study
  International Journal of Computer Vision 2007
  https://hal.archives-ouvertes.fr/hal-00171412/document

Examples
--------
>>> from sklearn.metrics.pairwise import chi2_kernel
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> chi2_kernel(X, Y)
array([[0.368, 0.135],
       [0.135, 0.368]])
ri   )r   r)  r   r0   r  r  s         r9   chi2_kernelr+  "  sJ    @ !EBQ"AJA2vva66!9r;   )	r   r   r   r   r   r   r   r?   r   c                      [         $ )a  Valid metrics for pairwise_distances.

This function simply returns the valid pairwise distance metrics.
It exists to allow for a description of the mapping for
each of the valid strings.

The valid distance metrics, and the function they map to, are:

=============== ========================================
metric          Function
=============== ========================================
'cityblock'     metrics.pairwise.manhattan_distances
'cosine'        metrics.pairwise.cosine_distances
'euclidean'     metrics.pairwise.euclidean_distances
'haversine'     metrics.pairwise.haversine_distances
'l1'            metrics.pairwise.manhattan_distances
'l2'            metrics.pairwise.euclidean_distances
'manhattan'     metrics.pairwise.manhattan_distances
'nan_euclidean' metrics.pairwise.nan_euclidean_distances
=============== ========================================

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

Returns
-------
distance_metrics : dict
    Returns valid metrics for pairwise_distances.
)PAIRWISE_DISTANCE_FUNCTIONS r;   r9   distance_metricsr/  z  s
    : '&r;   c                 "    U " U0 UD6USS2U4'   g)z/Write in-place to a slice of a distance matrix.Nr.  )	dist_funcdist_matrixslice_argskwargss        r9   _dist_wrapperr6    s    &77K6	r;   c           	        ^ ^^^^^ Tc  T m[        T T5      u  m mn[        U5      S:X  a
  T" T T40 TD6$ [        [        5      m[        R
                  " T R                  S   TR                  S   4USS9m[        SUS9" U UUUUU4S j[        [        T5      [        U5      5       5       5        T TL d  Tc   T[        L a  [        R                  " TS5        T$ )zVBreak the pairwise matrix in n_jobs even slices
and compute them using multithreading.r*   r   F)r3   order	threading)backendn_jobsc           	   3   D   >#    U  H  nT" TTUTTU   40 TD6v   M     g 7fNr.  ).0sr6   r7   fdr  r  rets     r9   	<genexpr>%_parallel_pairwise.<locals>.<genexpr>  s.      1KA 	4aAaD)D)Ks    )r:   r   r'   r6  r0   r   rK   r&   r   r(   rb   r{   )r6   r7   r  r<  r  r3   rA  rB  s   ``` ` @@r9   _parallel_pairwiserE    s     	y%a+KAq%1$Aq!D!! 
	B
((AGGAJ
+5
DC[0 1 1 a2B62JK1 
 	
Q!))<!< 	a Jr;   c                    [        U USUSS9u  pXL Ga	  [        R                  " U R                  S   UR                  S   4SS9n[        R
                  " [        U R                  S   5      S5      nU HL  u  px[        U 5      (       a	  X/SS24   OX   n	[        U5      (       a	  X/SS24   OX   n
U" X40 UD6XWU4'   MN     XUR                  -   n[        U R                  S   5       H-  n[        U 5      (       a	  X/SS24   OX   n	U" X40 UD6XWU4'   M/     U$ [        R                  " U R                  S   UR                  S   4SS9n[        R                  " [        U R                  S   5      [        UR                  S   5      5      nU HL  u  px[        U 5      (       a	  X/SS24   OX   n	[        U5      (       a	  X/SS24   OX   n
U" X40 UD6XWU4'   MN     U$ )z:Handle the callable case for pairwise_{distances,kernels}.NF)r3   rB   rC   r   r5   r"  r
   )rH   r0   r   rK   	itertoolscombinationsr  r   r_   r   product)r6   r7   r   rB   r  rj   iteratorr   r   xys              r9   _pairwise_callablerM    s    		+DA 	vhh
AGGAJ/w?))%
*;Q?DA &a[[#q&	adA%a[[#q&	adAq,t,C1I  EEk qwwqz"A &a[[#q&	adAq,t,C1I	 #" J hh
AGGAJ/w?$$U1771:%6aggaj8IJDA &a[[#q&	adA%a[[#q&	adAq,t,C1I  Jr;   c                 8  ^ U c  g[        U [        5      nU(       d  U 4n [        S U  5       5      (       a  [        SU(       a  U OU S   T4-  5      e[        U4S jU  5       5      (       a.  [        S U  5       5      n[	        SU(       a  UOUS   T4-  5      eg)z?Checks chunk is a sequence of expected size or a tuple of same.Nc              3   r   #    U  H-  n[        U[        5      =(       d    [        US 5      (       + v   M/     g7f)__iter__N)r/   tuplehasattrr?  rs     r9   rC  $_check_chunk_size.<locals>.<genexpr>  s)     
Ow!:a=wq*'=#==ws   57z;reduce_func returned %r. Expected sequence(s) of length %d.r   c              3   @   >#    U  H  n[        U5      T:g  v   M     g 7fr>  r(   )r?  rT  
chunk_sizes     r9   rC  rU    s     
:'Q<?j('s   c              3   8   #    U  H  n[        U5      v   M     g 7fr>  rW  rS  s     r9   rC  rU    s     =WLOOWs   zLreduce_func returned object of length %s. Expected same length as input: %d.)r/   rQ  rJ   	TypeErrorrL   )reducedrX  is_tupleactual_sizes    `  r9   _check_chunk_sizer^    s    '5)H*

Ow
OOOI"w
J?@
 	
 
:'
:::=W==1&{KNJGH
 	
 ;r;   c                 <   US:X  a/  SU;  a)  XL a  [         R                  " U SSS9nSU0$ [        S5      eUS:X  a`  SU;  aZ  XL aK  [         R                  R	                  [         R
                  " U R                  5      5      R                  nSU0$ [        S	5      e0 $ )
z:Precompute data-derived metric parameters if not provided.r   Vr   r*   )r   ddofzIThe 'V' parameter is required for the seuclidean metric when Y is passed.r   VIzKThe 'VI' parameter is required for the mahalanobis metric when Y is passed.)r0   varrL   linalginvcovr_   )r6   r7   r   r  r`  rb  s         r9   _precompute_metric_paramsrg    s    #T/6qqq)A Qx	 $ 
 4t#36rvvacc{+--B bz	 $ 
 Ir;   r?   )r6   r7   r   r   r<  working_memory)r   r   r<  rh  c             +   R  #    [        U 5      nUS:X  a  [        SU5      4nO'Uc  U n[        S[        U5      -  UUS9n	[        Xy5      n[	        X4SU0UD6n
UR
                  " S	0 U
D6  U H  nUR                  S:X  a  UR                  U:X  a  U nOX   n[        X4X4S.UD6nXL d  UcE  [        R                  US5      [        L a(  SUR                  UR                  S[        U 5      S-   2'   Ub,  UR                  S   nU" XR                  5      n[        X5        Uv   M     g7f)
a[  Generate a distance matrix chunk by chunk with optional reduction.

In cases where not all of a pairwise distance matrix needs to be
stored at once, this is used to calculate pairwise distances in
``working_memory``-sized chunks.  If ``reduce_func`` is given, it is
run on each chunk and its return values are concatenated into lists,
arrays or sparse matrices.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_samples_X) or             (n_samples_X, n_features)
    Array of pairwise distances between samples, or a feature array.
    The shape the array should be (n_samples_X, n_samples_X) if
    metric='precomputed' and (n_samples_X, n_features) otherwise.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None
    An optional second feature array. Only allowed if
    metric != "precomputed".

reduce_func : callable, default=None
    The function which is applied on each chunk of the distance matrix,
    reducing it to needed values.  ``reduce_func(D_chunk, start)``
    is called repeatedly, where ``D_chunk`` is a contiguous vertical
    slice of the pairwise distance matrix, starting at row ``start``.
    It should return one of: None; an array, a list, or a sparse matrix
    of length ``D_chunk.shape[0]``; or a tuple of such objects.
    Returning None is useful for in-place operations, rather than
    reductions.

    If None, pairwise_distances_chunked returns a generator of vertical
    chunks of the distance matrix.

metric : str or callable, default='euclidean'
    The metric to use when calculating distance between instances in a
    feature array. If metric is a string, it must be one of the options
    allowed by :func:`scipy.spatial.distance.pdist` for its metric parameter,
    or a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS.
    If metric is "precomputed", X is assumed to be a distance matrix.
    Alternatively, if metric is a callable function, it is called on
    each pair of instances (rows) and the resulting value recorded.
    The callable should take two arrays from X as input and return a
    value indicating the distance between them.

n_jobs : int, default=None
    The number of jobs to use for the computation. This works by
    breaking down the pairwise matrix into n_jobs even slices and
    computing them in parallel.

    ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
    ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
    for more details.

working_memory : float, default=None
    The sought maximum memory for temporary distance matrix chunks.
    When None (default), the value of
    ``sklearn.get_config()['working_memory']`` is used.

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

Yields
------
D_chunk : {ndarray, sparse matrix}
    A contiguous slice of distance matrix, optionally processed by
    ``reduce_func``.

Examples
--------
Without reduce_func:

>>> import numpy as np
>>> from sklearn.metrics import pairwise_distances_chunked
>>> X = np.random.RandomState(0).rand(5, 3)
>>> D_chunk = next(pairwise_distances_chunked(X))
>>> D_chunk
array([[0.   , 0.295, 0.417, 0.197, 0.572],
       [0.295, 0.   , 0.576, 0.419, 0.764],
       [0.417, 0.576, 0.   , 0.449, 0.903],
       [0.197, 0.419, 0.449, 0.   , 0.512],
       [0.572, 0.764, 0.903, 0.512, 0.   ]])

Retrieve all neighbors and average distance within radius r:

>>> r = .2
>>> def reduce_func(D_chunk, start):
...     neigh = [np.flatnonzero(d < r) for d in D_chunk]
...     avg_dist = (D_chunk * (D_chunk < r)).mean(axis=1)
...     return neigh, avg_dist
>>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func)
>>> neigh, avg_dist = next(gen)
>>> neigh
[array([0, 3]), array([1]), array([2]), array([0, 3]), array([4])]
>>> avg_dist
array([0.039, 0.        , 0.        , 0.039, 0.        ])

Where r is defined per sample, we need to make use of ``start``:

>>> r = [.2, .4, .4, .3, .1]
>>> def reduce_func(D_chunk, start):
...     neigh = [np.flatnonzero(d < r[i])
...              for i, d in enumerate(D_chunk, start)]
...     return neigh
>>> neigh = next(pairwise_distances_chunked(X, reduce_func=reduce_func))
>>> neigh
[array([0, 3]), array([0, 1]), array([2]), array([0, 3]), array([4])]

Force row-by-row generation by reducing ``working_memory``:

>>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func,
...                                  working_memory=0)
>>> next(gen)
[array([0, 3])]
>>> next(gen)
[array([0, 1])]
r?   r   N   )	row_bytes
max_n_rowsrh  r   )r   r<  r*   r.  )r(   slicer   r   rg  updater   stoppairwise_distancesr-  r   rb   flatrK   r^  )r6   r7   r   r   r<  rh  r  r   sliceschunk_n_rowsparamsslr   D_chunkrX  s                  r9   r   r     s:    V q/K;')9A (,q/)")

 [7 'qCFCdCFKK&88q=RWW3GeG$WVVQUVFai%@%D%DD&
 &!
 =>GLL8\!_q%889" q)J!'884Gg2! s   D%D'rw   )r6   r7   r   r<  rA   rB   )r<  rA   rB   c                   [        XE5      nUS:X  a  [        XSUS9u  pSn[        XS9  U $ U[        ;   a  [        U   n	GO>[	        U5      (       a  [        [        4UUS.UD6n	GO[        U 5      (       d  [        U5      (       a  [        S5      eU[        ;   a  [        OSn
U
[        L aK  U R                  [        :w  d  Ub4  UR                  [        :w  a   S	U-  n[        R                  " U[        5        [        XXS
9u  p[        X4SU0UD6nUR                   " S0 UD6  [#        U5      S:X  a1  XL a-  [$        R&                  " [$        R(                  " U 4SU0UD65      $ [        [$        R*                  4SU0UD6n	[-        XX40 UD6$ )aM  Compute the distance matrix from a feature array X and optional Y.

This function takes one or two feature arrays or a distance matrix, and returns
a distance matrix.

- If `X` is a feature array, of shape (n_samples_X, n_features), and:

  - `Y` is `None` and `metric` is not 'precomputed', the pairwise distances
    between `X` and itself are returned.
  - `Y` is a feature array of shape (n_samples_Y, n_features), the pairwise
    distances between `X` and `Y` is returned.

- If `X` is a distance matrix, of shape (n_samples_X, n_samples_X), `metric`
  should be 'precomputed'. `Y` is thus ignored and `X` is returned as is.

If the input is a collection of non-numeric data (e.g. a list of strings or a
boolean array), a custom metric must be passed.

This method provides a safe way to take a distance matrix as input, while
preserving compatibility with many other algorithms that take a vector
array.

Valid values for metric are:

- From scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
  'manhattan', 'nan_euclidean']. All metrics support sparse matrix
  inputs except 'nan_euclidean'.

- From :mod:`scipy.spatial.distance`: ['braycurtis', 'canberra', 'chebyshev',
  'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis',
  'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean',
  'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'].
  These metrics do not support sparse matrix inputs.

.. note::
    `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11.

.. note::
    `'matching'` has been removed in SciPy 1.9 (use `'hamming'` instead).

Note that in the case of 'cityblock', 'cosine' and 'euclidean' (which are
valid :mod:`scipy.spatial.distance` metrics), the scikit-learn implementation
will be used, which is faster and has support for sparse matrices (except
for 'cityblock'). For a verbose description of the metrics from
scikit-learn, see :func:`sklearn.metrics.pairwise.distance_metrics`
function.

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples_X, n_samples_X) or             (n_samples_X, n_features)
    Array of pairwise distances between samples, or a feature array.
    The shape of the array should be (n_samples_X, n_samples_X) if
    metric == "precomputed" and (n_samples_X, n_features) otherwise.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None
    An optional second feature array. Only allowed if
    metric != "precomputed".

metric : str or callable, default='euclidean'
    The metric to use when calculating distance between instances in a
    feature array. If metric is a string, it must be one of the options
    allowed by :func:`scipy.spatial.distance.pdist` for its metric parameter, or
    a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``.
    If metric is "precomputed", X is assumed to be a distance matrix.
    Alternatively, if metric is a callable function, it is called on each
    pair of instances (rows) and the resulting value recorded. The callable
    should take two arrays from X as input and return a value indicating
    the distance between them.

n_jobs : int, default=None
    The number of jobs to use for the computation. This works by breaking
    down the pairwise matrix into n_jobs even slices and computing them
    using multithreading.

    ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
    ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
    for more details.

    The "euclidean" and "cosine" metrics rely heavily on BLAS which is already
    multithreaded. So, increasing `n_jobs` would likely cause oversubscription
    and quickly degrade performance.

force_all_finite : bool or 'allow-nan', default=True
    Whether to raise an error on np.inf, np.nan, pd.NA in array. Ignored
    for a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``. The
    possibilities are:

    - True: Force all values of array to be finite.
    - False: accepts np.inf, np.nan, pd.NA in array.
    - 'allow-nan': accepts only np.nan and pd.NA values in array. Values
      cannot be infinite.

    .. versionadded:: 0.22
       ``force_all_finite`` accepts the string ``'allow-nan'``.

    .. versionchanged:: 0.23
       Accepts `pd.NA` and converts it into `np.nan`.

    .. deprecated:: 1.6
       `force_all_finite` was renamed to `ensure_all_finite` and will be removed
       in 1.8.

ensure_all_finite : bool or 'allow-nan', default=True
    Whether to raise an error on np.inf, np.nan, pd.NA in array. Ignored
    for a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``. The
    possibilities are:

    - True: Force all values of array to be finite.
    - False: accepts np.inf, np.nan, pd.NA in array.
    - 'allow-nan': accepts only np.nan and pd.NA values in array. Values
      cannot be infinite.

    .. versionadded:: 1.6
       `force_all_finite` was renamed to `ensure_all_finite`.

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

Returns
-------
D : ndarray of shape (n_samples_X, n_samples_X) or             (n_samples_X, n_samples_Y)
    A distance matrix D such that D_{i, j} is the distance between the
    ith and jth vectors of the given matrix X, if Y is None.
    If Y is not None, then D_{i, j} is the distance between the ith array
    from X and the jth array from Y.

See Also
--------
pairwise_distances_chunked : Performs the same calculation as this
    function, but returns a generator of chunks of the distance matrix, in
    order to limit memory usage.
sklearn.metrics.pairwise.paired_distances : Computes the distances between
    corresponding elements of two arrays.

Notes
-----
If metric is a callable, no restrictions are placed on `X` and `Y` dimensions.

Examples
--------
>>> from sklearn.metrics.pairwise import pairwise_distances
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> pairwise_distances(X, Y, metric='sqeuclidean')
array([[1., 2.],
       [2., 1.]])
r?   T)r?   rB   zM`pairwise_distances`. Precomputed distance  need to have non-negative values.)whom)r   rB   z6scipy distance metrics do not support sparse matrices.r<   z+Data was converted to boolean for metric %s)r3   rB   r   r*   r.  )r!   rH   r)   r-  r  r   rM  r   rZ  PAIRWISE_BOOLEAN_FUNCTIONSboolr3   warningswarnr   rg  rn  r   r	   
squareformpdistr   rE  )r6   r7   r   r<  rA   rB   r  rM   rx  r  r3   msgrt  s                r9   rp  rp    s   d 44DX$d6G

1 	 	1(	.	.*62	&		
/
 	
 A;;(1++TUU"<<-D=aggo!-AGGtO?&HCMM#45$

 +1GG$GfF#q(QV&&x~~a'O'O$'OPPx~~=f==aD9D99r;   )r   r   r   r   r   r   )	additive_chi2chi2linear
polynomialpolyrbf	laplaciansigmoidr   c                      [         $ )aC  Valid metrics for pairwise_kernels.

This function simply returns the valid pairwise distance metrics.
It exists, however, to allow for a verbose description of the mapping for
each of the valid strings.

The valid distance metrics, and the function they map to, are:
  ===============   ========================================
  metric            Function
  ===============   ========================================
  'additive_chi2'   sklearn.pairwise.additive_chi2_kernel
  'chi2'            sklearn.pairwise.chi2_kernel
  'linear'          sklearn.pairwise.linear_kernel
  'poly'            sklearn.pairwise.polynomial_kernel
  'polynomial'      sklearn.pairwise.polynomial_kernel
  'rbf'             sklearn.pairwise.rbf_kernel
  'laplacian'       sklearn.pairwise.laplacian_kernel
  'sigmoid'         sklearn.pairwise.sigmoid_kernel
  'cosine'          sklearn.pairwise.cosine_similarity
  ===============   ========================================

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

Returns
-------
kernel_metrics : dict
    Returns valid metrics for pairwise_kernels.
)PAIRWISE_KERNEL_FUNCTIONSr.  r;   r9   kernel_metricsr  	  s
    : %$r;   r.  r  )r  r  r  r  )	r  r  r   r  r  r  r  r  r  )r6   r7   r   filter_paramsr<  )r  r<  c                V   SSK Jn  US:X  a  [        XSS9u  pU $ [        X&5      (       a  UR                  nO`U[
        ;   a4  U(       a#  U V	s0 s H  o[        U   ;   d  M  XU	   _M     nn	[
        U   nO"[        U5      (       a  [        [        4SU0UD6n[        XWU40 UD6$ s  sn	f )a:  Compute the kernel between arrays X and optional array Y.

This function takes one or two feature arrays or a kernel matrix, and returns
a kernel matrix.

- If `X` is a feature array, of shape (n_samples_X, n_features), and:

  - `Y` is `None` and `metric` is not 'precomputed', the pairwise kernels
    between `X` and itself are returned.
  - `Y` is a feature array of shape (n_samples_Y, n_features), the pairwise
    kernels between `X` and `Y` is returned.

- If `X` is a kernel matrix, of shape (n_samples_X, n_samples_X), `metric`
  should be 'precomputed'. `Y` is thus ignored and `X` is returned as is.

This method provides a safe way to take a kernel matrix as input, while
preserving compatibility with many other algorithms that take a vector
array.

Valid values for metric are:
    ['additive_chi2', 'chi2', 'linear', 'poly', 'polynomial', 'rbf',
    'laplacian', 'sigmoid', 'cosine']

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

Parameters
----------
X : {array-like, sparse matrix}  of shape (n_samples_X, n_samples_X) or             (n_samples_X, n_features)
    Array of pairwise kernels between samples, or a feature array.
    The shape of the array should be (n_samples_X, n_samples_X) if
    metric == "precomputed" and (n_samples_X, n_features) otherwise.

Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None
    A second feature array only if X has shape (n_samples_X, n_features).

metric : str or callable, default="linear"
    The metric to use when calculating kernel between instances in a
    feature array. If metric is a string, it must be one of the metrics
    in ``pairwise.PAIRWISE_KERNEL_FUNCTIONS``.
    If metric is "precomputed", X is assumed to be a kernel matrix.
    Alternatively, if metric is a callable function, it is called on each
    pair of instances (rows) and the resulting value recorded. The callable
    should take two rows from X as input and return the corresponding
    kernel value as a single number. This means that callables from
    :mod:`sklearn.metrics.pairwise` are not allowed, as they operate on
    matrices, not single samples. Use the string identifying the kernel
    instead.

filter_params : bool, default=False
    Whether to filter invalid parameters or not.

n_jobs : int, default=None
    The number of jobs to use for the computation. This works by breaking
    down the pairwise matrix into n_jobs even slices and computing them
    using multithreading.

    ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
    ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
    for more details.

**kwds : optional keyword parameters
    Any further parameters are passed directly to the kernel function.

Returns
-------
K : ndarray of shape (n_samples_X, n_samples_X) or (n_samples_X, n_samples_Y)
    A kernel matrix K such that K_{i, j} is the kernel between the
    ith and jth vectors of the given matrix X, if Y is None.
    If Y is not None, then K_{i, j} is the kernel between the ith array
    from X and the jth array from Y.

Notes
-----
If metric is a callable, no restrictions are placed on `X` and `Y` dimensions.

Examples
--------
>>> from sklearn.metrics.pairwise import pairwise_kernels
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> pairwise_kernels(X, Y, metric='linear')
array([[0., 0.],
       [1., 2.]])
r
   )Kernelr?   T)r?   r   )gaussian_process.kernelsr  rH   r/   __call__r  KERNEL_PARAMSr  r   rM  rE  )
r6   r7   r   r  r<  r  GPKernelrM   r  r   s
             r9   pairwise_kernelsr  	  s    L >$Qt<	F	%	%	,	,(,K1]65J0JJAAwJDK(0	&		)A&ADAaD&9D99 Ls   B&!	B&r>  )NNF)NNNN)NT)N   Nr*   )NNr*   )NN)Nr  )T)Nr   )Nr  )w__doc__rG  r   r{  	functoolsr   numbersr   r   numpyr0   joblibr   scipy.sparser   r   scipy.spatialr	    r   
exceptionsr   preprocessingr   utilsr   r   r   utils._array_apir   r   r   r   r   r   r   utils._chunkingr   utils._maskr   utils._missingr   utils._param_validationr   r   r   r   r   r    utils.deprecationr!   utils.extmathr"   r#   utils.fixesr$   r%   utils.parallelr&   r'   utils.validationr(   r)   _pairwise_distances_reductionr+   _pairwise_fastr,   r-   r:   rH   rQ   rb   r`   r|   r   rl   r   r   _VALID_METRICS_NAN_METRICSsetunionvalid_metricsr  dictr   r   r   r   r   r   r   r   r  r  r
  r1   r  r  r  r  r   r)  r+  r-  r/  r6  rE  rM  r^  rg  r   rp  ry  r  r  	frozensetr  r  r.  r;   r9   <module>r     sQ	   E
     "  # - "  . % = =   / # *  < 6 8 . ? 2 @8 
!	_D H O,2'.;'. #'	 
iO!%uTiO	iOX3l ^D!;(d;< #'	 
|T|	|~GT6 ]6**''N]6**{m#N]5))zl"N  O,O,Aq6*+s>*001F1F1HIJ
 	 #( KtFFR O,O,Aq6*+s>*001F1F1HIJ
 	 #( -.kQU ~~B 
)0UV"&3A	3Al O,2 #'2-2-j O,2 #'..d 
)0OP"&	> 
)0OP"&%)	%)P 
)0OP"&#F	#FN &+
$
$++  ^^c"234h?
 #' &1 ::| O,2"
 #'#>#>L O,2D!T&9:T1d622::

 4tI>?
 #'11h O,2T1d622::

 4tI>?	 #'//d O,2T1d622::
 #'--` O,2T1d952::
 #'--` O,2"
 #'77t .d34"&N+	N+b ^D!4D;VBJJ=OP
 #'==H %$$

$, '@8
6-`
*. O,2 $'}o33NCDhOT"#D!T&A4H #(
 j j
jZ O,2c.1]OCDhOT"}%:|n-.

 ([M)BF4LQ #'" O:
 !O:O:f  ]6**?"33]6**;-/]5)):,. *#! %B wi 2389gYG9%'7+,
 O,2s45GH
 $T"	 #' g:16tg:g:r;   