2.5. Decomposing signals in components (matrix factorization problems)

2.5.1. Principal component analysis (PCA)

2.5.1.1. Exact PCA and probabilistic interpretation

PCA is used to decompose a multivariate dataset in a set of successiveorthogonal components that explain a maximum amount of the variance. Inscikit-learn, PCA is implemented as a transformer objectthat learns

2.5. Decomposing signals in components (matrix factorization problems) - 图1 components in its fit method, and can be used on newdata to project it on these components.

PCA centers but does not scale the input data for each feature beforeapplying the SVD. The optional parameter whiten=True makes itpossible to project the data onto the singular space while scaling eachcomponent to unit variance. This is often useful if the models down-stream makestrong assumptions on the isotropy of the signal: this is for example the casefor Support Vector Machines with the RBF kernel and the K-Means clusteringalgorithm.

Below is an example of the iris dataset, which is comprised of 4features, projected on the 2 dimensions that explain most variance:

../_images/sphx_glr_plot_pca_vs_lda_0011.png

The PCA object also provides aprobabilistic interpretation of the PCA that can give a likelihood ofdata based on the amount of variance it explains. As such it implements ascore method that can be used in cross-validation:

../_images/sphx_glr_plot_pca_vs_fa_model_selection_0011.png

Examples:

2.5.1.2. Incremental PCA

The PCA object is very useful, but has certain limitations forlarge datasets. The biggest limitation is that PCA only supportsbatch processing, which means all of the data to be processed must fit in mainmemory. The IncrementalPCA object uses a different form ofprocessing and allows for partial computations which almostexactly match the results of PCA while processing the data in aminibatch fashion. IncrementalPCA makes it possible to implementout-of-core Principal Component Analysis either by:

  • Using its partial_fit method on chunks of data fetched sequentiallyfrom the local hard drive or a network database.

  • Calling its fit method on a sparse matrix or a memory mapped file usingnumpy.memmap.

IncrementalPCA only stores estimates of component and noise variances,in order update explainedvariance_ratio incrementally. This is whymemory usage depends on the number of samples per batch, rather than thenumber of samples to be processed in the dataset.

As in PCA, IncrementalPCA centers but does not scale theinput data for each feature before applying the SVD.

../_images/sphx_glr_plot_incremental_pca_0011.png

../_images/sphx_glr_plot_incremental_pca_0021.png

Examples:

2.5.1.3. PCA using randomized SVD

It is often interesting to project data to a lower-dimensionalspace that preserves most of the variance, by dropping the singular vectorof components associated with lower singular values.

For instance, if we work with 64x64 pixel gray-level picturesfor face recognition,the dimensionality of the data is 4096 and it is slow to train anRBF support vector machine on such wide data. Furthermore we know thatthe intrinsic dimensionality of the data is much lower than 4096 since allpictures of human faces look somewhat alike.The samples lie on a manifold of much lowerdimension (say around 200 for instance). The PCA algorithm can be usedto linearly transform the data while both reducing the dimensionalityand preserve most of the explained variance at the same time.

The class PCA used with the optional parametersvd_solver='randomized' is very useful in that case: since we are goingto drop most of the singular vectors it is much more efficient to limit thecomputation to an approximated estimate of the singular vectors we will keepto actually perform the transform.

For instance, the following shows 16 sample portraits (centered around0.0) from the Olivetti dataset. On the right hand side are the first 16singular vectors reshaped as portraits. Since we only require the top16 singular vectors of a dataset with size

2.5. Decomposing signals in components (matrix factorization problems) - 图6and2.5. Decomposing signals in components (matrix factorization problems) - 图7, the computation time isless than 1s:

orig_imgpca_img

If we note

2.5. Decomposing signals in components (matrix factorization problems) - 图10 and2.5. Decomposing signals in components (matrix factorization problems) - 图11, the time complexityof the randomized PCA is2.5. Decomposing signals in components (matrix factorization problems) - 图12instead of2.5. Decomposing signals in components (matrix factorization problems) - 图13 for the exact methodimplemented in PCA.

The memory footprint of randomized PCA is also proportional to

2.5. Decomposing signals in components (matrix factorization problems) - 图14 instead of2.5. Decomposing signals in components (matrix factorization problems) - 图15 for the exact method.

