
    0Ph              
          d dl Z d dlmZmZ d dlmZ d dlZd dlmZ d dl	m
Z
mZ d dlmZmZ ddlmZmZmZm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 ddlm Z m!Z!m"Z"m#Z# ddl$m%Z%m&Z&m'Z' ddl(m)Z)m*Z*  ej+        ej,                  j-        Z.d Z/d Z0	 	 d,dZ1	 	 	 	 	 d-dZ2	 	 	 	 	 	 	 	 	 d.dZ3 e#dd gdd g e!eddd!"          g e" e4e          d#hz            e5gd$d%          d&d'd(d)            Z6 G d* d+eee          Z7dS )/    N)IntegralReal)time)linalg)
csr_matrixissparse)pdist
squareform   )BaseEstimatorClassNamePrefixFeaturesOutMixinTransformerMixin_fit_context)PCA)_VALID_METRICSpairwise_distances)NearestNeighbors)check_random_state)_openmp_effective_n_threads)HiddenInterval
StrOptionsvalidate_params)_num_samplescheck_non_negativevalidate_data   )_barnes_hut_tsne_utilsc                 4   |                      t          j        d          } t          j        | ||          }||j        z   }t          j        t          j        |          t                    }t          j        t          |          |z  t                    }|S )aT  Compute joint probabilities p_ij from distances.

    Parameters
    ----------
    distances : ndarray of shape (n_samples * (n_samples-1) / 2,)
        Distances of samples are stored as condensed matrices, i.e.
        we omit the diagonal and duplicate entries and store everything
        in a one-dimensional array.

    desired_perplexity : float
        Desired perplexity of the joint probability distributions.

    verbose : int
        Verbosity level.

    Returns
    -------
    P : ndarray of shape (n_samples * (n_samples-1) / 2,)
        Condensed joint probability matrix.
    Fcopy)
astypenpfloat32r   _binary_search_perplexityTmaximumsumMACHINE_EPSILONr
   )	distancesdesired_perplexityverboseconditional_PPsum_Ps         W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/manifold/_t_sne.py_joint_probabilitiesr2   '   s    .   % 88I4%w M 	'AJrvayy/22E

:a==5(/::AH    c                    t                      }|                                  | j        d         }| j                            |d          }|                    t          j        d          }t          j	        |||          }t          j
        t          j        |                    s
J d            t          |                                | j        | j        f||f          }||j        z   }t          j        |                                t&                    }||z  }t          j
        t          j        |j                  dk              sJ |dk    r3t                      |z
  }	t+          d	                    |	                     |S )
ax  Compute joint probabilities p_ij from distances using just nearest
    neighbors.

    This method is approximately equal to _joint_probabilities. The latter
    is O(N), but limiting the joint probability to nearest neighbors improves
    this substantially to O(uN).

    Parameters
    ----------
    distances : sparse matrix of shape (n_samples, n_samples)
        Distances of samples to its n_neighbors nearest neighbors. All other
        distances are left to zero (and are not materialized in memory).
        Matrix should be of CSR format.

    desired_perplexity : float
        Desired perplexity of the joint probability distributions.

    verbose : int
        Verbosity level.

    Returns
    -------
    P : sparse matrix of shape (n_samples, n_samples)
        Condensed joint probability matrix with only nearest neighbors. Matrix
        will be of CSR format.
    r   Fr!   "All probabilities should be finite)shape      ?r   z5[t-SNE] Computed conditional probabilities in {:.3f}s)r   sort_indicesr7   datareshaper#   r$   r%   r   r&   allisfiniter   ravelindicesindptrr'   r(   r)   r*   absprintformat)
r+   r,   r-   t0	n_samplesdistances_datar.   r/   r0   durations
             r1   _joint_probabilities_nnrH   H   sk   6 
B "I^++Ir::N#**2:E*BBN4*G M 6"+m,,--SS/SSSS 							 193CD)$	 	 	A 	
ACA Jquuww00EJA6"&..C'(((((!||66B;ELLXVVWWWHr3   Tc           
         |                      ||          }t          |d          }||z  }|dz  }||dz   dz  z  }t          j        |dt          j        |          z  z  t
                    }	|rFdt          j        |t          j        t          j        |t
                    |	z                      z  }
nt          j        }
t          j	        ||f| j
                  }t          ||	z
  |z            }t          ||          D ]=}t          j        t          j        ||         d          ||         |z
            ||<   >|                                }d|dz   z  |z  }||z  }|
