
    0Ph                        d Z ddlmZmZ ddlZddlmZ ddl	m
Z
 ddlmZmZ 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 dd
lmZ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&  ej'        e(          j)        Z*d Z+ G d deee          Z,dS )a6  

=============================================================
Online Latent Dirichlet Allocation with variational inference
=============================================================

This implementation is modified from Matthew D. Hoffman's onlineldavb code
Link: https://github.com/blei-lab/onlineldavb
    )IntegralRealN)effective_n_jobs)gammaln	logsumexp   )BaseEstimatorClassNamePrefixFeaturesOutMixinTransformerMixin_fit_context)check_random_stategen_batchesgen_even_slices)Interval
StrOptions)Paralleldelayed)check_is_fittedcheck_non_negativevalidate_data   )_dirichlet_expectation_1d)_dirichlet_expectation_2d)mean_changec           	      ,   t          j        |           }| j        \  }}	|j        d         }
|r4|                    dd||
f                              | j        d          }nt          j        ||
f| j                  }t          j        t          |                    }|r t          j
        |j        | j                  nd}|r| j        }| j        }| j        }| j        t          j        k    rdnd	}t          |         }t           |         }t          j        | j                  j        }t'          |          D ]U}|r3|||         ||d
z                     }|||         ||d
z                     }n.t          j        | |ddf                   d         }| ||f         }||ddf         }||ddf                                         }|dd|f         }t'          d|          D ][}|}t          j        ||          |z   }|t          j        ||z  |j                  z  } ||||            |||          |k     r n\|||ddf<   |rBt          j        ||          |z   }|dd|fxx         t          j        |||z            z  cc<   W||fS )a  E-step: update document-topic distribution.

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        Document word matrix.

    exp_topic_word_distr : ndarray of shape (n_topics, n_features)
        Exponential value of expectation of log topic word distribution.
        In the literature, this is `exp(E[log(beta)])`.

    doc_topic_prior : float
        Prior of document topic distribution `theta`.

    max_doc_update_iter : int
        Max number of iterations for updating document topic distribution in
        the E-step.

    mean_change_tol : float
        Stopping tolerance for updating document topic distribution in E-step.

    cal_sstats : bool
        Parameter that indicate to calculate sufficient statistics or not.
        Set `cal_sstats` to `True` when we need to run M-step.

    random_state : RandomState instance or None
        Parameter that indicate how to initialize document topic distribution.
        Set `random_state` to None will initialize document topic distribution
        to a constant number.

    Returns
    -------
    (doc_topic_distr, suff_stats) :
        `doc_topic_distr` is unnormalized topic distribution for each document.
        In the literature, this is `gamma`. we can calculate `E[log(theta)]`
        from it.
        `suff_stats` is expected sufficient statistics for the M-step.
            When `cal_sstats == False`, this will be None.

    r         Y@g{Gz?FcopydtypeNfloatdoubler   )spissparseshapegammaastyper    nponesexpr   zerosdataindicesindptrfloat32cy_mean_changecy_dirichlet_expectation_1dfinfoepsrangenonzeror   dotTouter)Xexp_topic_word_distrdoc_topic_priormax_doc_update_itermean_change_tol
cal_sstatsrandom_stateis_sparse_x	n_samples
n_featuresn_topicsdoc_topic_distrexp_doc_topic
suff_statsX_data	X_indicesX_indptrctyper   dirichlet_expectation_1dr3   idx_didscntsdoc_topic_dexp_doc_topic_dexp_topic_word_d_last_dnorm_phis                                 Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/decomposition/_lda.py_update_doc_distributionrV   ,   s    b +a..KGIz#)!,H H&,,UD9h:OPPWWG% X 
 
 '9h"7qwGGG F4_EEFFM @JS%+17;;;;t   I	8 w"*,,GG(E 'K:5A
