
    0Ph]                        d Z ddlZddlmZmZ ddlZddlmZ ddl	m
Z
mZ ddlmZ ddlmZ dd	lmZmZmZ dd
lmZmZmZ ddlmZmZ ddlmZ 	 	 	 	 	 	 	 	 d!dZ edgdg eeddd          gddg eeddd          gedg eeddd          gdg eeddd          gdgdgd edh          gdd          ddddddddddddd            Z G d d e
          ZdS )"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,  MbP?Fc	                    t          | d          } | j        d         }	t          |          }dt          j        |	          z
  | z                                  }
|
|
dk             }|1|                    |	|z            }|                    |	|f          }n4|j        d         }|	|j        d         k    rt          d|	|fz            |}d}t                      }t          |          D ]O}t          |          }|r| }n|                                }||
dk             }|                    ||          }|                                }|||
dk    <   |                    |	|	f          }|t          j        |	|	dz
  z  dz  |dz                                  z            z  }|                                |                                z
  dz                                  dz  }|rAt          j        ||                                dz                                  dz  z            }d	||dk    <   ||z  }| }|t          j        t#          |                    t          j        t#          |                    fxx         |                    d
          z  cc<   d|	z  t          j        ||          z  }t          j        |dz                      d
                                                    }|dk    rt'          d||fz             |$|||z  z
  |k     r|rt'          d||fz              n||z  }Q|||dz   fS )ab  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-3
        Relative tolerance with respect to stress at which to declare
        convergence. The value of `eps` should be tuned separately depending
        on whether or not `normalized_stress` is being used.

    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 use and return normed stress value (Stress-1) instead of raw
        stress calculated by default. Only supported in non-metric MDS. The
        caller must ensure that if `normalized_stress=True` then `metric=False`

        .. versionadded:: 1.2

    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`, and `metric=False` 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)r   gh㈵>)axisg      ?zit: %d, stress %sz'breaking at iteration %d with stress %s)r   shaper   nptriraveluniformreshape
ValueErrorr	   ranger
   fit_transformcopysqrtsumarangelendotprint)dissimilaritiesmetricn_componentsinitmax_iterverboseepsrandom_statenormalized_stress	n_samplessim_flat
sim_flat_wX
old_stressiritdisdisparitiesdis_flat
dis_flat_wdisparities_flatstressratioBs                           U/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/manifold/_mds.py_smacof_singlerE      si   d &otLLLO%a(I%l33LRVI&&&/9@@BBH(a-(J|  i,&> ??IIy,/00 z!}
1%%9Y<UU   J			BHoo '" '"!!$$ 	)KKyy{{H!(a-0J  "//
JGG"--//K)9KA&%--y).DEEK27i!m,q0[!^4H4H4J4JJ  K
 99;;!2!2!4!44:??AAAE 	NWV(9(9(;(;q(@'E'E'G'G!'KLMMFC1Hc!F	")CFF

RYs1vv..
.///599!93D3DD///)ObfQll*gq!tjjaj(())--//a<<%V4555!Vc\)S00 TCr6lRSSSc\

fb1f    z
array-likebooleanr   leftclosedr1   r3   auto)r,   r-   r.   r/   n_initn_jobsr0   r1   r2   r3   return_n_iterr4   prefer_skip_nested_validation   r-   r.   r/   rL   rM   r0   r1   r2   r3   rN   r4   c                r    t                      t          |	          }	dk    r rrt          d          t          d          rEt	          j                                                  |dk    st          j        d|z             d}d\  }}t          |          dk    rOt          |          D ]>}t           |		  	        \  }}}|||k     r|}|                                }|}?n|	                    t	          j        t          j                  j        |	          } t!          |t          dz
  d
                     fd|D                       }t#          | \  }}}t	          j        |          }||         }||         }||         }|
r|||fS ||fS )a  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.

    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-3
        Relative tolerance with respect to stress at which to declare
        convergence. The value of `eps` should be tuned separately depending
        on whether or not `normalized_stress` is being used.

    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 use and return normed stress value (Stress-1) instead of raw
        stress calculated by default. Only supported in non-metric MDS.

        .. versionadded:: 1.2

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

    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`, and `metric=False` 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)
    >>> mds_result, stress = smacof(dissimilarities, n_components=2, random_state=42)
    >>> mds_result
    array([[ 0.05... -1.07... ],
           [ 1.74..., -0.75...],
           [-1.79...,  1.83...]])
    >>> stress
    np.float64(0.0012...)
    rK   znNormalized stress is not supported for metric MDS. Either set `normalized_stress=False` or use `metric=False`.	__array__r   zTExplicit initial positions passed: performing only one init of the MDS instead of %dNNr-   r.   r/   r0   r1   r2   r3   r4   Nr   r   )rM   r1   c              3   d   K   | ]*} t          t                    	| 	  	        V  +dS )rV   N)r   rE   )