|fS )aZ  t-SNE objective function: gradient of the KL divergence
    of p_ijs and q_ijs and the absolute error.

    Parameters
    ----------
    params : ndarray of shape (n_params,)
        Unraveled embedding.

    P : ndarray of shape (n_samples * (n_samples-1) / 2,)
        Condensed joint probability matrix.

    degrees_of_freedom : int
        Degrees of freedom of the Student's-t distribution.

    n_samples : int
        Number of samples.

    n_components : int
        Dimension of the embedded space.

    skip_num_points : int, default=0
        This does not compute the gradient for points with indices below
        `skip_num_points`. This is useful when computing transforms of new
        data where you'd like to keep the old data fixed.

    compute_error: bool, default=True
        If False, the kl_divergence is not computed and returns NaN.

    Returns
    -------
    kl_divergence : float
        Kullback-Leibler divergence of p_ij and q_ij.

    grad : ndarray of shape (n_params,)
        Unraveled gradient of the Kullback-Leibler divergence with respect to
        the embedding.
    sqeuclideanr8   g              @dtypeK)order)r;   r	   r$   r(   r)   r*   dotlognanndarrayrM   r
   ranger>   )paramsr/   degrees_of_freedomrE   n_componentsskip_num_pointscompute_error
X_embeddeddistQkl_divergencegradPQdics                  r1   _kl_divergencerb      sq   \ 	<88J ]++DDCKD 3&$..D

43-.@@A  bfQrz!_/M/MPQ/Q(R(RSSS :y,/v|DDDD
a!et^
$
$C?I.. R R&#a&444jmj6PQQQ::<<D!C'(+==AAID$r3         ?Fc
                 ,   |                      t          j        d          } |                     ||          }
|j                             t          j        d          }|j                             t          j        d          }|j                             t          j        d          }t          j        |
j	        t          j                  }t          j        ||
|||||||||	          }d|dz   z  |z  }|                                }||z  }||fS )a$  t-SNE objective function: KL divergence of p_ijs and q_ijs.

    Uses Barnes-Hut tree methods to calculate the gradient that
    runs in O(NlogN) instead of O(N^2).

    Parameters
    ----------
    params : ndarray of shape (n_params,)
        Unraveled embedding.

    P : sparse matrix of shape (n_samples, n_sample)
        Sparse approximate joint probability matrix, computed only for the
        k nearest-neighbors and symmetrized. Matrix should be of CSR format.

    degrees_of_freedom : int
        Degrees of freedom of the Student's-t distribution.

    n_samples : int
        Number of samples.

    n_components : int
        Dimension of the embedded space.

    angle : float, default=0.5
        This is the trade-off between speed and accuracy for Barnes-Hut T-SNE.
        'angle' is the angular size (referred to as theta in [3]) of a distant
        node as measured from a point. If this size is below 'angle' then it is
        used as a summary node of all points contained within it.
        This method is not very sensitive to changes in this parameter
        in the range of 0.2 - 0.8. Angle less than 0.2 has quickly increasing
        computation time and angle greater 0.8 has quickly increasing error.

    skip_num_points : int, default=0
        This does not compute the gradient for points with indices below
        `skip_num_points`. This is useful when computing transforms of new
        data where you'd like to keep the old data fixed.

    verbose : int, default=False
        Verbosity level.

    compute_error: bool, default=True
        If False, the kl_divergence is not computed and returns NaN.

    num_threads : int, default=1
        Number of threads used to compute the gradient. This is set here to
        avoid calling _openmp_effective_n_threads for each gradient step.

    Returns
    -------
    kl_divergence : float
        Kullback-Leibler divergence of p_ij and q_ij.

    grad : ndarray of shape (n_params,)
        Unraveled gradient of the Kullback-Leibler divergence with respect to
        the embedding.
    Fr!   rL   )dofrY   num_threadsrK   r8   )r#   r$   r%   r;   r:   r?   int64r@   zerosr7   r   gradientr>   )rU   r/   rV   rE   rW   anglerX   r-   rY   rf   rZ   val_P	neighborsr@   r^   errorra   s                    r1   _kl_divergence_bhrn      s   H ]]2:E]22F	<88JFMM"*5M11E	   66IX__RXE_22F8J$BJ777D%#  E 	!C'(+==A::<<DAID$;r3   ,  皙?      i@{Gz?Hz>c           	         |g }|i }|                                                                 }t          j        |          }t          j        |          }t          j        t                    j        }t          j        t                    j        }|x}}t                      }t          ||          D ]C}|dz   |z  dk    }|p||dz
  k    |d<    | |g|R i |\  }}||z  dk     }t          j
        |          }||xx         dz  cc<   ||xx         dz  cc<   t          j        ||t          j        |           ||z  }||z  ||z  z
  }||z  }|rt                      }||z
  }|}t          j        |          }|