(17


Cy!! !M !M 	!HUOhuqy.AABC(5/HUQY,??@DD*Quaaax[))!,CUCZ=D%eQQQh/'qqq16688/37 q-.. 	 	A F vo/?@@3FH)BF4(?DTDV,W,WWK$$[/?SSS{6;///AA B$/qqq!  	Mvo/?@@3FHqqq#v"(?D8O"L"LLZ((    c                       e Zd ZU dZi d eeddd          gdd eeddd	          gd
d eeddd	          gd eddh          gd eeddd	          gd eeddd          gd eeddd          gd eeddd          gd eeddd          gd eeddd          gd eeddd          gd eeddd          gd eeddd          gddegddgddgZe	e
d<   	 d;ddddddd d!d"d#d$d%dddd&d'Zej        fd(Zd<d)Zd<d*Z fd+Zd, Z ed-.          d<d/            Z ed-.          d<d0            Zd1 Zd-d2d3Zd<d-d2d4Zd5 Zd<d6Zd=d8Zd>d9Zed:             Z xZS )?LatentDirichletAllocationaT  Latent Dirichlet Allocation with online variational Bayes algorithm.

    The implementation is based on [1]_ and [2]_.

    .. versionadded:: 0.17

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

    Parameters
    ----------
    n_components : int, default=10
        Number of topics.

        .. versionchanged:: 0.19
            ``n_topics`` was renamed to ``n_components``

    doc_topic_prior : float, default=None
        Prior of document topic distribution `theta`. If the value is None,
        defaults to `1 / n_components`.
        In [1]_, this is called `alpha`.

    topic_word_prior : float, default=None
        Prior of topic word distribution `beta`. If the value is None, defaults
        to `1 / n_components`.
        In [1]_, this is called `eta`.

    learning_method : {'batch', 'online'}, default='batch'
        Method used to update `_component`. Only used in :meth:`fit` method.
        In general, if the data size is large, the online update will be much
        faster than the batch update.

        Valid options:

        - 'batch': Batch variational Bayes method. Use all training data in each EM
          update. Old `components_` will be overwritten in each iteration.
        - 'online': Online variational Bayes method. In each EM update, use mini-batch
          of training data to update the ``components_`` variable incrementally. The
          learning rate is controlled by the ``learning_decay`` and the
          ``learning_offset`` parameters.

        .. versionchanged:: 0.20
            The default learning method is now ``"batch"``.

    learning_decay : float, default=0.7
        It is a parameter that control learning rate in the online learning
        method. The value should be set between (0.5, 1.0] to guarantee
        asymptotic convergence. When the value is 0.0 and batch_size is
        ``n_samples``, the update method is same as batch learning. In the
        literature, this is called kappa.

    learning_offset : float, default=10.0
        A (positive) parameter that downweights early iterations in online
        learning.  It should be greater than 1.0. In the literature, this is
        called tau_0.

    max_iter : int, default=10
        The maximum number of passes over the training data (aka epochs).
        It only impacts the behavior in the :meth:`fit` method, and not the
        :meth:`partial_fit` method.

    batch_size : int, default=128
        Number of documents to use in each EM iteration. Only used in online
        learning.

    evaluate_every : int, default=-1
        How often to evaluate perplexity. Only used in `fit` method.
        set it to 0 or negative number to not evaluate perplexity in
        training at all. Evaluating perplexity can help you check convergence
        in training process, but it will also increase total training time.
        Evaluating perplexity in every iteration might increase training time
        up to two-fold.

    total_samples : int, default=1e6
        Total number of documents. Only used in the :meth:`partial_fit` method.

    perp_tol : float, default=1e-1
        Perplexity tolerance. Only used when ``evaluate_every`` is greater than 0.

    mean_change_tol : float, default=1e-3
        Stopping tolerance for updating document topic distribution in E-step.

    max_doc_update_iter : int, default=100
        Max number of iterations for updating document topic distribution in
        the E-step.

    n_jobs : int, default=None
        The number of jobs to use in the E-step.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    verbose : int, default=0
        Verbosity level.

    random_state : int, RandomState instance or None, default=None
        Pass an int for reproducible results across multiple function calls.
        See :term:`Glossary <random_state>`.

    Attributes
    ----------
    components_ : ndarray of shape (n_components, n_features)
        Variational parameters for topic word distribution. Since the complete
        conditional for topic word distribution is a Dirichlet,
        ``components_[i, j]`` can be viewed as pseudocount that represents the
        number of times word `j` was assigned to topic `i`.
        It can also be viewed as distribution over the words for each topic
        after normalization:
        ``model.components_ / model.components_.sum(axis=1)[:, np.newaxis]``.

    exp_dirichlet_component_ : ndarray of shape (n_components, n_features)
        Exponential value of expectation of log topic word distribution.
        In the literature, this is `exp(E[log(beta)])`.

    n_batch_iter_ : int
        Number of iterations of the EM step.

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    n_iter_ : int
        Number of passes over the dataset.

    bound_ : float
        Final perplexity score on training set.

    doc_topic_prior_ : float
        Prior of document topic distribution `theta`. If the value is None,
        it is `1 / n_components`.

    random_state_ : RandomState instance
        RandomState instance that is generated either from a seed, the random
        number generator or by `np.random`.

    topic_word_prior_ : float
        Prior of topic word distribution `beta`. If the value is None, it is
        `1 / n_components`.

    See Also
    --------
    sklearn.discriminant_analysis.LinearDiscriminantAnalysis:
        A classifier with a linear decision boundary, generated by fitting
        class conditional densities to the data and using Bayes' rule.

    References
    ----------
    .. [1] "Online Learning for Latent Dirichlet Allocation", Matthew D.
           Hoffman, David M. Blei, Francis Bach, 2010
           https://github.com/blei-lab/onlineldavb

    .. [2] "Stochastic Variational Inference", Matthew D. Hoffman,
           David M. Blei, Chong Wang, John Paisley, 2013

    Examples
    --------
    >>> from sklearn.decomposition import LatentDirichletAllocation
    >>> from sklearn.datasets import make_multilabel_classification
    >>> # This produces a feature matrix of token counts, similar to what
    >>> # CountVectorizer would produce on text.
    >>> X, _ = make_multilabel_classification(random_state=0)
    >>> lda = LatentDirichletAllocation(n_components=5,
    ...     random_state=0)
    >>> lda.fit(X)
    LatentDirichletAllocation(...)
    >>> # get topics for some given samples:
    >>> lda.transform(X[-2:])
    array([[0.00360392, 0.25499205, 0.0036211 , 0.64236448, 0.09541846],
           [0.15297572, 0.00362644, 0.44412786, 0.39568399, 0.003586  ]])
    n_componentsr   Nneither)closedr;   r   bothtopic_word_priorlearning_methodbatchonlinelearning_decaylearning_offset      ?leftmax_iter