Note: the implementation of inverse_transform in PCA withsvd_solver='randomized' is not the exact inverse transform oftransform even when whiten=False (default).

Examples:

References:

2.5.1.4. Kernel PCA

KernelPCA is an extension of PCA which achieves non-lineardimensionality reduction through the use of kernels (see Pairwise metrics, Affinities and Kernels). Ithas many applications including denoising, compression and structuredprediction (kernel dependency estimation). KernelPCA supports bothtransform and inverse_transform.

../_images/sphx_glr_plot_kernel_pca_0011.png

Examples:

2.5.1.5. Sparse principal components analysis (SparsePCA and MiniBatchSparsePCA)

SparsePCA is a variant of PCA, with the goal of extracting theset of sparse components that best reconstruct the data.

Mini-batch sparse PCA (MiniBatchSparsePCA) is a variant ofSparsePCA that is faster but less accurate. The increased speed isreached by iterating over small chunks of the set of features, for a givennumber of iterations.

Principal component analysis (PCA) has the disadvantage that thecomponents extracted by this method have exclusively dense expressions, i.e.they have non-zero coefficients when expressed as linear combinations of theoriginal variables. This can make interpretation difficult. In many cases,the real underlying components can be more naturally imagined as sparsevectors; for example in face recognition, components might naturally map toparts of faces.

Sparse principal components yields a more parsimonious, interpretablerepresentation, clearly emphasizing which of the original features contributeto the differences between samples.

The following example illustrates 16 components extracted using sparse PCA fromthe Olivetti faces dataset. It can be seen how the regularization term inducesmany zeros. Furthermore, the natural structure of the data causes the non-zerocoefficients to be vertically adjacent. The model does not enforce thismathematically: each component is a vector

2.5. Decomposing signals in components (matrix factorization problems) - 图17, andthere is no notion of vertical adjacency except during the human-friendlyvisualization as 64x64 pixel images. The fact that the components shown belowappear local is the effect of the inherent structure of the data, which makessuch local patterns minimize reconstruction error. There exist sparsity-inducingnorms that take into account adjacency and different kinds of structure; see[Jen09] for a review of such methods.For more details on how to use Sparse PCA, see the Examples section, below.

pca_imgspca_img

Note that there are many different formulations for the Sparse PCAproblem. The one implemented here is based on [Mrl09] . The optimizationproblem solved is a PCA problem (dictionary learning) with an

2.5. Decomposing signals in components (matrix factorization problems) - 图20 penalty on the components:

2.5. Decomposing signals in components (matrix factorization problems) - 图21

The sparsity-inducing

2.5. Decomposing signals in components (matrix factorization problems) - 图22 norm also prevents learningcomponents from noise when few training samples are available. The degreeof penalization (and thus sparsity) can be adjusted through thehyperparameter alpha. Small values lead to a gently regularizedfactorization, while larger values shrink many coefficients to zero.

Note

While in the spirit of an online algorithm, the classMiniBatchSparsePCA does not implement partial_fit becausethe algorithm is online along the features direction, not the samplesdirection.

Examples:

References:

2.5.2. Truncated singular value decomposition and latent semantic analysis

TruncatedSVD implements a variant of singular value decomposition(SVD) that only computes the

2.5. Decomposing signals in components (matrix factorization problems) - 图23 largest singular values,where2.5. Decomposing signals in components (matrix factorization problems) - 图24 is a user-specified parameter.

When truncated SVD is applied to term-document matrices(as returned by CountVectorizer or TfidfVectorizer),this transformation is known aslatent semantic analysis(LSA), because it transforms such matricesto a “semantic” space of low dimensionality.In particular, LSA is known to combat the effects of synonymy and polysemy(both of which roughly mean there are multiple meanings per word),which cause term-document matrices to be overly sparseand exhibit poor similarity under measures such as cosine similarity.

Note

LSA is also known as latent semantic indexing, LSI,though strictly that refers to its use in persistent indexesfor information retrieval purposes.

Mathematically, truncated SVD applied to training samples