d	k    rt          d
|dz   ||||fz             ||k     r|}|}n(||z
  |k    r|
d	k    rt          d|dz   |fz              n'||	k    r|
d	k    rt          d|dz   |fz              nE|||fS )aA  Batch gradient descent with momentum and individual gains.

    Parameters
    ----------
    objective : callable
        Should return a tuple of cost and gradient for a given parameter
        vector. When expensive to compute, the cost can optionally
        be None and can be computed every n_iter_check steps using
        the objective_error function.

    p0 : array-like of shape (n_params,)
        Initial parameter vector.

    it : int
        Current number of iterations (this function will be called more than
        once during the optimization).

    max_iter : int
        Maximum number of gradient descent iterations.

    n_iter_check : int, default=1
        Number of iterations before evaluating the global error. If the error
        is sufficiently low, we abort the optimization.

    n_iter_without_progress : int, default=300
        Maximum number of iterations without progress before we abort the
        optimization.

    momentum : float within (0.0, 1.0), default=0.8
        The momentum generates a weight for previous gradients that decays
        exponentially.

    learning_rate : float, default=200.0
        The learning rate for t-SNE is usually in the range [10.0, 1000.0]. If
        the learning rate is too high, the data may look like a 'ball' with any
        point approximately equidistant from its nearest neighbours. If the
        learning rate is too low, most points may look compressed in a dense
        cloud with few outliers.

    min_gain : float, default=0.01
        Minimum individual gain for each parameter.

    min_grad_norm : float, default=1e-7
        If the gradient norm is below this threshold, the optimization will
        be aborted.

    verbose : int, default=0
        Verbosity level.

    args : sequence, default=None
        Arguments to pass to objective function.

    kwargs : dict, default=None
        Keyword arguments to pass to objective function.

    Returns
    -------
    p : ndarray of shape (n_params,)
        Optimum parameters.

    error : float
        Optimum.

    i : int
        Last iteration.
    Nr   r   rY   g        g?rp   )outr   zR[t-SNE] Iteration %d: error = %.7f, gradient norm = %.7f (%s iterations in %0.3fs)zV[t-SNE] Iteration %d: did not make any progress during the last %d episodes. Finished.z1[t-SNE] Iteration %d: gradient norm %f. Finished.)r"   r>   r$   
