
    -ie                        S r SSK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JrJr  SS
KJrJrJr  SSKJrJr  SSKJr          S!S jr\" S/S/\" \SSSS9/SS/\" \SSSS9\" S15      /\S/\" \SSSS9/S/\" \SSSS9/S/S/S\" S15      /S.SS9SSSSSSSSSSSS.S j5       r " S S \
5      rg)"z"
Multi-dimensional Scaling (MDS).
    N)IntegralReal)effective_n_jobs   )BaseEstimator_fit_context)IsotonicRegression)euclidean_distances)check_arraycheck_random_statecheck_symmetric)Interval
StrOptionsvalidate_params)Paralleldelayed)validate_dataT,  ư>Fc	                    [        U SS9n U R                  S   n	[        U5      nS[        R                  " U	5      -
  U -  R                  5       n
XS:g     nUc$  UR                  X-  S9nUR                  X45      nO2UR                  S   nXR                  S   :w  a  [        SX4-  5      eUn[        U5      n[        SS	9nSn[        U5       GH  nU(       a  U nOUR                  5       nUU
S:g     nUS:  a  UnOUR                  UU5      n[        R                  " U5      nUUU
S:g  '   UR                  X45      nU[        R                  " XS-
  -  S
-  US
-  R                  5       -  5      -  nUUR                   -   nSXS:H  '   UU-  nU* nU[        R"                  " [%        U5      5      [        R"                  " [%        U5      5      4==   UR                  SS9-  ss'   SU	-  [        R&                  " UU5      -  n[        U5      nUR                  5       UR                  5       -
  S
-  R                  5       S
-  nUS
:  a  [)        SU SUS 35        UbD  UR                  5       S
-  R                  5       nUU-
  US
-  -  U:  a  U(       a  [)        S5          OUnGM     U(       a=  UR                  5       S
-  R                  5       n[        R                  " WUS
-  -  5      nUWWS-   4$ )a
  Computes multidimensional scaling using SMACOF algorithm.

Parameters
----------
dissimilarities : ndarray of shape (n_samples, n_samples)
    Pairwise dissimilarities between the points. Must be symmetric.

metric : bool, default=True
    Compute metric or nonmetric SMACOF algorithm.
    When ``False`` (i.e. non-metric MDS), dissimilarities with 0 are considered as
    missing values.

n_components : int, default=2
    Number of dimensions in which to immerse the dissimilarities. If an
    ``init`` array is provided, this option is overridden and the shape of
    ``init`` is used to determine the dimensionality of the embedding
    space.

init : ndarray of shape (n_samples, n_components), default=None
    Starting configuration of the embedding to initialize the algorithm. By
    default, the algorithm is initialized with a randomly chosen array.

max_iter : int, default=300
    Maximum number of iterations of the SMACOF algorithm for a single run.

verbose : int, default=0
    Level of verbosity.

eps : float, default=1e-6
    The tolerance with respect to stress (normalized by the sum of squared
    embedding distances) at which to declare convergence.

    .. versionchanged:: 1.7
       The default value for `eps` has changed from 1e-3 to 1e-6, as a result
       of a bugfix in the computation of the convergence criterion.

random_state : int, RandomState instance or None, default=None
    Determines the random number generator used to initialize the centers.
    Pass an int for reproducible results across multiple function calls.
    See :term:`Glossary <random_state>`.

normalized_stress : bool, default=False
    Whether to return normalized stress value (Stress-1) instead of raw
    stress.

    .. versionadded:: 1.2

    .. versionchanged:: 1.7
       Normalized stress is now supported for metric MDS as well.

Returns
-------
X : ndarray of shape (n_samples, n_components)
    Coordinates of the points in a ``n_components``-space.

stress : float
    The final value of the stress (sum of squared distance of the
    disparities and the distances for all constrained points).
    If `normalized_stress=True`, returns Stress-1.
    A value of 0 indicates "perfect" fit, 0.025 excellent, 0.05 good,
    0.1 fair, and 0.2 poor [1]_.

n_iter : int
    The number of iterations corresponding to the best stress.

References
----------
.. [1] "Nonmetric multidimensional scaling: a numerical method" Kruskal, J.
       Psychometrika, 29 (1964)

.. [2] "Multidimensional scaling by optimizing goodness of fit to a nonmetric
       hypothesis" Kruskal, J. Psychometrika, 29, (1964)

.. [3] "Modern Multidimensional Scaling - Theory and Applications" Borg, I.;
       Groenen P. Springer Series in Statistics (1997)
T)raise_exceptionr      Nsizez'init matrix should be of shape (%d, %d)clip)out_of_boundsr   gh㈵>)axisg      ?z
Iteration z	, stress z.4fzConvergence criterion reached.)r   shaper   nptriraveluniformreshape
ValueErrorr
   r	   rangefit_transform
zeros_likesqrtsumTarangelendotprint)dissimilaritiesmetricn_componentsinitmax_iterverboseepsrandom_statenormalized_stress	n_samplesdissimilarities_flatdissimilarities_flat_wX	distancesir
old_stressitdisparitiesdistances_flatdistances_flat_wdisparities_flatratioBstresssum_squared_distancess                            H/var/www/html/venv/lib/python3.13/site-packages/sklearn/manifold/_mds.py_smacof_singlerI      s   n &otLO%%a(I%l3L	!22oELLN1!2KL|  i&> ?IIy/0 zz!}

1%9Y<UU  #A&I
 
&	1BJHo)K&__.N-.Ba.GH Av#9 #%#3#3*,<$  --7K5EK,12%--y.DEK277!m,q0[!^4H4H4JJ K &5K %)	q.!i'F	"))CF
RYYs1v.
./599!93DD/)ObffQl* (*	??${'8'8'::q@EEG!Ka<Jrd)F3<89!%.__%6!%;$@$@$B!f$)>)BCsJ:;
] ` !*!2a!7 < < >#81#<=>fb1f    z
array-likebooleanr   leftclosedwarnr4   r6   auto)r/   r0   r1   r2   n_initn_jobsr3   r4   r5   r6   return_n_iterr7   prefer_skip_nested_validationr0   r1   r2   rQ   rR   r3   r4   r5   r6   rS   r7   c                P  ^ ^^^^^^^ US:X  a  [         R                  " S[        5        Sn[        T 5      m [	        U	5      n	TS:X  a  T(       + m[        TS5      (       aE  [        R                  " T5      R                  5       mUS:X  d  [         R                  " SU-  5        SnSu  p[        U5      S:X  aG  [        U5       H7  n[        T TTTTTTU	TS	9	u  nnnUb  UU:  d  M#  UnUR                  5       nUnM9     OU	R                  [        R                  " [        R                  5      R                  US
9n[!        U[        TS-
  S5      S9" U UUUUUUU4S jU 5       5      n[#        U6 u  nnn[        R$                  " U5      nUU   nUU   nUU   nU
(       a  XW4$ X4$ )ao  Compute multidimensional scaling using the SMACOF algorithm.

The SMACOF (Scaling by MAjorizing a COmplicated Function) algorithm is a
multidimensional scaling algorithm which minimizes an objective function
(the *stress*) using a majorization technique. Stress majorization, also
known as the Guttman Transform, guarantees a monotone convergence of
stress, and is more powerful than traditional techniques such as gradient
descent.

The SMACOF algorithm for metric MDS can be summarized by the following
steps:

1. Set an initial start configuration, randomly or not.
2. Compute the stress
3. Compute the Guttman Transform
4. Iterate 2 and 3 until convergence.

The nonmetric algorithm adds a monotonic regression step before computing
the stress.

Parameters
----------
dissimilarities : array-like of shape (n_samples, n_samples)
    Pairwise dissimilarities between the points. Must be symmetric.

metric : bool, default=True
    Compute metric or nonmetric SMACOF algorithm.
    When ``False`` (i.e. non-metric MDS), dissimilarities with 0 are considered as
    missing values.

n_components : int, default=2
    Number of dimensions in which to immerse the dissimilarities. If an
    ``init`` array is provided, this option is overridden and the shape of
    ``init`` is used to determine the dimensionality of the embedding
    space.

init : array-like of shape (n_samples, n_components), default=None
    Starting configuration of the embedding to initialize the algorithm. By
    default, the algorithm is initialized with a randomly chosen array.

n_init : int, default=8
    Number of times the SMACOF algorithm will be run with different
    initializations. The final results will be the best output of the runs,
    determined by the run with the smallest final stress. If ``init`` is
    provided, this option is overridden and a single run is performed.

    .. versionchanged:: 1.9
       The default value for `n_iter` will change from 8 to 1 in version 1.9.

n_jobs : int, default=None
    The number of jobs to use for the computation. If multiple
    initializations are used (``n_init``), each run of the algorithm is
    computed 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.

max_iter : int, default=300
    Maximum number of iterations of the SMACOF algorithm for a single run.

verbose : int, default=0
    Level of verbosity.

eps : float, default=1e-6
    The tolerance with respect to stress (normalized by the sum of squared
    embedding distances) at which to declare convergence.

    .. versionchanged:: 1.7
       The default value for `eps` has changed from 1e-3 to 1e-6, as a result
       of a bugfix in the computation of the convergence criterion.

random_state : int, RandomState instance or None, default=None
    Determines the random number generator used to initialize the centers.
    Pass an int for reproducible results across multiple function calls.
    See :term:`Glossary <random_state>`.

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

normalized_stress : bool or "auto", default="auto"
    Whether to return normalized stress value (Stress-1) instead of raw
    stress. By default, metric MDS returns raw stress while non-metric MDS
    returns normalized stress.

    .. versionadded:: 1.2

    .. versionchanged:: 1.4
       The default value changed from `False` to `"auto"` in version 1.4.

    .. versionchanged:: 1.7
       Normalized stress is now supported for metric MDS as well.

Returns
-------
X : ndarray of shape (n_samples, n_components)
    Coordinates of the points in a ``n_components``-space.

stress : float
    The final value of the stress (sum of squared distance of the
    disparities and the distances for all constrained points).
    If `normalized_stress=True`, returns Stress-1.
    A value of 0 indicates "perfect" fit, 0.025 excellent, 0.05 good,
    0.1 fair, and 0.2 poor [1]_.

n_iter : int
    The number of iterations corresponding to the best stress. Returned
    only if ``return_n_iter`` is set to ``True``.

References
----------
.. [1] "Nonmetric multidimensional scaling: a numerical method" Kruskal, J.
       Psychometrika, 29 (1964)

.. [2] "Multidimensional scaling by optimizing goodness of fit to a nonmetric
       hypothesis" Kruskal, J. Psychometrika, 29, (1964)

.. [3] "Modern Multidimensional Scaling - Theory and Applications" Borg, I.;
       Groenen P. Springer Series in Statistics (1997)

Examples
--------
>>> import numpy as np
>>> from sklearn.manifold import smacof
>>> from sklearn.metrics import euclidean_distances
>>> X = np.array([[0, 1, 2], [1, 0, 3], [2, 3, 0]])
>>> dissimilarities = euclidean_distances(X)
>>> Z, stress = smacof(
...     dissimilarities, n_components=2, n_init=1, eps=1e-6, random_state=42
... )
>>> Z.shape
(3, 2)
>>> np.round(stress, 6).item()
3.2e-05
rO   z=The default value of `n_init` will change from 8 to 1 in 1.9.   rP   	__array__r   zTExplicit initial positions passed: performing only one init of the MDS instead of %dNNr0   r1   r2   r3   r4   r5   r6   r7   r   r   )rR   r4   c              3   Z   >#    U  H   n[        [        5      " TTTTTT	TUTS 9	v   M"     g7f)r[   N)r   rI   )
.0seedr/   r5   r2   r3   r0   r1   r7   r4   s
     rH   	<genexpr>smacof.<locals>.<genexpr>  sB      G
  N#)!!"3
 s   (+)warningsrO   FutureWarningr   r   hasattrr   asarraycopyr   r%   rI   randintiinfoint32maxr   zipargmin)r/   r0   r1   r2   rQ   rR   r3   r4   r5   r6   rS   r7   best_posbest_stressr?   posrF   n_iter_	best_iterseedsresults	positionsn_itersbests   ````  ```  `            rH   smacofrv      s   P K	
 !/2O%l3LF" &Jt[!!zz$$$&{MMDFLM F&H1$-B#1)!)"3
$ C "f{&:$88:#	  " $$RXXbhh%7%;%;&$I&#gk12EF G
 G
 G
 
 &)']"	67yy TlT?DM	i//$$rJ   c                     ^  \ rS rSr% Sr\" \SSSS9/S/\" \SSSS9\" S15      /\" \SSSS9/S	/\" \S
SSS9/S\/S/\" SS15      /S\" S15      /S.
r	\
\S'    SSSSSSSSSSS.	S jjrU 4S jrSS jr\" SS9SS j5       rSrU =r$ )MDSi  a  Multidimensional scaling.

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

Parameters
----------
n_components : int, default=2
    Number of dimensions in which to immerse the dissimilarities.

metric : bool, default=True
    If ``True``, perform metric MDS; otherwise, perform nonmetric MDS.
    When ``False`` (i.e. non-metric MDS), dissimilarities with 0 are considered as
    missing values.

n_init : int, default=4
    Number of times the SMACOF algorithm will be run with different
    initializations. The final results will be the best output of the runs,
    determined by the run with the smallest final stress.

    .. versionchanged:: 1.9
       The default value for `n_init` will change from 4 to 1 in version 1.9.

max_iter : int, default=300
    Maximum number of iterations of the SMACOF algorithm for a single run.

verbose : int, default=0
    Level of verbosity.

eps : float, default=1e-6
    The tolerance with respect to stress (normalized by the sum of squared
    embedding distances) at which to declare convergence.

    .. versionchanged:: 1.7
       The default value for `eps` has changed from 1e-3 to 1e-6, as a result
       of a bugfix in the computation of the convergence criterion.

n_jobs : int, default=None
    The number of jobs to use for the computation. If multiple
    initializations are used (``n_init``), each run of the algorithm is
    computed 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.

random_state : int, RandomState instance or None, default=None
    Determines the random number generator used to initialize the centers.
    Pass an int for reproducible results across multiple function calls.
    See :term:`Glossary <random_state>`.

dissimilarity : {'euclidean', 'precomputed'}, default='euclidean'
    Dissimilarity measure to use:

    - 'euclidean':
        Pairwise Euclidean distances between points in the dataset.

    - 'precomputed':
        Pre-computed dissimilarities are passed directly to ``fit`` and
        ``fit_transform``.

normalized_stress : bool or "auto" default="auto"
    Whether to return normalized stress value (Stress-1) instead of raw
    stress. By default, metric MDS returns raw stress while non-metric MDS
    returns normalized stress.

    .. versionadded:: 1.2

    .. versionchanged:: 1.4
       The default value changed from `False` to `"auto"` in version 1.4.

    .. versionchanged:: 1.7
       Normalized stress is now supported for metric MDS as well.

Attributes
----------
embedding_ : ndarray of shape (n_samples, n_components)
    Stores the position of the dataset in the embedding space.

stress_ : float
    The final value of the stress (sum of squared distance of the
    disparities and the distances for all constrained points).
    If `normalized_stress=True`, returns Stress-1.
    A value of 0 indicates "perfect" fit, 0.025 excellent, 0.05 good,
    0.1 fair, and 0.2 poor [1]_.

dissimilarity_matrix_ : ndarray of shape (n_samples, n_samples)
    Pairwise dissimilarities between the points. Symmetric matrix that:

    - either uses a custom dissimilarity matrix by setting `dissimilarity`
      to 'precomputed';
    - or constructs a dissimilarity matrix from data using
      Euclidean distances.

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

n_iter_ : int
    The number of iterations corresponding to the best stress.

See Also
--------
sklearn.decomposition.PCA : Principal component analysis that is a linear
    dimensionality reduction method.
sklearn.decomposition.KernelPCA : Non-linear dimensionality reduction using
    kernels and PCA.
TSNE : T-distributed Stochastic Neighbor Embedding.
Isomap : Manifold learning based on Isometric Mapping.
LocallyLinearEmbedding : Manifold learning using Locally Linear Embedding.
SpectralEmbedding : Spectral embedding for non-linear dimensionality.

References
----------
.. [1] "Nonmetric multidimensional scaling: a numerical method" Kruskal, J.
   Psychometrika, 29 (1964)

.. [2] "Multidimensional scaling by optimizing goodness of fit to a nonmetric
   hypothesis" Kruskal, J. Psychometrika, 29, (1964)

.. [3] "Modern Multidimensional Scaling - Theory and Applications" Borg, I.;
   Groenen P. Springer Series in Statistics (1997)

Examples
--------
>>> from sklearn.datasets import load_digits
>>> from sklearn.manifold import MDS
>>> X, _ = load_digits(return_X_y=True)
>>> X.shape
(1797, 64)
>>> embedding = MDS(n_components=2, n_init=1)
>>> X_transformed = embedding.fit_transform(X[:100])
>>> X_transformed.shape
(100, 2)

For a more detailed example of usage, see
:ref:`sphx_glr_auto_examples_manifold_plot_mds.py`.

For a comparison of manifold learning techniques, see
:ref:`sphx_glr_auto_examples_manifold_plot_compare_methods.py`.
r   NrL   rM   rK   rO   r4   g        r6   	euclideanprecomputedrP   )
r1   r0   rQ   r3   r4   r5   rR   r6   dissimilarityr7   _parameter_constraintsTr   r   r   )	r0   rQ   r3   r4   r5   rR   r6   r{   r7   c       	         |    Xl         Xl        X l        X0l        X@l        X`l        XPl        Xpl        Xl        Xl	        g )N)
r1   r{   r0   rQ   r3   r5   r4   rR   r6   r7   )selfr1   r0   rQ   r3   r4   r5   rR   r6   r{   r7   s              rH   __init__MDS.__init__Q  s:     )* (!2rJ   c                 `   > [         TU ]  5       nU R                  S:H  UR                  l        U$ )Nrz   )super__sklearn_tags__r{   
input_tagspairwise)r~   tags	__class__s     rH   r   MDS.__sklearn_tags__j  s,    w')#'#5#5#F rJ   c                 $    U R                  XS9  U $ )ao  
Compute the position of the points in the embedding space.

Parameters
----------
X : array-like of shape (n_samples, n_features) or                 (n_samples, n_samples)
    Input data. If ``dissimilarity=='precomputed'``, the input should
    be the dissimilarity matrix.

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

init : ndarray of shape (n_samples, n_components), default=None
    Starting configuration of the embedding to initialize the SMACOF
    algorithm. By default, the algorithm is initialized with a randomly
    chosen array.

Returns
-------
self : object
    Fitted estimator.
)r2   )r&   r~   r;   yr2   s       rH   fitMDS.fito  s    0 	1(rJ   rT   c                    U R                   S:X  a#  [        R                  " S[        5        SU l        OU R                   U l        [        X5      nUR                  S   UR                  S   :X  a&  U R                  S:w  a  [        R                  " S5        U R                  S:X  a  Xl        O U R                  S:X  a  [        U5      U l        [        U R                  U R                  U R                  UU R                  U R                  U R                  U R                  U R                   U R"                  S	U R$                  S
9u  U l        U l        U l        U R&                  $ )a  
Fit the data from `X`, and returns the embedded coordinates.

Parameters
----------
X : array-like of shape (n_samples, n_features) or                 (n_samples, n_samples)
    Input data. If ``dissimilarity=='precomputed'``, the input should
    be the dissimilarity matrix.

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

init : ndarray of shape (n_samples, n_components), default=None
    Starting configuration of the embedding to initialize the SMACOF
    algorithm. By default, the algorithm is initialized with a randomly
    chosen array.

Returns
-------
X_new : ndarray of shape (n_samples, n_components)
    X transformed in the new space.
rO   z=The default value of `n_init` will change from 4 to 1 in 1.9.   r   r   rz   zThe MDS API has changed. ``fit`` now constructs a dissimilarity matrix from data. To use a custom dissimilarity matrix, set ``dissimilarity='precomputed'``.ry   TrV   )rQ   ra   rO   rb   _n_initr   r   r{   dissimilarity_matrix_r
   rv   r0   r1   rR   r3   r4   r5   r6   r7   
embedding_stress_ro   r   s       rH   r&   MDS.fit_transform  s   4 ;;& MMO DL;;DL$"771:#(:(:m(KMM3 .)*&;.)<Q)?D&6<&&;;**<<;;]]LL**"447
3t| rJ   )r   r{   r   r   r5   r3   r0   r1   rQ   ro   rR   r7   r6   r   r4   )r   rZ   )__name__
__module____qualname____firstlineno____doc__r   r   r   r   r|   dict__annotations__r   r   r   r   r&   __static_attributes____classcell__)r   s   @rH   rx   rx     s    Rj "(AtFCD+Haf=z6(?STh4?@;sD89"'($k=%ABC'VH)=>$D  3 ! 32
6 5? 6?rJ   rx   )Tr   Nr   r   r   NF) r   ra   numbersr   r   numpyr   joblibr   baser   r   isotonicr	   metricsr
   utilsr   r   r   utils._param_validationr   r   r   utils.parallelr   r   utils.validationr   rI   rv   rx    rJ   rH   <module>r      s1    "  # . ) ) D D K K . ,
 	fT (>+!(AtFCDt$Haf=z6(?STT"h4?@;q$v67'(#'VH)=> #'( 	Y%#"Y%z[- [rJ   