batch_sizeevaluate_everytotal_samplesperp_tolr=   r<   n_jobsverboser?   _parameter_constraints
   gffffff?g      $@   g    .Ag?gMbP?d   )r;   r^   r_   rb   rc   rf   rg   rh   ri   rj   r=   r<   rk   rl   r?   c                    || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        || _
        || _        || _        || _        || _        || _        d S N)rZ   r;   r^   r_   rb   rc   rf   rg   rh   ri   rj   r=   r<   rk   rl   r?   )selfrZ   r;   r^   r_   rb   rc   rf   rg   rh   ri   rj   r=   r<   rk   rl   r?   s                    rU   __init__z"LatentDirichletAllocation.__init__k  s    ( ). 0.,. $,* .#6 (rW   c                    t          | j                  | _        d| _        d| _        | j        d| j        z  | _        n| j        | _        | j        d| j        z  | _	        n| j        | _	        d}d|z  }| j        
                    ||| j        |f                              |d          | _        t          j        t          | j                            | _        dS )zInitialize latent variables.r   r   Nrd   r   Fr   )r   r?   random_state_n_batch_iter_n_iter_r;   rZ   doc_topic_prior_r^   topic_word_prior_r&   r'   components_r(   r*   r   exp_dirichlet_component_)rt   rB   r    