zeros_like	ones_likefinfofloatmaxr   rT   invertclipinfr   normrB   )	objectivep0itmax_itern_iter_checkn_iter_without_progressmomentumlearning_ratemin_gainmin_grad_normr-   argskwargspupdategainsrm   
best_error	best_iterr`   ticcheck_convergencer^   incdectocrG   	grad_norms                               r1   _gradient_descentr   .  s   b |~
		A]1FLOOEHUOOE%$JI
&&C2x   / /Ul2a7"3"HqHqL7Hi3D333F33ttmc!innc


c


c


c



xU3333F"]T%99	V 	&&CSyHCD))I!||1 1ueYhGH   z!!"
		Y!888a<<Aq5"9:;  
 M))a<<Kq5),-   eQ;r3   z
array-likezsparse matrixleftclosedprecomputed)XrZ   n_neighborsmetricprefer_skip_nested_validation   	euclidean)r   r   c                   t          |           }||dz  k    rt          d| d|dz   d          t          | |          }|dk    r|                                }t	          j        |t          j                   t	          j        |d          }t          |	          	                    |          
                    d
          }t	          j        ||ft                    }t	          j        |dz             }	|	dd         ||	ddt          j        f         |f<   ||	ddt          j        f         |f         |z
  }
t	          j        |
|
dk                       }d|d||z  d|z  d|z  z
  dz
  z  z  z  z
  }|S )a  Indicate to what extent the local structure is retained.

    The trustworthiness is within [0, 1]. It is defined as

    .. math::

        T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1}
            \sum_{j \in \mathcal{N}_{i}^{k}} \max(0, (r(i, j) - k))

    where for each sample i, :math:`\mathcal{N}_{i}^{k}` are its k nearest
    neighbors in the output space, and every sample j is its :math:`r(i, j)`-th
    nearest neighbor in the input space. In other words, any unexpected nearest
    neighbors in the output space are penalised in proportion to their rank in
    the input space.

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
        (n_samples, n_samples)
        If the metric is 'precomputed' X must be a square distance
        matrix. Otherwise it contains a sample per row.

    X_embedded : {array-like, sparse matrix} of shape (n_samples, n_components)
        Embedding of the training data in low-dimensional space.

    n_neighbors : int, default=5
        The number of neighbors that will be considered. Should be fewer than
        `n_samples / 2` to ensure the trustworthiness to lies within [0, 1], as
        mentioned in [1]_. An error will be raised otherwise.

    metric : str or callable, default='euclidean'
        Which metric to use for computing pairwise distances between samples
        from the original input space. If metric is 'precomputed', X must be a
        matrix of pairwise distances or squared distances. Otherwise, for a list
        of available metrics, see the documentation of argument metric in
        `sklearn.pairwise.pairwise_distances` and metrics listed in
        `sklearn.metrics.pairwise.PAIRWISE_DISTANCE_FUNCTIONS`. Note that the
        "cosine" metric uses :func:`~sklearn.metrics.pairwise.cosine_distances`.

        .. versionadded:: 0.20

    Returns
    -------
    trustworthiness : float
        Trustworthiness of the low-dimensional embedding.

    References
    ----------
    .. [1] Jarkko Venna and Samuel Kaski. 2001. Neighborhood
           Preservation in Nonlinear Projection Methods: An Experimental Study.
           In Proceedings of the International Conference on Artificial Neural Networks
           (ICANN '01). Springer-Verlag, Berlin, Heidelberg, 485-491.

    .. [2] Laurens van der Maaten. Learning a Parametric Embedding by Preserving
           Local Structure. Proceedings of the Twelfth International Conference on
           Artificial Intelligence and Statistics, PMLR 5:384-391, 2009.

    Examples
    --------
    >>> from sklearn.datasets import make_blobs
    >>> from sklearn.decomposition import PCA
    >>> from sklearn.manifold import trustworthiness
    >>> X, _ = make_blobs(n_samples=100, n_features=10, centers=3, random_state=42)
    >>> X_embedded = PCA(n_components=2).fit_transform(X)
    >>> print(f"{trustworthiness(X, X_embedded, n_neighbors=5):.2f}")
    0.92
    r   zn_neighbors (z%) should be less than n_samples / 2 ())r   r   r   )axis)r   F)return_distancerL   Nr5   r   r8   rK         @)r   
ValueErrorr   r"   r$   fill_diagonalr}   argsortr   fit
kneighborsrh   intarangenewaxisr)   )r   rZ   r   r   rE   dist_Xind_Xind_X_embeddedinverted_indexordered_indicesranksts               r1   trustworthinessr     s   Z QIi!m##"K " "Q" " "
 
 	
  &111F VRV$$$JvA&&&E 	[111	Z	E	*	*  Xy)4C@@@Ni	A..O>Mabb>QN?3B3
?3U:;ssBJ7GH;V 
 	uUQY  Aay;&#	/C+<M*MPS*STU 	A Hr3   c                       e Zd ZU dZi d eeddd          gd eeddd	          gd
 eeddd          gd edh           eeddd	          gd eeddd          dgd eeddd          gd eeddd          gd e ee	          dhz            e
gdedgd eddh          ej        gddgddgd eddh          gd eeddd          gddegd  eeddd           e ed!h                    gZeed"<   dZd#Z	 d6d%d&ddd'd(d)dddddd*dd!d+d,Zd- Zd7d.Z	 	 d8d/Z ed01          d9d2            Z ed01          d9d3            Zed4             Z fd5Z xZS ):TSNEa'  T-distributed Stochastic Neighbor Embedding.

    t-SNE [1] is a tool to visualize high-dimensional data. It converts
    similarities between data points to joint probabilities and tries
    to minimize the Kullback-Leibler divergence between the joint
    probabilities of the low-dimensional embedding and the
    high-dimensional data. t-SNE has a cost function that is not convex,
    i.e. with different initializations we can get different results.

    It is highly recommended to use another dimensionality reduction
    method (e.g. PCA for dense data or TruncatedSVD for sparse data)
    to reduce the number of dimensions to a reasonable amount (e.g. 50)
    if the number of features is very high. This will suppress some
    noise and speed up the computation of pairwise distances between
    samples. For more tips see Laurens van der Maaten's FAQ [2].

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

    Parameters
    ----------
    n_components : int, default=2
        Dimension of the embedded space.

    perplexity : float, default=30.0
        The perplexity is related to the number of nearest neighbors that
        is used in other manifold learning algorithms. Larger datasets
        usually require a larger perplexity. Consider selecting a value
        between 5 and 50. Different values can result in significantly
        different results. The perplexity must be less than the number
        of samples.

    early_exaggeration : float, default=12.0
        Controls how tight natural clusters in the original space are in
        the embedded space and how much space will be between them. For
        larger values, the space between natural clusters will be larger
        in the embedded space. Again, the choice of this parameter is not
        very critical. If the cost function increases during initial
        optimization, the early exaggeration factor or the learning rate
        might be too high.

    learning_rate : float or "auto", default="auto"
        The learning rate for t-SNE is usually in the range [10.0, 1000.0]. If
        the learning rate is too high, the data may look like a 'ball' with any
        point approximately equidistant from its nearest neighbours. If the
        learning rate is too low, most points may look compressed in a dense
        cloud with few outliers. If the cost function gets stuck in a bad local
        minimum increasing the learning rate may help.
        Note that many other t-SNE implementations (bhtsne, FIt-SNE, openTSNE,
        etc.) use a definition of learning_rate that is 4 times smaller than
        ours. So our learning_rate=200 corresponds to learning_rate=800 in
        those other implementations. The 'auto' option sets the learning_rate
        to `max(N / early_exaggeration / 4, 50)` where N is the sample size,
        following [4] and [5].

        .. versionchanged:: 1.2
           The default value changed to `"auto"`.

    max_iter : int, default=1000
        Maximum number of iterations for the optimization. Should be at
        least 250.

        .. versionchanged:: 1.5
            Parameter name changed from `n_iter` to `max_iter`.

    n_iter_without_progress : int, default=300
        Maximum number of iterations without progress before we abort the
        optimization, used after 250 initial iterations with early
        exaggeration. Note that progress is only checked every 50 iterations so
        this value is rounded to the next multiple of 50.

        .. versionadded:: 0.17
           parameter *n_iter_without_progress* to control stopping criteria.

    min_grad_norm : float, default=1e-7
        If the gradient norm is below this threshold, the optimization will
        be stopped.

    metric : str or callable, default='euclidean'
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string, it must be one of the options
        allowed by scipy.spatial.distance.pdist for its metric parameter, or
        a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS.
        If metric is "precomputed", X is assumed to be a distance matrix.
        Alternatively, if metric is a callable function, it is called on each
        pair of instances (rows) and the resulting value recorded. The callable
        should take two arrays from X as input and return a value indicating
        the distance between them. The default is "euclidean" which is
        interpreted as squared euclidean distance.

    metric_params : dict, default=None
        Additional keyword arguments for the metric function.

        .. versionadded:: 1.1

    init : {"random", "pca"} or ndarray of shape (n_samples, n_components),             default="pca"
        Initialization of embedding.
        PCA initialization cannot be used with precomputed distances and is
        usually more globally stable than random initialization.

        .. versionchanged:: 1.2
           The default value changed to `"pca"`.

    verbose : int, default=0
        Verbosity level.

    random_state : int, RandomState instance or None, default=None
        Determines the random number generator. Pass an int for reproducible
        results across multiple function calls. Note that different
        initializations might result in different local minima of the cost
        function. See :term:`Glossary <random_state>`.

    method : {'barnes_hut', 'exact'}, default='barnes_hut'
        By default the gradient calculation algorithm uses Barnes-Hut
        approximation running in O(NlogN) time. method='exact'
        will run on the slower, but exact, algorithm in O(N^2) time. The
        exact algorithm should be used when nearest-neighbor errors need
        to be better than 3%. However, the exact method cannot scale to
        millions of examples.

        .. versionadded:: 0.17
           Approximate optimization *method* via the Barnes-Hut.

    angle : float, default=0.5
        Only used if method='barnes_hut'
        This is the trade-off between speed and accuracy for Barnes-Hut T-SNE.
        'angle' is the angular size (referred to as theta in [3]) of a distant
        node as measured from a point. If this size is below 'angle' then it is
        used as a summary node of all points contained within it.
        This method is not very sensitive to changes in this parameter
        in the range of 0.2 - 0.8. Angle less than 0.2 has quickly increasing
        computation time and angle greater 0.8 has quickly increasing error.

    n_jobs : int, default=None
        The number of parallel jobs to run for neighbors search. This parameter
        has no impact when ``metric="precomputed"`` or
        (``metric="euclidean"`` and ``method="exact"``).
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

        .. versionadded:: 0.22

    n_iter : int
        Maximum number of iterations for the optimization. Should be at
        least 250.

        .. deprecated:: 1.5
            `n_iter` was deprecated in version 1.5 and will be removed in 1.7.
            Please use `max_iter` instead.

    Attributes
    ----------
    embedding_ : array-like of shape (n_samples, n_components)
        Stores the embedding vectors.

    kl_divergence_ : float
        Kullback-Leibler divergence after optimization.

    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

    learning_rate_ : float
        Effective learning rate.

        .. versionadded:: 1.2

    n_iter_ : int
        Number of iterations run.

    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.
    MDS : Manifold learning using multidimensional scaling.
    Isomap : Manifold learning based on Isometric Mapping.
    LocallyLinearEmbedding : Manifold learning using Locally Linear Embedding.
    SpectralEmbedding : Spectral embedding for non-linear dimensionality.

    Notes
    -----
    For an example of using :class:`~sklearn.manifold.TSNE` in combination with
    :class:`~sklearn.neighbors.KNeighborsTransformer` see
    :ref:`sphx_glr_auto_examples_neighbors_approximate_nearest_neighbors.py`.

    References
    ----------

    [1] van der Maaten, L.J.P.; Hinton, G.E. Visualizing High-Dimensional Data
        Using t-SNE. Journal of Machine Learning Research 9:2579-2605, 2008.

    [2] van der Maaten, L.J.P. t-Distributed Stochastic Neighbor Embedding
        https://lvdmaaten.github.io/tsne/

    [3] L.J.P. van der Maaten. Accelerating t-SNE using Tree-Based Algorithms.
        Journal of Machine Learning Research 15(Oct):3221-3245, 2014.
        https://lvdmaaten.github.io/publications/papers/JMLR_2014.pdf

    [4] Belkina, A. C., Ciccolella, C. O., Anno, R., Halpert, R., Spidlen, J.,
        & Snyder-Cappione, J. E. (2019). Automated optimized parameters for
        T-distributed stochastic neighbor embedding improve visualization
        and analysis of large datasets. Nature Communications, 10(1), 1-12.

    [5] Kobak, D., & Berens, P. (2019). The art of using t-SNE for single-cell
        transcriptomics. Nature Communications, 10(1), 1-14.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.manifold import TSNE
    >>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
    >>> X_embedded = TSNE(n_components=2, learning_rate='auto',
    ...                   init='random', perplexity=3).fit_transform(X)
    >>> X_embedded.shape
    (4, 2)
    rW   r   Nr   r   
perplexityr   neitherearly_exaggerationr   autor      r   r5   r   r   r   metric_paramsinitpcarandomr-   random_statemethod
barnes_hutexactrj   bothn_jobsn_iter
deprecated_parameter_constraints2   r   g      >@g      (@ro   rs   r   rc   )r   r   r   r   r   r   r   r   r   r-   r   r   rj   r   r   c                    || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        || _
        || _        || _        || _        || _        || _        d S N)rW   r   r   r   r   r   r   r   r   r   r-   r   r   rj   r   r   )selfrW   r   r   r   r   r   r   r   r   r   r-   r   r   rj   r   r   s                    r1   __init__zTSNE.__init__7  s    ( )$"4* '>$**	(
r3   c                 P    | j         |j        d         k    rt          d          d S )Nr   z&perplexity must be less than n_samples)r   r7   r   )r   r   s     r1   _check_params_vs_inputzTSNE._check_params_vs_input\  s,    ?agaj((EFFF )(r3   c                 l   t          | j        t                    r)| j        dk    rt          |          rt	          d          | j        dk    r=|j        d         | j        z  dz  | _        t          j
        | j        d          | _        n| j        | _        | j        dk    r,t          | |dgd	t          j        t          j        g
          }n+t          | |g dt          j        t          j        g          }| j        dk    rt          | j        t                    r| j        dk    rt!          d          |j        d         |j        d         k    rt!          d          t#          |d           | j        dk    rt          |          rt	          d          | j        dk    r| j        dk    rt!          d          t'          | j                  }|j        d         }d}| j        dk    r2| j        dk    r|}n\| j        rt-          d           | j        dk    rt/          || j        d          }n#| j        pi }t/          |f| j        | j        d|}t          j        |dk               rt!          d          | j        dk    r|d	z  }t7          || j        | j                  }t          j        t          j        |                    s
J d            t          j        |dk              s
J d            t          j        |dk              s
J d            n`t?          |dz
  tA          d | j        z  dz                       }	| j        r"t-          d!!                    |	                     tE          d| j        |	| j        | j        "          }