.0seedr,   r2   r/   r0   r-   r.   r4   r1   s
     rD   	<genexpr>zsmacof.<locals>.<genexpr>r  su       G
 G
  $GN##)!!"3
 
 
G
 G
 G
 G
 G
 G
rF   )r   r   r"   hasattrr   asarrayr%   warningswarnr   r#   rE   randintiinfoint32maxr   zipargmin)r,   r-   r.   r/   rL   rM   r0   r1   r2   r3   rN   r4   best_posbest_stressr;   posrA   n_iter_	best_iterseedsresults	positionsn_itersbests   ````  ```  `            rD   smacofro      sd   | "/22O%l33LF"" &J 
V 
@
 
 	
 t[!! z$$$&&{{MDFLM   F&Hk1$$-- 	$ 	$B#1)!)"3
$ 
$ 
$ C "f{&:&:$88::#		$" $$RXbh%7%7%;&$IIF(&#gk12E2EFFF G
 G
 G
 G
 G
 G
 G
 G
 G
 G
 G
 G
 G
 G
 
 
 &)']"	67y  TlT?DM	 %i//$$rF   c                   F    e Zd ZU dZ eeddd          gdg eeddd          g eeddd          gdg eeddd          gdegd	g ed
dh          gd edh          gd
Ze	e
d<   	 ddddddddd
dd	dZ fdZddZ ed          dd            Z xZS )MDSaf  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.

    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-3
        Relative tolerance with respect to stress at which to declare
        convergence. The value of `eps` should be tuned separately depending
        on whether or not `normalized_stress` is being used.

    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 use and return normed stress value (Stress-1) instead of raw
        stress calculated by default. Only supported in non-metric MDS.

        .. versionadded:: 1.2

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

    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`, and `metric=False` 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, normalized_stress='auto')
    >>> 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   NrH   rI   rG   r1   g        r3   	euclideanprecomputedrK   )
r.   r-   rL   r0   r1   r2   rM   r3   dissimilarityr4   _parameter_constraintsr   T   r   r   r   )	r-   rL   r0   r1   r2   rM   r3   rt   r4   c       	             || _         |	| _        || _        || _        || _        || _        || _        || _        || _        |
| _	        d S )N)
r.   rt   r-   rL   r0   r2   r1   rM   r3   r4   )selfr.   r-   rL   r0   r1   r2   rM   r3   rt   r4   s              rD   __init__zMDS.__init__$  sT     )* (!2rF   c                 r    t                                                      }| j        dk    |j        _        |S )Nrs   )super__sklearn_tags__rt   
input_tagspairwise)rx   tags	__class__s     rD   r|   zMDS.__sklearn_tags__=  s/    ww''))#'#5#F rF   c                 4    |                      ||           | S )a  
        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.
        )r/   )r$   rx   r8   yr/   s       rD   fitzMDS.fitB  s"    0 	14(((rF   rO   c                    t          | |          }|j        d         |j        d         k    r| j        dk    rt          j        d           | j        dk    r|| _        n| j        dk    rt          |          | _        t          | j        | j        | j	        || j
        | j        | j        | j        | j        | j        d| j                  \  | _        | _        | _        | j        S )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.
        r   r   rs   zThe MDS API has changed. ``fit`` now constructs an dissimilarity matrix from data. To use a custom dissimilarity matrix, set ``dissimilarity='precomputed'``.rr   TrR   )r   r   rt   r]   r^   dissimilarity_matrix_r
   ro   r-   r.   rL   rM   r0   r1   r2   r3   r4   
embedding_stress_rh   r   s       rD   r$   zMDS.fit_transform]  s    2 $""71:##(:m(K(KM3   ..)*D&&;..)<Q)?)?D&6<&;*;;]L*"47
 7
 7
3t| rF   )r   rU   )__name__
__module____qualname____doc__r   r   r   r   ru   dict__annotations__ry   r|   r   r   r$   __classcell__)r   s   @rD   rq   rq     s        H HV "(AtFCCCD+8Haf===>Xh4???@;sD8889"'($*k=%ABBC'VH)=)=>$ $D    3 ! 3 3 3 3 32    
   6 \5555 5 5 655 5 5 5 5rF   rq   )Tr   Nr   r   r   NF) r   r]   numbersr   r   numpyr   joblibr   baser   r   isotonicr	   metricsr
   utilsr   r   r   utils._param_validationr   r   r   utils.parallelr   r   utils.validationr   rE   ro   rq    rF   rD   <module>r      sv     " " " " " " " "     # # # # # # . . . . . . . . ) ) ) ) ) ) ) ) ) ) ) ) D D D D D D D D D D K K K K K K K K K K . . . . . . . . , , , , , ,
 	Q Q Q Qh (>+!(AtFCCCDt$8Haf===>T"Xh4???@;q$v6667'(#'VH)=)=>  #'  ( 	M% M% M% M%# "M%`G G G G G- G G G G GrF   