2.5. Decomposing signals in components (matrix factorization problems) - 图25produces a low-rank approximation2.5. Decomposing signals in components (matrix factorization problems) - 图26:

2.5. Decomposing signals in components (matrix factorization problems) - 图27

After this operation,

2.5. Decomposing signals in components (matrix factorization problems) - 图28is the transformed training set with2.5. Decomposing signals in components (matrix factorization problems) - 图29 features(called n_components in the API).

To also transform a test set

2.5. Decomposing signals in components (matrix factorization problems) - 图30, we multiply it with2.5. Decomposing signals in components (matrix factorization problems) - 图31:

2.5. Decomposing signals in components (matrix factorization problems) - 图32

Note

Most treatments of LSA in the natural language processing (NLP)and information retrieval (IR) literatureswap the axes of the matrix

2.5. Decomposing signals in components (matrix factorization problems) - 图33 so that it has shapen_features × n_samples.We present LSA in a different way that matches the scikit-learn API better,but the singular values found are the same.

TruncatedSVD is very similar to PCA, but differsin that it works on sample matrices

2.5. Decomposing signals in components (matrix factorization problems) - 图34 directlyinstead of their covariance matrices.When the columnwise (per-feature) means of2.5. Decomposing signals in components (matrix factorization problems) - 图35are subtracted from the feature values,truncated SVD on the resulting matrix is equivalent to PCA.In practical terms, this meansthat the TruncatedSVD transformer accepts scipy.sparsematrices without the need to densify them,as densifying may fill up memory even for medium-sized document collections.

While the TruncatedSVD transformerworks with any (sparse) feature matrix,using it on tf–idf matrices is recommended over raw frequency countsin an LSA/document processing setting.In particular, sublinear scaling and inverse document frequencyshould be turned on (sublinear_tf=True, use_idf=True)to bring the feature values closer to a Gaussian distribution,compensating for LSA’s erroneous assumptions about textual data.

Examples:

References:

2.5.3. Dictionary Learning

2.5.3.1. Sparse coding with a precomputed dictionary

The SparseCoder object is an estimator that can be used to transform signalsinto sparse linear combination of atoms from a fixed, precomputed dictionarysuch as a discrete wavelet basis. This object therefore does notimplement a fit method. The transformation amountsto a sparse coding problem: finding a representation of the data as a linearcombination of as few dictionary atoms as possible. All variations ofdictionary learning implement the following transform methods, controllable viathe transform_method initialization parameter:

Thresholding is very fast but it does not yield accurate reconstructions.They have been shown useful in literature for classification tasks. For imagereconstruction tasks, orthogonal matching pursuit yields the most accurate,unbiased reconstruction.

The dictionary learning objects offer, via the split_code parameter, thepossibility to separate the positive and negative values in the results ofsparse coding. This is useful when dictionary learning is used for extractingfeatures that will be used for supervised learning, because it allows thelearning algorithm to assign different weights to negative loadings of aparticular atom, from to the corresponding positive loading.

The split code for a single sample has length 2 * n_componentsand is constructed using the following rule: First, the regular code of lengthn_components is computed. Then, the first n_components entries of thesplit_code arefilled with the positive part of the regular code vector. The second half ofthe split code is filled with the negative part of the code vector, only witha positive sign. Therefore, the split_code is non-negative.

Examples:

2.5.3.2. Generic dictionary learning

Dictionary learning (DictionaryLearning) is a matrix factorizationproblem that amounts to finding a (usually overcomplete) dictionary that willperform well at sparsely encoding the fitted data.

Representing data as sparse combinations of atoms from an overcompletedictionary is suggested to be the way the mammalian primary visual cortex works.Consequently, dictionary learning applied on image patches has been shown togive good results in image processing tasks such as image completion,inpainting and denoising, as well as for supervised recognition tasks.

Dictionary learning is an optimization problem solved by alternatively updatingthe sparse code, as a solution to multiple Lasso problems, considering thedictionary fixed, and then updating the dictionary to best fit the sparse code.

2.5. Decomposing signals in components (matrix factorization problems) - 图36

pca_img2dict_img2

After using such a procedure to fit the dictionary, the transform is simply asparse coding step that shares the same implementation with all dictionarylearning objects (see Sparse coding with a precomputed dictionary).