tG                      }|
$                    |           tG                      |z
  }| j        r#t-          d#!                    ||                     tG                      }|
%                    d$%          }tG                      |z
  }| j        r#t-          d&!                    ||                     ~
|xj&        d	z  c_&        tO          || j        | j                  }t          | j        t          j(                  r| j        }n| j        dk    rtS          | j        d'|(          }|*                    d)*           |+                    |          ,                    t          j        d+,          }|t          j-        |dddf                   z  d-z  }nH| j        d.k    r=d-|.                    || j        f/          ,                    t          j                  z  }t_          | j        dz
  d          }| 0                    ||||||0          S )1z;Private function to fit the model using X as training data.r   zfPCA initialization is currently not supported with the sparse input matrix. Use init="random" instead.r   r      r   r   csrr   )accept_sparseensure_min_samplesrM   )r   csccoo)r   rM   r   zBThe parameter init="pca" cannot be used with metric="precomputed".r   z$X should be a square distance matrixzKTSNE.fit(). With metric='precomputed', X should contain positive distances.r   zTSNE with method="exact" does not accept sparse precomputed distance matrix. Use method="barnes_hut" or provide the dense distance matrix.   zj'n_components' should be inferior to 4 for the barnes_hut algorithm as it relies on quad-tree or oct-tree.Nz'[t-SNE] Computing pairwise distances...r   T)r   squared)r   r   zAAll distances should be positive, the metric given is not correctr6   z(All probabilities should be non-negativez5All probabilities should be less or then equal to oner   z)[t-SNE] Computing {} nearest neighbors...)	algorithmr   r   r   r   z([t-SNE] Indexed {} samples in {:.3f}s...distance)modez7[t-SNE] Computed neighbors for {} samples in {:.3f}s...
