B
    0d!I                 @   s   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
 ddlmZmZmZ ddlmZ dd	lmZ dd
lmZ dddZddddddddddd
ddZG dd deZdS )z"
Multi-dimensional Scaling (MDS).
    N)Paralleleffective_n_jobs   )BaseEstimator)euclidean_distances)check_random_statecheck_arraycheck_symmetric)IsotonicRegression)
deprecated)delayedT,  MbP?c             C   s$  t | dd} | jd }t|}dt| |   }	|	|	dk }
|dkrf||| }|||f}n,|jd }||jd krtd||f |}d}t	 }xvt
|D ]h}t|}|r| }nh| }||	dk }||
|}| }|||	dk< |||f}|t||d  d |d   9 }| |  d  d }d||dk< || }| }|tt|tt|f  |jdd	7  < d
| t|| }t|d jdd	 }|dkrtd||f  |dk	r
|||  |k r
|rtd||f  P || }qW |||d fS )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.

    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.

    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>`.

    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).

    n_iter : int
        The number of iterations corresponding to the best stress.
    T)Zraise_exceptionr      Nz'init matrix should be of shape (%d, %d)r   gh㈵>)Zaxisg      ?zit: %d, stress %sz'breaking at iteration %d with stress %s)r	   shaper   npZtriZravelZrandZreshape
ValueErrorr
   ranger   fit_transformcopysqrtsumZarangelendotprint)dissimilaritiesmetricn_componentsinitmax_iterverboseepsrandom_stateZ	n_samplesZsim_flatZ
sim_flat_wXZ
old_stressZiritdisZdisparitiesZdis_flatZ
dis_flat_wZdisparities_flatstressratioB r)   G/var/www/html/venv/lib/python3.7/site-packages/sklearn/manifold/_mds.py_smacof_single   sV    9

 0

r+      F)
r   r   r   n_initn_jobsr   r    r!   r"   return_n_iterc   
            s@  t   t|	}	tdrBt |dksBtd|  d}d\}}t|dkrxt	|D ]B}t
 |	d\}}}|dks||k r`|}| }|}q`W n||	jttjj|d}t|td dd	 fd
d|D }t| \}}}t|}|| }|| }|| }|
r4|||fS ||fS d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 : 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.

    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.

    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.

    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.

    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).

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

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

    "Nonmetric multidimensional scaling: a numerical method" Kruskal, J.
    Psychometrika, 29 (1964)

    "Multidimensional scaling by optimizing goodness of fit to a nonmetric
    hypothesis" Kruskal, J. Psychometrika, 29, (1964)
    Z	__array__r   zTExplicit initial positions passed: performing only one init of the MDS instead of %d)NN)r   r   r   r   r    r!   r"   N)sizer   )r.   r    c             3   s*   | ]"}t t |d V  qdS ))r   r   r   r   r    r!   r"   N)r   r+   ).0seed)r   r!   r   r   r   r   r    r)   r*   	<genexpr>  s   
zsmacof.<locals>.<genexpr>)r   r   hasattrr   Zasarrayr   warningswarnr   r   r+   randintZiinfoZint32maxr   zipZargmin)r   r   r   r   r-   r.   r   r    r!   r"   r/   Zbest_posZbest_stressr$   posr&   n_iter_Z	best_iterZseedsresultsZ	positionsZn_itersbestr)   )r   r!   r   r   r   r   r    r*   smacof   sJ    n





r>   c            
   @   s^   e Zd ZdZddddddddd	d
ddZdd Zededd ZdddZ	dddZ
dS )MDSaQ  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.

    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.

    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``.

    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).

    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
    ----------
    "Modern Multidimensional Scaling - Theory and Applications" Borg, I.;
    Groenen P. Springer Series in Statistics (1997)

    "Nonmetric multidimensional scaling: a numerical method" Kruskal, J.
    Psychometrika, 29 (1964)

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

    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)
    >>> X_transformed = embedding.fit_transform(X[:100])
    >>> X_transformed.shape
    (100, 2)
    r   T   i,  r   gMbP?N	euclidean)r   r-   r   r    r!   r.   r"   dissimilarityc      
      C   s:   || _ |	| _|| _|| _|| _|| _|| _|| _|| _d S )N)	r   rB   r   r-   r   r!   r    r.   r"   )
selfr   r   r-   r   r    r!   r.   r"   rB   r)   r)   r*   __init__  s    zMDS.__init__c             C   s   d| j dkiS )Npairwiseprecomputed)rB   )rC   r)   r)   r*   
_more_tags  s    zMDS._more_tagszcAttribute `_pairwise` was deprecated in version 0.24 and will be removed in 1.1 (renaming of 0.26).c             C   s
   | j dkS )NrF   )rB   )rC   r)   r)   r*   	_pairwise  s    zMDS._pairwisec             C   s   | j ||d | 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,), 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   )rC   r#   yr   r)   r)   r*   fit  s    zMDS.fitc             C   s   |  |}|jd |jd kr2| jdkr2td | jdkrD|| _n(| jdkrZt|| _ntdt| j t	| j| j
| j|| j| j| j| j| j| jdd\| _| _| _| 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,), 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   rF   zThe MDS API has changed. ``fit`` now constructs an dissimilarity matrix from data. To use a custom dissimilarity matrix, set ``dissimilarity='precomputed'``.rA   z>Proximity must be 'precomputed' or 'euclidean'. Got %s insteadT)
r   r   r   r-   r.   r   r    r!   r"   r/   )Z_validate_datar   rB   r5   r6   Zdissimilarity_matrix_r   r   strr>   r   r   r-   r.   r   r    r!   r"   Z
embedding_Zstress_r;   )rC   r#   rI   r   r)   r)   r*   r     s0    


zMDS.fit_transform)r   )NN)NN)__name__
__module____qualname____doc__rD   rG   r   propertyrH   rJ   r   r)   r)   r)   r*   r?   6  s    t
r?   )Tr   Nr   r   r   N)rO   numpyr   Zjoblibr   r   r5   baser   Zmetricsr   utilsr   r   r	   Zisotonicr
   Zutils.deprecationr   Zutils.fixesr   r+   r>   r?   r)   r)   r)   r*   <module>   s8         
u 