ó
‡ˆ\c           @   sù   d  Z  d d l 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
 l m Z e d d d d d d d „ Z e d d d d d d d d e d „
 Z d e f d „  ƒ  YZ d S(   s!   
Multi-dimensional Scaling (MDS)
iÿÿÿÿNi   (   t   BaseEstimator(   t   euclidean_distances(   t   check_random_statet   check_arrayt   check_symmetric(   t   Parallel(   t   delayed(   t   effective_n_jobs(   t   IsotonicRegressioni,  i    gü©ñÒMbP?c         C   s×  t  |  d t ƒ}  |  j d } t | ƒ } d t j | ƒ |  j ƒ  }	 |	 |	 d k }
 | d k r | j | | ƒ } | j	 | | f ƒ } n? | j d } | | j d k rÈ t
 d | | f ƒ ‚ n  | } d } t ƒ  } xæt | ƒ D]Ø} t | ƒ } | r|  } nŒ | j ƒ  } | |	 d k } | j |
 | ƒ } | j ƒ  } | | |	 d k <| j	 | | f ƒ } | t j | | d d | d j ƒ  ƒ 9} | j ƒ  | j ƒ  d j ƒ  d } d | | d k <| | } | } | t j t | ƒ ƒ t j t | ƒ ƒ f c | j d d ƒ 7<d | t j | | ƒ } t j | d j d d ƒ ƒ j ƒ  } | d k ryd	 | | f GHn  | d k	 r¸| | | | k  r¸| r±d
 | | f GHn  Pq¸n  | | } qê W| | | d f S(   s‘  Computes multidimensional scaling using SMACOF algorithm

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

    metric : boolean, optional, default: True
        Compute metric or nonmetric SMACOF algorithm.

    n_components : int, optional, 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, shape (n_samples, n_components), optional, 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, optional, default: 300
        Maximum number of iterations of the SMACOF algorithm for a single run.

    verbose : int, optional, default: 0
        Level of verbosity.

    eps : float, optional, default: 1e-3
        Relative tolerance with respect to stress at which to declare
        convergence.

    random_state : int, RandomState instance or None, optional, default: None
        The generator used to initialize the centers.  If int, random_state is
        the seed used by the random number generator; If RandomState instance,
        random_state is the random number generator; If None, the random number
        generator is the RandomState instance used by `np.random`.

    Returns
    -------
    X : ndarray, 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   raise_exceptioni    i   s'   init matrix should be of shape (%d, %d)i   gñhãˆµøä>t   axisg      ð?s   it: %d, stress %ss'   breaking at iteration %d with stress %sN(   R   t   Truet   shapeR   t   npt   trit   ravelt   Nonet   randt   reshapet
   ValueErrorR   t   rangeR   t   fit_transformt   copyt   sqrtt   sumt   aranget   lent   dot(   t   dissimilaritiest   metrict   n_componentst   initt   max_itert   verboset   epst   random_statet	   n_samplest   sim_flatt
   sim_flat_wt   Xt
   old_stresst   irt   itt   dist   disparitiest   dis_flatt
   dis_flat_wt   disparities_flatt   stresst   ratiot   B(    (    s3   lib/python2.7/site-packages/sklearn/manifold/mds.pyt   _smacof_single   sX    2		$
@%i   c            sà  t  ˆ  ƒ ‰  t |	 ƒ }	 t ˆ d ƒ re t j ˆ ƒ j ƒ  ‰ | d k se t j d | ƒ d } qe n  d \ } } t	 | ƒ d k rx9t
 | ƒ D]x } t ˆ  d ˆ d ˆ d ˆ d ˆ d ˆ d	 ˆ d
 |	 ƒ\ } } } | d k sí | | k  r | } | j ƒ  } | } q q Wn° |	 j t j t j ƒ j d | ƒ} t d | d t ˆ d d ƒ ƒ ‡  ‡ ‡ ‡ ‡ ‡ ‡ f d †  | Dƒ ƒ } t | Œ  \ } } } t j | ƒ } | | } | | } | | } |
 rÒ| | | f S| | f Sd S(   sŠ  Computes 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 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, shape (n_samples, n_samples)
        Pairwise dissimilarities between the points. Must be symmetric.

    metric : boolean, optional, default: True
        Compute metric or nonmetric SMACOF algorithm.

    n_components : int, optional, 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, shape (n_samples, n_components), optional, 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, optional, 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 or None, optional (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, optional, default: 300
        Maximum number of iterations of the SMACOF algorithm for a single run.

    verbose : int, optional, default: 0
        Level of verbosity.

    eps : float, optional, default: 1e-3
        Relative tolerance with respect to stress at which to declare
        convergence.

    random_state : int, RandomState instance or None, optional, default: None
        The generator used to initialize the centers.  If int, random_state is
        the seed used by the random number generator; If RandomState instance,
        random_state is the random number generator; If None, the random number
        generator is the RandomState instance used by `np.random`.

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

    Returns
    -------
    X : ndarray, 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)
    t	   __array__i   sT   Explicit initial positions passed: performing only one init of the MDS instead of %dR   R   R   R    R!   R"   R#   t   sizet   n_jobsi    c         3   sK   |  ]A } t  t ƒ ˆ  d  ˆ d ˆ d ˆ d ˆ d ˆ d ˆ d | ƒVq d S(   R   R   R   R    R!   R"   R#   N(   R   R3   (   t   .0t   seed(   R   R"   R   R    R   R   R!   (    s3   lib/python2.7/site-packages/sklearn/manifold/mds.pys	   <genexpr>  s   N(   NN(   R   R   t   hasattrR   t   asarrayR   t   warningst   warnR   R   R   R3   t   randintt   iinfot   int32t   maxR   t   zipt   argmin(   R   R   R   R   t   n_initR6   R    R!   R"   R#   t   return_n_itert   best_post   best_stressR*   t   posR0   t   n_iter_t	   best_itert   seedst   resultst	   positionst   n_iterst   best(    (   R   R"   R   R    R   R   R!   s3   lib/python2.7/site-packages/sklearn/manifold/mds.pyt   smacof‡   sB    c$


t   MDSc        
   B   s_   e  Z d  Z d e d d d d d d d d „	 Z e d „  ƒ Z d d d	 „ Z d d d
 „ Z	 RS(   s+  Multidimensional scaling

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

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

    metric : boolean, optional, default: True
        If ``True``, perform metric MDS; otherwise, perform nonmetric MDS.

    n_init : int, optional, 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, optional, default: 300
        Maximum number of iterations of the SMACOF algorithm for a single run.

    verbose : int, optional, default: 0
        Level of verbosity.

    eps : float, optional, default: 1e-3
        Relative tolerance with respect to stress at which to declare
        convergence.

    n_jobs : int or None, optional (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, optional, default: None
        The generator used to initialize the centers.  If int, random_state is
        the seed used by the random number generator; If RandomState instance,
        random_state is the random number generator; If None, the random number
        generator is the RandomState instance used by `np.random`.

    dissimilarity : 'euclidean' | 'precomputed', optional, 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_ : array-like, 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).

    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)

    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)

    i   i   i,  i    gü©ñÒMbP?t	   euclideanc
   
      C   sU   | |  _  |	 |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ d  S(   N(	   R   t   dissimilarityR   RC   R    R"   R!   R6   R#   (
   t   selfR   R   RC   R    R!   R"   R6   R#   RR   (    (    s3   lib/python2.7/site-packages/sklearn/manifold/mds.pyt   __init__m  s    								c         C   s   |  j  d k S(   Nt   precomputed(   t   kernel(   RS   (    (    s3   lib/python2.7/site-packages/sklearn/manifold/mds.pyt	   _pairwisez  s    c         C   s   |  j  | d | ƒ|  S(   sF  
        Computes the position of the points in the embedding space

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

        y : Ignored

        init : ndarray, shape (n_samples,), optional, default: None
            Starting configuration of the embedding to initialize the SMACOF
            algorithm. By default, the algorithm is initialized with a randomly
            chosen array.
        R   (   R   (   RS   R'   t   yR   (    (    s3   lib/python2.7/site-packages/sklearn/manifold/mds.pyt   fit~  s    c         C   s  t  | ƒ } | j d | j d k rE |  j d k rE t j d ƒ n  |  j d k r` | |  _ n: |  j d k r t | ƒ |  _ n t d t |  j ƒ ƒ ‚ t	 |  j d |  j
 d |  j d	 | d
 |  j d |  j d |  j d |  j d |  j d |  j d t ƒ
\ |  _ |  _ |  _ |  j S(   sE  
        Fit the data from X, and returns the embedded coordinates

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

        y : Ignored

        init : ndarray, shape (n_samples,), optional, default: None
            Starting configuration of the embedding to initialize the SMACOF
            algorithm. By default, the algorithm is initialized with a randomly
            chosen array.
        i    i   RU   s   The MDS API has changed. ``fit`` now constructs an dissimilarity matrix from data. To use a custom dissimilarity matrix, set ``dissimilarity='precomputed'``.RQ   s>   Proximity must be 'precomputed' or 'euclidean'. Got %s insteadR   R   R   RC   R6   R    R!   R"   R#   RD   (   R   R   RR   R;   R<   t   dissimilarity_matrix_R   R   t   strRO   R   R   RC   R6   R    R!   R"   R#   R   t
   embedding_t   stress_RH   (   RS   R'   RX   R   (    (    s3   lib/python2.7/site-packages/sklearn/manifold/mds.pyR   ’  s     )N(
   t   __name__t
   __module__t   __doc__R   R   RT   t   propertyRW   RY   R   (    (    (    s3   lib/python2.7/site-packages/sklearn/manifold/mds.pyRP     s   U	(   R`   t   numpyR   R;   t   baseR    t   metricsR   t   utilsR   R   R   t   utils._joblibR   R   R   t   isotonicR   R   R   R3   t   FalseRO   RP   (    (    (    s3   lib/python2.7/site-packages/sklearn/manifold/mds.pyt   <module>   s   	qŽ