randomized)rW   
svd_solverr   default)	transformFr!   g-C6?r   )size)rZ   rl   rX   )1
isinstancer   strr   	TypeErrorr   r7   r   learning_rate_r$   r(   r   r   r%   float64r   r   r   rW   r   r   r-   rB   r   r   r   anyr2   r   r<   r=   minr   rC   r   r   r   kneighbors_graphr:   rH   rS   r   
set_outputfit_transformr#   stdstandard_normalrz   _tsne)r   r   rX   r   rE   neighbors_nnr+   metric_params_r/   r   knnrD   rG   distances_nnrZ   r   rV   s                    r1   _fitz	TSNE._fit`  sA    di%% 	$)u*<*<!*<)   ''"#'!*t/F"F"JD"$*T-@""E"ED"&"4D;,&&$g#$z2:.  AA 333z2:.	  A ;-''$)S)) di5.@.@ X   wqzQWQZ'' !GHHH9   {g%%(1++%<   ;,&&4+<q+@+@)  
 *$*;<<GAJ	;'!! {m++		< ECDDD;+-- !31T[RV W W WII%)%7%=2N 2!"&+dk! !ES! !I vi!m$$  W   {k))a	 %YNNA6"+a..))OO+OOOO6!q&>>MM#MMMM6Q  G GFG G G G i!mSt1F1J-K-KLLK| WAHHUUVVV # {'{"0  C BGGAJJJvv{H| >EE!8    B//Z/@@Lvv{H| MTT!8     !# (dot|TTAdi,, 	!JJY%!.')  C NNYN///**1--44RZe4LLJ $bfZ1-=&>&>>EJJY(""  < <!23 != ! !fRZ  !J !!2Q!6::zz!"+  
 
 	
r3   c                    |                                 }d| j        | j        | j        | j        t          |          |||| j        g| j        | j        dd
}| j        dk    r?t          }	| j
        |d         d<   | j        |d         d<   t                      |d         d	<   nt          }	|| j        z  }t          |	|fi |\  }}
}| j        rt          d
|dz   |
fz             || j        z  }| j        | j        z
  }|| j        k     s|dk    r3| j        |d<   |dz   |d<   d|d<   | j        |d<   t          |	|fi |\  }}
}|| _        | j        rt          d|dz   |
fz             |                    || j                  }|
| _        |S )zRuns t-SNE.r   )rX   rc   )
r   r   r   r   r-   r   r   r   r   r   r   r   rj   r-   rf   zE[t-SNE] KL divergence after %d iterations with early exaggeration: %fr   r   r   rp   r   r   z-[t-SNE] KL divergence after %d iterations: %f)r>   _N_ITER_CHECKr   r   r-   dictrW   _EXPLORATION_MAX_ITERr   rn   rj   r   rb   r   r   rB   	_max_iterr   n_iter_r;   kl_divergence_)r   r/   rV   rE   rZ   rl   rX   rU   opt_argsobj_funcr]   r   	remainings                r1   r   z
TSNE._tsne  s    !!##  .!/!0|?;;;*It7HI'+'A2
 
 ;,&&(H*.*HXw',0LHXy) 1L0M0MHX}--%H 	
T$$$5h$S$S($S$S!r< 	W6=)*   	
T$$NT%??	***i!mm#'>HZ !VHTN#&HZ 262NH./(9(F(W(Wh(W(W%FM2 < 	?6=)*  
 ^^It/@AA
+r3   Fr   c                 8   | j         dk    r=| j        t          d          t          j        dt
                     | j         | _        n| j        d| _        n| j        | _        |                     |           |                     |          }|| _	        | j	        S )a  Fit X into an embedded space and return that transformed output.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features) or             (n_samples, n_samples)
            If the metric is 'precomputed' X must be a square distance
            matrix. Otherwise it contains a sample per row. If the method
            is 'exact', X may be a sparse matrix of type 'csr', 'csc'
            or 'coo'. If the method is 'barnes_hut' and the metric is
            'precomputed', X may be a precomputed sparse graph.

        y : None
            Ignored.

        Returns
        -------
        X_new : ndarray of shape (n_samples, n_components)
            Embedding of the training data in low-dimensional space.
        r   NzBoth 'n_iter' and 'max_iter' attributes were set. Attribute 'n_iter' was deprecated in version 1.5 and will be removed in 1.7. To avoid this error, only set the 'max_iter' attribute.zM'n_iter' was renamed to 'max_iter' in version 1.5 and will be removed in 1.7.i  )