It is also possible to constrain the dictionary and/or code to be positive tomatch constraints that may be present in the data. Below are the faces withdifferent positivity constraints applied. Red indicates negative values, blueindicates positive values, and white represents zeros.

dict_img_pos1dict_img_pos2

dict_img_pos3dict_img_pos4

The following image shows how a dictionary learned from 4x4 pixel image patchesextracted from part of the image of a raccoon face looks like.

../_images/sphx_glr_plot_image_denoising_0011.png

Examples:

References:

2.5.3.3. Mini-batch dictionary learning

MiniBatchDictionaryLearning implements a faster, but less accurateversion of the dictionary learning algorithm that is better suited for largedatasets.

By default, MiniBatchDictionaryLearning divides the data intomini-batches and optimizes in an online manner by cycling over the mini-batchesfor the specified number of iterations. However, at the moment it does notimplement a stopping condition.

The estimator also implements partial_fit, which updates the dictionary byiterating only once over a mini-batch. This can be used for online learningwhen the data is not readily available from the start, or for when the datadoes not fit into the memory.../_images/sphx_glr_plot_dict_face_patches_0011.png

Clustering for dictionary learning

Note that when using dictionary learning to extract a representation(e.g. for sparse coding) clustering can be a good proxy to learn thedictionary. For instance the MiniBatchKMeans estimator iscomputationally efficient and implements on-line learning with apartial_fit method.

2.5.4. Factor Analysis

In unsupervised learning we only have a dataset

2.5. Decomposing signals in components (matrix factorization problems) - 图45. How can this dataset be described mathematically? A very simplecontinuous latent variable model for2.5. Decomposing signals in components (matrix factorization problems) - 图46 is

2.5. Decomposing signals in components (matrix factorization problems) - 图47

The vector

2.5. Decomposing signals in components (matrix factorization problems) - 图48 is called “latent” because it is unobserved.2.5. Decomposing signals in components (matrix factorization problems) - 图49 isconsidered a noise term distributed according to a Gaussian with mean 0 andcovariance2.5. Decomposing signals in components (matrix factorization problems) - 图50 (i.e.2.5. Decomposing signals in components (matrix factorization problems) - 图51),2.5. Decomposing signals in components (matrix factorization problems) - 图52 is somearbitrary offset vector. Such a model is called “generative” as it describeshow2.5. Decomposing signals in components (matrix factorization problems) - 图53 is generated from2.5. Decomposing signals in components (matrix factorization problems) - 图54. If we use all the2.5. Decomposing signals in components (matrix factorization problems) - 图55’s as columns to forma matrix2.5. Decomposing signals in components (matrix factorization problems) - 图56 and all the2.5. Decomposing signals in components (matrix factorization problems) - 图57’s as columns of a matrix2.5. Decomposing signals in components (matrix factorization problems) - 图58then we can write (with suitably defined2.5. Decomposing signals in components (matrix factorization problems) - 图59 and2.5. Decomposing signals in components (matrix factorization problems) - 图60):

2.5. Decomposing signals in components (matrix factorization problems) - 图61

In other words, we decomposed matrix

2.5. Decomposing signals in components (matrix factorization problems) - 图62.

If

2.5. Decomposing signals in components (matrix factorization problems) - 图63 is given, the above equation automatically implies the followingprobabilistic interpretation:

2.5. Decomposing signals in components (matrix factorization problems) - 图64

For a complete probabilistic model we also need a prior distribution for thelatent variable

2.5. Decomposing signals in components (matrix factorization problems) - 图65. The most straightforward assumption (based on the niceproperties of the Gaussian distribution) is2.5. Decomposing signals in components (matrix factorization problems) - 图66. This yields a Gaussian as the marginal distribution of2.5. Decomposing signals in components (matrix factorization problems) - 图67:

2.5. Decomposing signals in components (matrix factorization problems) - 图68

Now, without any further assumptions the idea of having a latent variable

2.5. Decomposing signals in components (matrix factorization problems) - 图69would be superfluous –2.5. Decomposing signals in components (matrix factorization problems) - 图70 can be completely modelled with a meanand a covariance. We need to impose some more specific structure on oneof these two parameters. A simple additional assumption regards thestructure of the error covariance2.5. Decomposing signals in components (matrix factorization problems) - 图71:

2.5. Decomposing signals in components (matrix factorization problems) - 图72: This assumption leads tothe probabilistic model of PCA.

2.5. Decomposing signals in components (matrix factorization problems) - 图73: This model is calledFactorAnalysis, a classical statistical model. The matrix W issometimes called the “factor loading matrix”.

Both models essentially estimate a Gaussian with a low-rank covariance matrix.Because both models are probabilistic they can be integrated in more complexmodels, e.g. Mixture of Factor Analysers. One gets very different models (e.g.FastICA) if non-Gaussian priors on the latent variables are assumed.

Factor analysis can produce similar components (the columns of its loadingmatrix) to PCA. However, one can not make any general statementsabout these components (e.g. whether they are orthogonal):

pca_img3fa_img3

The main advantage for Factor Analysis over PCA is thatit can model the variance in every direction of the input space independently(heteroscedastic noise):

../_images/sphx_glr_plot_faces_decomposition_0081.png

This allows better model selection than probabilistic PCA in the presenceof heteroscedastic noise:

../_images/sphx_glr_plot_pca_vs_fa_model_selection_0021.png

Examples:

2.5.5. Independent component analysis (ICA)

Independent component analysis separates a multivariate signal intoadditive subcomponents that are maximally independent. It isimplemented in scikit-learn using the Fast ICAalgorithm. Typically, ICA is not used for reducing dimensionality butfor separating superimposed signals. Since the ICA model does not includea noise term, for the model to be correct, whitening must be applied.This can be done internally using the whiten argument or manually using oneof the PCA variants.

It is classically used to separate mixed signals (a problem known asblind source separation), as in the example below:

../_images/sphx_glr_plot_ica_blind_source_separation_0011.png

ICA can also be used as yet another non linear decomposition that findscomponents with some sparsity:

pca_img4ica_img4

Examples:

2.5.6. Non-negative matrix factorization (NMF or NNMF)

2.5.6.1. NMF with the Frobenius norm

NMF1 is an alternative approach to decomposition that assumes that thedata and the components are non-negative. NMF can be plugged ininstead of PCA or its variants, in the cases where the data matrixdoes not contain negative values. It finds a decomposition of samples

2.5. Decomposing signals in components (matrix factorization problems) - 图81 into two matrices2.5. Decomposing signals in components (matrix factorization problems) - 图82 and2.5. Decomposing signals in components (matrix factorization problems) - 图83 of non-negative elements,by optimizing the distance2.5. Decomposing signals in components (matrix factorization problems) - 图84 between2.5. Decomposing signals in components (matrix factorization problems) - 图85 and the matrix product2.5. Decomposing signals in components (matrix factorization problems) - 图86. The most widely used distance function is the squared Frobeniusnorm, which is an obvious extension of the Euclidean norm to matrices:

2.5. Decomposing signals in components (matrix factorization problems) - 图87

Unlike PCA, the representation of a vector is obtained in an additivefashion, by superimposing the components, without subtracting. Such additivemodels are efficient for representing images and text.

It has been observed in [Hoyer, 2004] 2 that, when carefully constrained,NMF can produce a parts-based representation of the dataset,resulting in interpretable models. The following example displays 16sparse components found by NMF from the images in the Olivettifaces dataset, in comparison with the PCA eigenfaces.

pca_img5nmf_img5

The init attribute determines the initialization method applied, whichhas a great impact on the performance of the method. NMF implements themethod Nonnegative Double Singular Value Decomposition. NNDSVD 4 is based ontwo SVD processes, one approximating the data matrix, the other approximatingpositive sections of the resulting partial SVD factors utilizing an algebraicproperty of unit rank matrices. The basic NNDSVD algorithm is better fit forsparse factorization. Its variants NNDSVDa (in which all zeros are set equal tothe mean of all elements of the data), and NNDSVDar (in which the zeros are setto random perturbations less than the mean of the data divided by 100) arerecommended in the dense case.

Note that the Multiplicative Update (‘mu’) solver cannot update zeros present inthe initialization, so it leads to poorer results when used jointly with thebasic NNDSVD algorithm which introduces a lot of zeros; in this case, NNDSVDa orNNDSVDar should be preferred.

