`L iedZddlZddlmZmZddlZddlmZddl m Z m Z ddl m Z ddlmZdd lmZmZmZdd lmZmZmZdd lmZmZdd lmZ d!dZedgdgeedddgddgeedddedhgedgeedddgdgeedddgdgdgdedhgd d d ddddddddddd dZGdd e Zy)"z" Multi-dimensional Scaling (MDS). N)IntegralReal)effective_n_jobs) BaseEstimator _fit_context)IsotonicRegression)euclidean_distances) check_arraycheck_random_statecheck_symmetric)Interval StrOptionsvalidate_params)Paralleldelayed) validate_dataT,ư>Fc t|d}|jd} t|}dtj| z |zj } | | dk7} |)|j | |z} | j| |f} n3|jd}| |jdk7rtd| |fz|} t| } td }d}t|D]}|r|}n| j }|| dk7}|dkr| }n|j| |}tj|}||| dk7<|j| | f}|tj| | dz zd z |d zjz z}||j z}d | | dk(<|| z }| }|tj"t%|tj"t%|fxx|jd z cc<d | z tj&|| z} t| } | j |j z d zjd z }|d k\rt)d|d|d|>| j d zj}||z |d z z |kr|r t)dn|}|r<| j d zj}tj|d z z }| dzfS)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 `. 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_exceptionrNsizez'init matrix should be of shape (%d, %d)clip) out_of_boundsrgh㈵>)axisg?z Iteration z , stress z.4fzConvergence criterion reached.)r shaper nptriraveluniformreshape ValueErrorr r range fit_transform zeros_likesqrtsumTarangelendotprint)dissimilaritiesmetric n_componentsinitmax_iterverboseeps random_statenormalized_stress n_samplesdissimilarities_flatdissimilarities_flat_wX distancesir old_stressit disparitiesdistances_flatdistances_flat_wdisparities_flatratioBstresssum_squared_distancess [/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/manifold/_mds.py_smacof_singlerIs'n&otLO%%a(I%l3L !22oELLN12F!2KL |  i,&> ? IIy,/ 0zz!}  1 %9Y )BCsJ:; ].`!*!2a!7 < < >#81#<=> fb1f z array-likebooleanrleftclosedwarnr4r6auto) r/r0r1r2n_initn_jobsr3r4r5r6 return_n_iterr7prefer_skip_nested_validation r0r1r2rQrRr3r4r5r6rSr7c . |dk(rtjdtd}tt | } dk(r t drBt jj|dk(stjd|zd}d\} } t|dk(rEt|D]6}t| \}}}| || ks#|} |j} |}8n| jt jt jj| }t!|tdz d   fd |D}t#|\}}}t j$|}||} ||} ||}| r| | fS| | fS)aCompute 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 ` 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 `. 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 rOz=The default value of `n_init` will change from 8 to 1 in 1.9.rP __array__rzTExplicit initial positions passed: performing only one init of the MDS instead of %dNNr0r1r2r3r4r5r6r7rr)rRr4c 3ZK|]"}tt | $yw)r[N)rrI) .0seedr/r5r2r3r0r1r7r4s rH zsmacof..sI G  $GN #)!!"3   G s(+)warningsrO FutureWarningr r hasattrrasarraycopyrr%rIrandintiinfoint32maxrzipargmin)r/r0r1r2rQrRr3r4r5r6rSr7best_pos best_stressr?posrFn_iter_ best_iterseedsresults positionsn_itersbests```` ``` ` rHsmacofrusP K  !/2O%l3LF" &Jt[!zz$$$&{ MMDFLM F&Hk1$- $B#1)!)"3 $ C"f{&:$ 88:#  $"$$RXXbhh%7%;%;&$IF(&#gk12EF G G  G  &)']" 67yy Tl T?DM i//$$rJc &eZdZUdZeedddgdgeedddedhgeedddgdgeed ddgdegd ged d hgded hgd Ze e d< ddddddddd d d dZ fdZ ddZ edddZxZS)MDSaMultidimensional scaling. Read more in the :ref:`User Guide `. 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 ` 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 `. 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`. rNrLrMrKrOr4gr6 euclidean precomputedrP) r1r0rQr3r4r5rRr6 dissimilarityr7_parameter_constraintsTrrr) r0rQr3r4r5rRr6rzr7c ||_| |_||_||_||_||_||_||_||_| |_ y)N) r1rzr0rQr3r5r4rRr6r7) selfr1r0rQr3r4r5rRr6rzr7s rH__init__z MDS.__init__QsN)*      (!2rJc`t|}|jdk(|j_|S)Nry)super__sklearn_tags__rz input_tagspairwise)r}tags __class__s rHrzMDS.__sklearn_tags__js,w')#'#5#5#F  rJc,|j|||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. )r2)r&r}r;yr2s rHfitzMDS.fitos0 14( rJrTc|jdk(r"tjdtd|_n|j|_t ||}|j d|j dk(r$|jdk7rtjd|jdk(r||_n|jdk(rt||_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. rOz=The default value of `n_init` will change from 4 to 1 in 1.9.rrryzThe MDS API has changed. ``fit`` now constructs a dissimilarity matrix from data. To use a custom dissimilarity matrix, set ``dissimilarity='precomputed'``.rxTrV)rQr`rOra_n_initrrrzdissimilarity_matrix_r rur0r1rRr3r4r5r6r7 embedding_stress_rnrs rHr&zMDS.fit_transforms"4 ;;& MMO DL;;DL $ " 771: #(:(:m(K MM3     .)*D &   ; .) $D 3 ! 32 65?6?rJrw)TrNrrrNF) rr`numbersrrnumpyrjoblibrbaserrisotonicr metricsr utilsr r r utils._param_validationrrrutils.parallelrrutils.validationrrIrurwrJrHrs1"#.))DDKK.,    fT(>+!(AtFCDt$Haf=z6(?STT"h4?@;q$v67'(#'VH)=> #'(      Y%#"Y%z[-[rJ