r   r   r   warningswarnFutureWarningr   r   r   
embedding_)r   r   y	embeddings       r1   r   zTSNE.fit_transformj  s    6 ;,&&}( T  
 M.    "[DNN]"!DNN!]DN##A&&&IIaLL	#r3   c                 0    |                      |           | S )a  Fit X into an embedded space.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features) or             (n_samples, n_samples)
            If the metric is 'precomputed' X must be a square distance
            matrix. Otherwise it contains a sample per row. If the method
            is 'exact', X may be a sparse matrix of type 'csr', 'csc'
            or 'coo'. If the method is 'barnes_hut' and the metric is
            'precomputed', X may be a precomputed sparse graph.

        y : None
            Ignored.

        Returns
        -------
        self : object
            Fitted estimator.
        )r   )r   r   r  s      r1   r   zTSNE.fit  s    2 	1r3   c                 &    | j         j        d         S )z&Number of transformed output features.r   )r  r7   )r   s    r1   _n_features_outzTSNE._n_features_out  s     $Q''r3   c                 r    t                                                      }| j        dk    |j        _        |S )Nr   )super__sklearn_tags__r   
input_tagspairwise)r   tags	__class__s     r1   r  zTSNE.__sklearn_tags__  s.    ww''))#';-#? r3   )r   )r   )Nr   r   )__name__
__module____qualname____doc__r   r   r   r   setr   callabler   r$   rS   r   r   __annotations__r   r   r   r   r   r   r   r   r   propertyr  r  __classcell__)r  s   @r1   r   r   1  s        a aF$(AtFCCCD$xxai@@@A$ 	xxafEEEF$ 	Jx  HT1d9555
	$ 	XXhT&AAA4H$ 	"HHXr4$O$O$O#P$ 	((4D@@@A$ 	::cc.11]OCDDhO$ 	$$ 	Jx())J
$" 	I;#$$ 	(%$& 	::|W5667'$( 	((4Af5556)$* 	4"+$, 	HXsD888F::|n--..
-$D   :   M #  #%# # # # #JG G G}
 }
 }
 }
J I I I IV \&+  . . .	 .` \&+    	 0 ( ( X(        r3   r   )r   T)rc   r   FTr   )	r   ro   rp   rq   rr   rs   r   NN)8r   numbersr   r   r   numpyr$   scipyr   scipy.sparser   r   scipy.spatial.distancer	   r
   baser   r   r   r   decompositionr   metrics.pairwiser   r   rl   r   utilsr   utils._openmp_helpersr   utils._param_validationr   r   r   r   utils.validationr   r   r    r   r   rx   doubleepsr*   r2   rH   rb   rn   r   r  r  r   r    r3   r1   <module>r)     s    " " " " " " " "                 - - - - - - - - 4 4 4 4 4 4 4 4                   A A A A A A A A ( ( ( ( ( ( & & & & & & ? ? ? ? ? ? S S S S S S S S S S S S N N N N N N N N N N ' & & & & & & &"(29%%)  B6 6 6~ J J J Jf ] ] ] ]J 	O O O Od O,#_5 1d6BBBC:cc.11]OCDDhO	  #'   34K e e e e ePQ
 Q
 Q
 Q
 Q
*,<m Q
 Q
 Q
 Q
 Q
r3   