
    -i                        S SK JrJr  S SKJr  S SKrS SKJr  S SKJ	r	J
r
  S SKJrJr  SSKJrJrJrJr  SS	KJr  SS
KJrJr  SSKJr  SSKJr  SSKJr  SSKJrJ r J!r!  SSK"J#r#J$r$J%r%  SSK&J'r'J(r(  \RR                  " \RT                  5      RV                  r,S r-S r.  S%S jr/     S&S jr0         S'S jr1\!" SS/SS/\" \SSSS9/\ " \2" \5      S1-  5      \3/S.SS9SS S!.S" j5       r4 " S# S$\\\5      r5g)(    )IntegralReal)timeN)linalg)
csr_matrixissparse)pdist
squareform   )BaseEstimatorClassNamePrefixFeaturesOutMixinTransformerMixin_fit_context)PCA)_VALID_METRICSpairwise_distances)NearestNeighbors)check_random_state)_openmp_effective_n_threads)Interval
StrOptionsvalidate_params)_num_samplescheck_non_negativevalidate_data   )_barnes_hut_tsne_utilsc                 8   U R                  [        R                  SS9n [        R                  " XU5      nX3R
                  -   n[        R                  " [        R                  " U5      [        5      n[        R                  " [        U5      U-  [        5      nU$ )a  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         J/var/www/html/venv/lib/python3.13/site-packages/sklearn/manifold/_t_sne.py_joint_probabilitiesr1   &   sv    .   % 8I44wM 	'AJJrvvay/2E


:a=5(/:AH    c                    [        5       nU R                  5         U R                  S   nU R                  R	                  US5      nUR                  [        R                  SS9n[        R                  " XQU5      n[        R                  " [        R                  " U5      5      (       d   S5       e[        UR                  5       U R                  U R                  4XD4S9nXwR                   -   n[        R"                  " UR%                  5       [&        5      nXx-  n[        R                  " [        R(                  " UR                  5      S:*  5      (       d   eUS:  a'  [        5       U-
  n	[+        S	R-                  U	5      5        U$ )
a(  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_indicesr6   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.   r/   durations
             r0   _joint_probabilities_nnrG   G   s?   6 
B "I^^++Ir:N#**2::E*BN44GM 66"++m,--S/SS- 						 1 193C3CD$	A 	
CCA JJquuw0EJA66"&&.C'((((!|6B;ELLXVWHr2   Tc           
         U R                  X45      n[        US5      nX-  nUS-  nXS-   S-  -  n[        R                  " US[        R                  " U5      -  -  [
        5      n	U(       aK  S[        R                  " U[        R                  " [        R                  " U[
        5      U	-  5      5      -  n
O[        R                  n
[        R                  " X44U R                  S9n[        X-
  U-  5      n[        XS5       H6  n[        R                  " [        R                  " X   SS9X}   U-
  5      X'   M8     UR                  5       nSUS-   -  U-  nX-  nX4$ )a  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.
sqeuclideanr7   g              @dtypeK)order)r:   r	   r#   r'   r(   r)   dotlognanndarrayrL   r
   ranger=   )paramsr.   degrees_of_freedomrD   n_componentsskip_num_pointscompute_error
X_embeddeddistQkl_divergencegradPQdics                  r0   _kl_divergencera      s2   \ 	8J ]+DDCKD3&$..D


43-.@A bffQrzz!_/MPQ/Q(RSS ::y/v||DD
aet^
$C?.&&#&4jmj6PQ /::<D!C'(+==AIDr2   c
                 ,   U R                  [        R                  SS9n U R                  X45      n
UR                  R                  [        R                  SS9nUR
                  R                  [        R                  SS9nUR                  R                  [        R                  SS9n[        R                  " U
R                  [        R                  S9n[        R                  " UU
UUUUUUUUU	S9nSUS-   -  U-  nUR                  5       nUU-  nX4$ )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    rK   )dofrX   num_threadsrJ   r7   )r"   r#   r$   r:   r9   r>   int64r?   zerosr6   r   gradientr=   )rT   r.   rU   rD   rV   anglerW   r,   rX   rd   rY   val_P	neighborsr?   r]   errorr`   s                    r0   _kl_divergence_bhrl      s    H ]]2::E]2F	8JFFMM"**5M1E		   6IXX__RXXE_2F88J$$BJJ7D%%#E 	!C'(+==A::<DAID;r2   c           	         Uc  / nUc  0 nUR                  5       R                  5       n[        R                  " U5      n[        R                  " U5      n[        R
                  " [        5      R                  n[        R
                  " [        5      R                  nU=nn[        5       n[        X#5       GH=  nUS-   U-  S:H  nU=(       d    UUS-
  :H  US'   U " U/UQ70 UD6u  nnUU-  S:  n[        R                  " U5      nUU==   S-  ss'   UU==   S-  ss'   [        R                  " X[        R                  US9  UU-  nXn-  UU-  -
  nX-  nU(       d  M  [        5       nUU-
  nUn[        R                  " U5      nU
S:  a  [        S	US-   UUUU4-  5        UU:  a  UnUnO$UU-
  U:  a  U
S:  a  [        S
US-   U4-  5          O&UU	::  d  GM%  U
S:  a  [        SUS-   U4-  5          O   UUU4$ )a}  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.
r   r   rX   g        g?皙?)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   rS   invertclipinfr   normrA   )	objectivep0itmax_itern_iter_checkn_iter_without_progressmomentumlearning_ratemin_gainmin_grad_normr,   argskwargspupdategainsrk   
best_error	best_iterr_   ticcheck_convergencer]   incdectocrF   	grad_norms                               r0   _gradient_descentr   -  s!   b |~
	A]]1FLLOEHHUOE%$$JI
&C2 Ul2a7"3"HqHqL7H3D3F3ttmc!iinc
c
c
c

U3"]T%99	&CSyHCD)I!|1 1ueYhGH z!"
	Y!88a<Aq5"9:;
 M)a<Kq5),- _ !b eQ;r2   z
array-likezsparse matrixleftclosedprecomputed)XrY   n_neighborsmetricprefer_skip_nested_validation   	euclidean)r   r   c                   [        U 5      nX$S-  :  a  [        SU SUS-   S35      e[        XS9nUS:X  a  UR                  5       n[        R
                  " U[        R                  5        [        R                  " USS9n[        US	9R                  U5      R                  S
S9n[        R                  " XD4[        S9n[        R                  " US-   5      n	U	SS XSS2[        R                  4   U4'   XSS2[        R                  4   U4   U-
  n
[        R                  " XS:     5      nSUSXB-  SU-  SU-  -
  S-
  -  -  -  -
  nU$ )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_distancerK   Nr4   r   r7   rJ         @)r   
ValueErrorr   r!   r#   fill_diagonalrw   argsortr   fit
kneighborsrf   intarangenewaxisr(   )r   rY   r   r   rD   dist_Xind_Xind_X_embeddedinverted_indexordered_indicesranksts               r0   trustworthinessr     so   Z QI!m#K= )Qq"
 	
  1F VRVV$JJvA&E 	[1	Z	E	*  XXy4C@Nii	A.O>Mab>QN3B3

?3U:;ssBJJ7GH;V 
 	uQY Aay&#	/C+<M*MPS*STU 	A Hr2   c                     ^  \ rS rSr% Sr\" \SSSS9/\" \SSSS9/\" \SSSS9/\" S	15      \" \SSSS9/\" \S
SSS9/\" \SSSS9/\" \SSSS9/\" \	" \
5      S1-  5      \/\S/\" SS15      \R                  /S/S/\" SS15      /\" \SSSS9/S\/S.r\\S'   S
rSr S*SSS	SSSSSSSSSSSS.S jjrS  rS+S! jr  S,S" jr\" S#S$9S-S% j5       r\" S#S$9S-S& j5       r\S' 5       rU 4S( jrS)rU =r$ ).TSNEi0  aZ#  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

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)
r   Nr   r   r   neitherauto   r4   r   pcarandomr,   random_state
barnes_hutexactbothrV   
perplexityearly_exaggerationr   r|   r~   r   r   metric_paramsinitr,   r   methodrh   n_jobs_parameter_constraints2   g      >@g      (@i  ,  Hz>r         ?)r   r   r   r|   r~   r   r   r   r   r,   r   r   rh   r   c                    Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        Xl        Xl	        Xl
        Xl        Xl        Xl        Xl        g Nr   )selfrV   r   r   r   r|   r~   r   r   r   r   r,   r   r   rh   r   s                   r0   __init__TSNE.__init__*  sV    & )$"4* '>$**	(
r2   c                     U R                   UR                  S   :  a)  [        SU R                    SUR                  S    S35      eg )Nr   zperplexity (z) must be less than n_samples (r   )r   r6   r   )r   r   s     r0   _check_params_vs_inputTSNE._check_params_vs_inputM  sM    ??aggaj(t/ 0##$771:,a1  )r2   c           	      H   [        U R                  [        5      (       a+  U R                  S:X  a  [        U5      (       a  [	        S5      eU R
                  S:X  aK  UR                  S   U R                  -  S-  U l        [        R                  " U R                  S5      U l        OU R
                  U l        U R                  S:X  a-  [        U US/S	[        R                  [        R                  /S
9nO,[        U U/ SQ[        R                  [        R                  /S9nU R                  S:X  a  [        U R                  [        5      (       a  U R                  S:X  a  [!        S5      eUR                  S   UR                  S   :w  a  [!        S5      e[#        US5        U R                  S:X  a  [        U5      (       a  [	        S5      eU R                  S:X  a  U R$                  S:  a  [!        S5      e['        U R(                  5      nUR                  S   nSnU R                  S:X  Gal  U R                  S:X  a  UnOyU R*                  (       a  [-        S5        U R                  S:X  a  [/        XR                  SS9nO8U R0                  =(       d    0 n[/        U4U R                  U R2                  S.UD6n[        R4                  " US:  5      (       a  [!        S5      eU R                  S:w  a  US	-  n[7        X`R8                  U R*                  5      n[        R:                  " [        R<                  " U5      5      (       d   S5       e[        R:                  " US:  5      (       d   S5       e[        R:                  " US:*  5      (       d   S5       eGOX[?        US-
  [A        S U R8                  -  S-   5      5      n	U R*                  (       a  [-        S!RC                  U	5      5        [E        SU R2                  U	U R                  U R0                  S"9n
[G        5       nU
RI                  U5        [G        5       U-
  nU R*                  (       a  [-        S#RC                  XL5      5        [G        5       nU
RK                  S$S%9n[G        5       U-
  nU R*                  (       a  [-        S&RC                  XL5      5        A
U=RL                  S	-  sl&        [O        XR8                  U R*                  5      n[        U R                  [        RP                  5      (       a  U R                  nOU R                  S:X  au  [S        U R$                  S'US(9nURU                  S)S*9  URW                  U5      RY                  [        R                  S+S,9nU[        RZ                  " USS2S4   5      -  S--  nOJU R                  S.:X  a:  S-UR]                  X@R$                  4S/9RY                  [        R                  5      -  n[_        U R$                  S-
  S5      nU Ra                  UUUWUUS09$ )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_samplesrL   )r   csccoo)r   rL   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 correctr5   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)rV   
svd_solverr   default)	transformFr    g-C6?r   )size)rY   rj   rW   )1
isinstancer   strr   	TypeErrorr   r6   r   learning_rate_r#   r'   r   r   r$   float64r   r   r   rV   r   r   r,   rA   r   r   r   anyr1   r   r;   r<   minr   rB   r   r   r   kneighbors_graphr9   rG   rR   r   
set_outputfit_transformr"   stdstandard_normalrt   _tsne)r   r   rW   r   rD   neighbors_nnr*   metric_params_r.   r   knnrC   rF   distances_nnrY   r   rU   s                    r0   _fit	TSNE._fitT  sF    dii%%$))u*<!)  '"#''!*t/F/F"F"JD"$**T-@-@""ED"&"4"4D;;,&$g#$zz2::.A 3zz2::.	A ;;-'$))S))dii5.@ X  wwqzQWWQZ' !GHH9 {{g%(1++<  ;;,&4+<+<q+@) 
 *$*;*;<GGAJ	;;'! {{m+	<<CD;;+- !31[[RV WI%)%7%7%=2N 2!"&++dkk!ES!I vvi!m$$ W  {{k)a	 %YNA66"++a.))O+OO)66!q&>>M#MM>66!q&>> G> i!mSt1F1J-KLK||AHHUV # {{'{{"00C BGGAJv{H||>EE! B//Z/@Lv{H||MTT!  !# (oot||TAdii,,JYY%!..')C NNYN/**1-44RZZe4LJ $bffZ1-=&>>EJYY("  < <!2!23 != !fRZZ !J !!2!2Q!6:zz!"+  
 	
r2   c                    UR                  5       nSU R                  U R                  U R                  U R                  [        US9XX0R                  /U R                  U R                  SS.
nU R                  S:X  a;  [        n	U R                  US   S'   U R                  US   S'   [        5       US   S	'   O[        n	XR                  -  n[        X40 UD6u  pznU R                  (       a  [        S
US-   U
4-  5        XR                  -  nU R                   U R                  -
  nXR                  :  d  US:  a:  U R                   US'   US-   US'   SUS'   U R"                  US'   [        X40 UD6u  pznXl        U R                  (       a  [        SUS-   U
4-  5        UR'                  X0R                  5      nXl        U$ )zRuns t-SNE.r   )rW   r   )
r{   r}   r   r   r,   r   r   r~   r|   r   r   r   rh   r,   rd   zE[t-SNE] KL divergence after %d iterations with early exaggeration: %fr   r|   r{   rn   r   r~   z-[t-SNE] KL divergence after %d iterations: %f)r=   _N_ITER_CHECKr   r   r,   dictrV   _EXPLORATION_MAX_ITERr   rl   rh   r   ra   r   r   rA   r|   r~   n_iter_r:   kl_divergence_)r   r.   rU   rD   rY   rj   rW   rT   opt_argsobj_funcr\   r{   	remainings                r0   r   
TSNE._tsne  s    !!#  ..!//!00||?;I7H7HI'+'A'A22
 ;;,&(H*.**HXw',0LLHXy) 1L0MHX}-%H 	
$$$$5h$S($S!r<<W6=)* 	
$$$MMD$>$>>	***i!m#'==HZ !VHTN#&HZ 262N2NH./(9((Wh(W%F2 <<?6=)*
 ^^I/@/@A
+r2   Fr   c                 j    U R                  U5        U R                  U5      nX0l        U R                  $ )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   r   
embedding_)r   r   y	embeddings       r0   r   TSNE.fit_transform^  s.    2 	##A&IIaL	#r2   c                 (    U R                  U5        U $ )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      r0   r   TSNE.fit|  s    2 	1r2   c                 4    U R                   R                  S   $ )z&Number of transformed output features.r   )r   r6   )r   s    r0   _n_features_outTSNE._n_features_out  s     $$Q''r2   c                 `   > [         TU ]  5       nU R                  S:H  UR                  l        U$ )Nr   )super__sklearn_tags__r   
input_tagspairwise)r   tags	__class__s     r0   r
  TSNE.__sklearn_tags__  s*    w')#';;-#? r2   )rh   r   r   r   r   r   r   r|   r   r   r   r   rV   r   r~   r   r   r   r,   )r   )r   )Nr   r   )__name__
__module____qualname____firstlineno____doc__r   r   r   r   setr   callabler   r#   rR   r   __annotations__r   r   r   r   r   r   r   r   r   propertyr  r
  __static_attributes____classcell__)r  s   @r0   r   r   0  s   Yx "(AtFCDai@A'afEFx T1d95
 hT&AB$,Xr4$O#P"4D@Ac.1]OCDhOx()JJ
 ;'(|W5674Af56"+$D 2   M !  ##!F}
J IV &+	4 &+	0 ( ( r2   r   )r   T)r   r   FTr   )	r   r   rn   g      i@g{Gz?r   r   NN)6numbersr   r   r   numpyr#   scipyr   scipy.sparser   r   scipy.spatial.distancer	   r
   baser   r   r   r   decompositionr   metrics.pairwiser   r   rj   r   utilsr   utils._openmp_helpersr   utils._param_validationr   r   r   utils.validationr   r   r    r   r   rr   doubleepsr)   r1   rG   ra   rl   r   r  r  r   r    r2   r0   <module>r+     s/   #    - 4    A ( & ? K K N N '((299%))B6~ Jf ]J 	Od O,#_5 1d6BCc.1]OCDhO	 #' 34K eePp	*,<m p	r2   