NMF can also be initialized with correctly scaled random non-negativematrices by setting init="random". An integer seed or aRandomState can also be passed to random_state to controlreproducibility.

In NMF, L1 and L2 priors can be added to the loss function in orderto regularize the model. The L2 prior uses the Frobenius norm, while the L1prior uses an elementwise L1 norm. As in ElasticNet, we control thecombination of L1 and L2 with the l1_ratio (

2.5. Decomposing signals in components (matrix factorization problems) - 图90) parameter,and the intensity of the regularization with the alpha(2.5. Decomposing signals in components (matrix factorization problems) - 图91) parameter. Then the priors terms are:

2.5. Decomposing signals in components (matrix factorization problems) - 图92

and the regularized objective function is:

2.5. Decomposing signals in components (matrix factorization problems) - 图93

NMF regularizes both W and H. The public functionnon_negative_factorization allows a finer control through theregularization attribute, and may regularize only W, only H, or both.

2.5.6.2. NMF with a beta-divergence

As described previously, the most widely used distance function is the squaredFrobenius norm, which is an obvious extension of the Euclidean norm tomatrices:

2.5. Decomposing signals in components (matrix factorization problems) - 图94

Other distance functions can be used in NMF as, for example, the (generalized)Kullback-Leibler (KL) divergence, also referred as I-divergence:

2.5. Decomposing signals in components (matrix factorization problems) - 图95

Or, the Itakura-Saito (IS) divergence:

2.5. Decomposing signals in components (matrix factorization problems) - 图96

These three distances are special cases of the beta-divergence family, with

2.5. Decomposing signals in components (matrix factorization problems) - 图97 respectively 6. The beta-divergence aredefined by :

2.5. Decomposing signals in components (matrix factorization problems) - 图98

../_images/sphx_glr_plot_beta_divergence_0011.png

Note that this definition is not valid if

2.5. Decomposing signals in components (matrix factorization problems) - 图100, yet it canbe continuously extended to the definitions of2.5. Decomposing signals in components (matrix factorization problems) - 图101 and2.5. Decomposing signals in components (matrix factorization problems) - 图102respectively.

NMF implements two solvers, using Coordinate Descent (‘cd’) 5, andMultiplicative Update (‘mu’) 6. The ‘mu’ solver can optimize everybeta-divergence, including of course the Frobenius norm (

2.5. Decomposing signals in components (matrix factorization problems) - 图103), the(generalized) Kullback-Leibler divergence (2.5. Decomposing signals in components (matrix factorization problems) - 图104) and theItakura-Saito divergence (2.5. Decomposing signals in components (matrix factorization problems) - 图105). Note that for2.5. Decomposing signals in components (matrix factorization problems) - 图106, the ‘mu’ solver is significantly faster than for othervalues of2.5. Decomposing signals in components (matrix factorization problems) - 图107. Note also that with a negative (or 0, i.e.‘itakura-saito’)2.5. Decomposing signals in components (matrix factorization problems) - 图108, the input matrix cannot contain zero values.

The ‘cd’ solver can only optimize the Frobenius norm. Due to theunderlying non-convexity of NMF, the different solvers may converge todifferent minima, even when optimizing the same distance function.

NMF is best used with the fittransform method, which returns the matrix W.The matrix H is stored into the fitted model in the components attribute;the method transform will decompose a new matrix X_new based on thesestored components:

>>>

  1. >>> import numpy as np
  2. >>> X = np.array([[1, 1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]])
  3. >>> from sklearn.decomposition import NMF
  4. >>> model = NMF(n_components=2, init='random', random_state=0)
  5. >>> W = model.fit_transform(X)
  6. >>> H = model.components_
  7. >>> X_new = np.array([[1, 0], [1, 6.1], [1, 0], [1, 4], [3.2, 1], [0, 4]])
  8. >>> W_new = model.transform(X_new)

Examples:

References:

2.5.7. Latent Dirichlet Allocation (LDA)

Latent Dirichlet Allocation is a generative probabilistic model for collections ofdiscrete dataset such as text corpora. It is also a topic model that is used fordiscovering abstract topics from a collection of documents.