init_gammainit_vars        rU   _init_latent_varsz+LatentDirichletAllocation._init_latent_vars  s     00ABB'$'$*;$;D!!$($8D! (%(4+<%<D""%)%:D"
#-334#4j"A
 

&U&
#
# 	
 )+%d&677)
 )
%%%rW   c                     |r j         ndt           j                  }|'t          |t	          d j        dz
                      } | fdt          j        d         |          D                       }t          | \  }}t          j
        |          }	r?t          j         j        j         j        j                  }
|D ]}|
|z  }
|
 j        z  }
nd}
|	|
fS )a  E-step in EM update.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Document word matrix.

        cal_sstats : bool
            Parameter that indicate whether to calculate sufficient statistics
            or not. Set ``cal_sstats`` to True when we need to run M-step.

        random_init : bool
            Parameter that indicate whether to initialize document topic
            distribution randomly in the E-step. Set it to True in training
            steps.

        parallel : joblib.Parallel, default=None
            Pre-initialized instance of joblib.Parallel.

        Returns
        -------
        (doc_topic_distr, suff_stats) :
            `doc_topic_distr` is unnormalized topic distribution for each
            document. In the literature, this is called `gamma`.
            `suff_stats` is expected sufficient statistics for the M-step.
            When `cal_sstats == False`, it will be None.

        Nr   r   rk   rl   c           
   3      K   | ]E} t          t                    |d d f         j        j        j        j                  V  Fd S rs   )r   rV   r}   rz   r<   r=   ).0	idx_slicer9   r>   r?   rt   s     rU   	<genexpr>z4LatentDirichletAllocation._e_step.<locals>.<genexpr>  s{       
 
  .G,--)QQQ,-%($ 
 
 
 
 
 
rW   r   )rw   r   rk   r   maxrl   r   r%   zipr(   vstackr+   r|   r    r}   )rt   r9   r>   random_initparallelrk   results
doc_topicssstats_listrD   rF   sstatsr?   s   ```         @rU   _e_stepz!LatentDirichletAllocation._e_step  s/   > .9Bt))d "$+..vs1dlQ>N7O7OPPPH( 
 
 
 
 
 
 
 -QWQZ@@
 
 
 
 
 #&w-
K)J// 	 $"2"8@P@VWWWJ% % %f$

$77JJJ,,rW   c                    |                      |dd|          \  }}|r| j        |z   | _        nvt          j        | j        | j        z   | j                   }t          |          |j	        d         z  }| xj        d|z
  z  c_        | xj        || j        ||z  z   z  z  c_        t          j
        t          | j                            | _        | xj        dz  c_        dS )a  EM update for 1 iteration.

        update `_component` by batch VB or online VB.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Document word matrix.

        total_samples : int
            Total number of documents. It is only used when
            batch_update is `False`.

        batch_update : bool
            Parameter that controls updating method.
            `True` for batch learning, `False` for online learning.

        parallel : joblib.Parallel, default=None
            Pre-initialized instance of joblib.Parallel

        Returns
        -------
        doc_topic_distr : ndarray of shape (n_samples, n_components)
            Unnormalized document topic distribution.
        Tr>   r   r   r   r   N)r   r{   r|   r(   powerrc   rx   rb   r!   r%   r*   r   r}   )	rt   r9   ri   batch_updater   rR   rF   weight	doc_ratios	            rU   _em_stepz"LatentDirichletAllocation._em_step  s   8 $D8 % 
 
:
  	#5
BD X$t'99D<O;O F m,,qwqz9IF
*&Z)??! 
 )+%d&677)
 )
% 	arW   c                     t                                                      }d|j        _        d|j        _        ddg|j        _        |S )NTr/   float64)super__sklearn_tags__
input_tagspositive_onlysparsetransformer_tagspreserves_dtype)rt   tags	__class__s     rU   r   z*LatentDirichletAllocation.__sklearn_tags__%  sA    ww''))(,%!%1:I0F-rW   c                     |rt           j        t           j        gn| j        j        }t          | ||d|          }t          ||           |S )zcheck X format

        check X format and make sure no negative value in X.

        Parameters
        ----------
        X :  array-like or sparse matrix

        csr)resetaccept_sparser    )r(   r   r/   r|   r    r   r   )rt   r9   reset_n_featureswhomr    s        rU   _check_non_neg_arrayz.LatentDirichletAllocation._check_non_neg_array,  s\     -=XRZ(($BRBX"
 
 
 	1d###rW   T)prefer_skip_nested_validationc                 H   t          | d           }|                     ||d          }|j        \  }}| j        }|r|                     ||j                   || j        j        d         k    r$t          d|| j        j        d         fz            t          | j	                  }t          |t          d| j        dz
                      5 }t          ||          D ]*}	|                     ||	d	d	f         | j        d
|           +	 d	d	d	           n# 1 swxY w Y   | S )am  Online VB with Mini-Batch update.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Document word matrix.

        y : Ignored
            Not used, present here for API consistency by convention.

        Returns
        -------
        self
            Partially fitted estimator.
        r|   z%LatentDirichletAllocation.partial_fitr   r   r   r   zUThe provided data has %d dimensions while the model was trained with feature size %d.r   r   NFri   r   r   )hasattrr   r%   rg   r   r    r|   
ValueErrorr   rk   r   r   rl   r   r   ri   )
rt   r9   y
first_timerA   rB   rg   rk   r   r   s
             rU   partial_fitz%LatentDirichletAllocation.partial_fitC  s   " !}555
%%
1X & 
 
 !"	:_
  	>"":QW"===)/222>t/5a89:   "$+..VSDL14D-E-EFFF 	((J??  	ilO"&"4!&%	     	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 s   <DDDc           	         |                      |dd          }|j        \  }}| j        }| j        }| j        }| j        }|                     ||j                   d}	t          | j	                  }
t          |
t          d| j        dz
                      5 }t          |          D ]}|d	k    r7t          ||          D ]%}|                     ||ddf         |d
|           &n|                     ||d|           |dk    r|dz   |z  dk    ru|                     |d
d
|          \  }}|                     ||d
          }| j        rt%          d|dz   ||fz             |	rt'          |	|z
            | j        k     r n3|}	n| j        rt%          d|dz   |fz             | xj        dz  c_        ddd           n# 1 swxY w Y   |                     |d
d
|          \  }}|                     ||d
          | _        | S )a  Learn model for the data X with variational Bayes method.

        When `learning_method` is 'online', use mini-batch update.
        Otherwise, use batch update.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Document word matrix.

        y : Ignored
            Not used, present here for API consistency by convention.

        Returns
        -------
        self
            Fitted estimator.
        TzLatentDirichletAllocation.fitr   r   Nr   r   r   ra   Fr   r   sub_samplingz/iteration: %d of max_iter: %d, perplexity: %.4fziteration: %d of max_iter: %d)r   r%   rf   rh   r_   rg   r   r    r   rk   r   r   rl   r4   r   r   r   _perplexity_precomp_distrprintabsrj   ry   bound_)rt   r9   r   rA   rB   rf   rh   r_   rg   
last_boundrk   r   ir   doc_topics_distrrR   bounds                    rU   fitzLatentDirichletAllocation.fits  s   ( %%+J & 
 
 !"	:=,._
 	z999
!$+..VSDL14D-E-EFFF $	"(8__ #" #""h..%0J%G%G  	ilO*3).%-	 &     MMPX "   
 "A%%1q5N*Ba*G*G*.,,e +7 + +'$a !::+% ;  E | M 1uh67  
 " c*u*<&=&=&M&M!&JJ\ O9QUH<MMNNN!I$	" $	" $	" $	" $	" $	" $	" $	" $	" $	" $	" $	" $	" $	" $	"N #ll%UX + 
 
! 44e 5 
 
 s   D GGGc                 <    |                      |dd          \  }}|S )a[  Transform data X according to fitted model.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Document word matrix.

        Returns
        -------
        doc_topic_distr : ndarray of shape (n_samples, n_components)
            Document topic distribution for X.
        F)r>   r   )r   )rt   r9   rD   rR   s       rU   _unnormalized_transformz1LatentDirichletAllocation._unnormalized_transform  s&     "\\!5\QQrW   	normalizec                    t          |            |                     |dd          }|                     |          }|r-||                    d          ddt          j        f         z  }|S )a  Transform data X according to the fitted model.

        .. versionchanged:: 0.18
            `doc_topic_distr` is now normalized.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Document word matrix.

        normalize : bool, default=True
            Whether to normalize the document topic distribution.

        Returns
        -------
        doc_topic_distr : ndarray of shape (n_samples, n_components)
            Document topic distribution for X.
        Fz#LatentDirichletAllocation.transformr   r   axisN)r   r   r   sumr(   newaxis)rt   r9   r   rD   s       rU   	transformz#LatentDirichletAllocation.transform  s    & 	%%,Q & 
 
 66q99 	J222::111bj=IIOrW   c                X    |                      ||                              ||          S )a  
        Fit to data, then transform it.

        Fits transformer to `X` and `y` and returns a transformed version of `X`.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Input samples.

        y :  array-like of shape (n_samples,) or (n_samples, n_outputs),                 default=None
            Target values (None for unsupervised transformations).

        normalize : bool, default=True
            Whether to normalize the document topic distribution in `transform`.

        Returns
        -------
        X_new : ndarray array of shape (n_samples, n_features_new)
            Transformed array.
        r   )r   r   )rt   r9   r   r   s       rU   fit_transformz'LatentDirichletAllocation.fit_transform  s)    . xx1~~''Y'???rW   c                    d }t          j        |          }|j        \  }}| j        j        d         }d}	t	          |          }
t	          | j                  }| j        }| j        }|r|j        }|j        }|j	        }t          d|          D ]}|r3|||         ||dz                     }|||         ||dz                     }n.t          j        ||ddf                   d         }|||f         }|
|ddt          j        f         |dd|f         z   }t          |d          }|	t          j        ||          z  }	|	 ||||
| j                  z  }	|rt#          | j                  |z  }|	|z  }	|	 ||| j        ||          z  }	|	S )a  Estimate the variational bound.

        Estimate the variational bound over "all documents" using only the
        documents passed in as X. Since log-likelihood of each word cannot
        be computed directly, we use this bound to estimate it.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Document word matrix.

        doc_topic_distr : ndarray of shape (n_samples, n_components)
            Document topic distribution. In the literature, this is called
            gamma.

        sub_sampling : bool, default=False
            Compensate for subsampling of documents.
            It is used in calculate bound in online learning.

        Returns
        -------
        score : float

        c           
      6   t          j        | |z
  |z            }|t          j        t          |          t          |           z
            z  }|t          j        t          | |z            t          t          j        |d                    z
            z  }|S )Nr   )r(   r   r   )priordistrdirichlet_distrsizescores        rU   _loglikelihoodz?LatentDirichletAllocation._approx_bound.<locals>._loglikelihood&  s}    FEEM_<==ERVGENNWU^^;<<<ERVGEDL11GBF5!<L<L4M4MMNNNELrW   r   r   Nr   )r#   r$   r%   r|   r   rz   r{   r,   r-   r.   r4   r(   r5   r   r   r6   rZ   r!   ri   )rt   r9   rD   r   r   r@   rA   rZ   rB   r   dirichlet_doc_topicdirichlet_component_r;   r^   rG   rH   rI   rL   rM   rN   temprT   r   s                          rU   _approx_boundz'LatentDirichletAllocation._approx_bound  s   4	 	 	 k!nn"1"7	<%+A.
7HH89IJJ/1 	 VF	IxH 1i(( 	, 	,E %(5192E EFhuo0CCDj5!!!8--a0}#E111bj$89<PQRQRQRTWQW<XX  !A...HRVD(+++EE 	_.A4CT
 
 	

  	d011I=IYE 	d.0Dj
 
 	
 rW   c                     t          |            |                     |dd          }|                     |          }|                     ||d          }|S )a  Calculate approximate log-likelihood as score.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Document word matrix.

        y : Ignored
            Not used, present here for API consistency by convention.

        Returns
        -------
        score : float
            Use approximate bound as score.
        FzLatentDirichletAllocation.scorer   r   )r   r   r   r   )rt   r9   r   rD   r   s        rU   r   zLatentDirichletAllocation.score[  sh      	%%,M & 
 
 66q99""1oE"JJrW   Fc                    ||                      |          }nD|j        \  }}||j        d         k    rt          d          || j        k    rt          d          |j        d         }|                     |||          }|r-|                                t          | j                  |z  z  }n|                                }||z  }	t          j	        d|	z            S )at  Calculate approximate perplexity for data X with ability to accept
        precomputed doc_topic_distr

        Perplexity is defined as exp(-1. * log-likelihood per word)

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Document word matrix.

        doc_topic_distr : ndarray of shape (n_samples, n_components),                 default=None
            Document topic distribution.
            If it is None, it will be generated by applying transform on X.

        Returns
        -------
        score : float
            Perplexity score.
        Nr   z8Number of samples in X and doc_topic_distr do not match.z Number of topics does not match.g      )
r   r%   r   rZ   r   r   r!   ri   r(   r*   )
rt   r9   rD   r   rA   rZ   current_samplesr   word_cntperword_bounds
             rU   r   z3LatentDirichletAllocation._perplexity_precomp_distrt  s    * ""::1==OO&5&;#I|AGAJ&& N   t000 !CDDD'!*""1o|DD 	uuww%(:";";o"MNHHuuwwH(vd]*+++rW   c                 ~    t          |            |                     |dd          }|                     ||          S )aW  Calculate approximate perplexity for data X.

        Perplexity is defined as exp(-1. * log-likelihood per word)

        .. versionchanged:: 0.19
           *doc_topic_distr* argument has been deprecated and is ignored
           because user no longer has access to unnormalized distribution

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Document word matrix.

        sub_sampling : bool
            Do sub-sampling or not.

        Returns
        -------
        score : float
            Perplexity score.
        Tz$LatentDirichletAllocation.perplexityr   r   )r   r   r   )rt   r9   r   s      rU   
perplexityz$LatentDirichletAllocation.perplexity  sO    , 	%%+Q & 
 
 --al-KKKrW   c                 &    | j         j        d         S )z&Number of transformed output features.r   )r|   r%   )rt   s    rU   _n_features_outz)LatentDirichletAllocation._n_features_out  s     %a((rW   )rn   rs   )NF)F) __name__
__module____qualname____doc__r   r   r   r   rm   dict__annotations__ru   r(   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   propertyr   __classcell__)r   s   @rU   rY   rY      s        o ob$(AtIFFFG$D((4Af"E"E"EF$ 	T88D!Qv#F#F#FG$ 	JJ':;;<	$
 	88D!Qv>>>?$ 	HHT3VDDDE$ 	XXh4???@$ 	xx!T)DDDE$ 	88HdDKKKL$ 	((4DCCCD$ 	XXdAtF;;;<$ 	HHT1d6BBBC$ 	1d6 J J JK$ 	4"$ 	I;$  	(!$D   * #) %#) #) #) #) #)J 35* 
 
 
 
:@- @- @- @-D4 4 4 4l      . \555- - - 65-^ \555P P P 65Pd  " )-     8@D @ @ @ @ @2M M M^   2*, *, *, *,XL L L L8 ) ) X) ) ) ) )rW   rY   )-r   numbersr   r   numpyr(   scipy.sparser   r#   joblibr   scipy.specialr   r   baser	   r
   r   r   utilsr   r   r   utils._param_validationr   r   utils.parallelr   r   utils.validationr   r   r   _online_lda_fastr   r1   r   r   r0   r2   r!   r3   EPSrV   rY    rW   rU   <module>r      s    # " " " " " " "           # # # # # # , , , , , , , ,            E D D D D D D D D D : : : : : : : : . . . . . . . . Q Q Q Q Q Q Q Q Q Q                bhuoou) u) u)p[) [) [) [) [)#%5}[) [) [) [) [)rW   