The graphical model of LDA is a three-level generative model:../_images/lda_model_graph.pngNote on notations presented in the graphical model above, which can be found inHoffman et al. (2013):

  • The corpus is a collection of

    2.5. Decomposing signals in components (matrix factorization problems) - 图110
    documents.

  • A document is a sequence of

    2.5. Decomposing signals in components (matrix factorization problems) - 图111
    words.

  • There are

    2.5. Decomposing signals in components (matrix factorization problems) - 图112
    topics in the corpus.

  • The boxes represent repeated sampling.

In the graphical model, each node is a random variable and has a role in thegenerative process. A shaded node indicates an observed variable and an unshadednode indicates a hidden (latent) variable. In this case, words in the corpus arethe only data that we observe. The latent variables determine the random mixtureof topics in the corpus and the distribution of words in the documents.The goal of LDA is to use the observed words to infer the hidden topicstructure.

When modeling text corpora, the model assumes the following generative processfor a corpus with

2.5. Decomposing signals in components (matrix factorization problems) - 图113 documents and2.5. Decomposing signals in components (matrix factorization problems) - 图114 topics, with2.5. Decomposing signals in components (matrix factorization problems) - 图115corresponding to n_components in the API:

  1. For each topic

    2.5. Decomposing signals in components (matrix factorization problems) - 图116
    , draw
    2.5. Decomposing signals in components (matrix factorization problems) - 图117
    . This provides a distribution over the words,i.e. the probability of a word appearing in topic
    2.5. Decomposing signals in components (matrix factorization problems) - 图118
    .
    2.5. Decomposing signals in components (matrix factorization problems) - 图119
    corresponds to topic_word_prior.

  2. For each document

    2.5. Decomposing signals in components (matrix factorization problems) - 图120
    , draw the topic proportions
    2.5. Decomposing signals in components (matrix factorization problems) - 图121
    .
    2.5. Decomposing signals in components (matrix factorization problems) - 图122
    corresponds to doc_topic_prior.

  3. For each word

    2.5. Decomposing signals in components (matrix factorization problems) - 图123
    in document
    2.5. Decomposing signals in components (matrix factorization problems) - 图124
    :

  1. Draw the topic assignment

    2.5. Decomposing signals in components (matrix factorization problems) - 图125

  2. Draw the observed word

    2.5. Decomposing signals in components (matrix factorization problems) - 图126

For parameter estimation, the posterior distribution is:

2.5. Decomposing signals in components (matrix factorization problems) - 图127

Since the posterior is intractable, variational Bayesian methoduses a simpler distribution

2.5. Decomposing signals in components (matrix factorization problems) - 图128to approximate it, and those variational parameters2.5. Decomposing signals in components (matrix factorization problems) - 图129,2.5. Decomposing signals in components (matrix factorization problems) - 图130,2.5. Decomposing signals in components (matrix factorization problems) - 图131 are optimized to maximize the EvidenceLower Bound (ELBO):

2.5. Decomposing signals in components (matrix factorization problems) - 图132

Maximizing ELBO is equivalent to minimizing the Kullback-Leibler(KL) divergencebetween

2.5. Decomposing signals in components (matrix factorization problems) - 图133 and the true posterior2.5. Decomposing signals in components (matrix factorization problems) - 图134.

LatentDirichletAllocation implements the online variational Bayesalgorithm and supports both online and batch update methods.While the batch method updates variational variables after each full pass throughthe data, the online method updates variational variables from mini-batch datapoints.

Note

Although the online method is guaranteed to converge to a local optimum point, the quality ofthe optimum point and the speed of convergence may depend on mini-batch size andattributes related to learning rate setting.

When LatentDirichletAllocation is applied on a “document-term” matrix, the matrixwill be decomposed into a “topic-term” matrix and a “document-topic” matrix. While“topic-term” matrix is stored as components_ in the model, “document-topic” matrixcan be calculated from transform method.

LatentDirichletAllocation also implements partial_fit method. This is usedwhen data can be fetched sequentially.

Examples:

References:

See also Dimensionality reduction for dimensionality reduction withNeighborhood Components Analysis.