LatentDirichletAllocation#

class sklearn.decomposition.LatentDirichletAllocation(n_components=10, *, doc_topic_prior=None, topic_word_prior=None, learning_method='batch', learning_decay=0.7, learning_offset=10.0, max_iter=10, batch_size=128, evaluate_every=-1, total_samples=1000000.0, perp_tol=0.1, mean_change_tol=0.001, max_doc_update_iter=100, n_jobs=None, verbose=0, random_state=None)[source]#

使用在线变分贝叶斯算法的潜在狄利克雷分配。

此实现基于[1][2]

版本0.17中新增。

用户指南中阅读更多内容。

参数:
n_components整型, 默认值=10

主题数量。

在版本0.19中更改: n_topics已重命名为n_components

doc_topic_prior浮点型, 默认值=无

文档主题分布theta的先验。如果值为None,则默认为1 / n_components。在[1]中,这称为alpha

topic_word_prior浮点型, 默认值=无

主题词分布beta的先验。如果值为None,则默认为1 / n_components。在[1]中,这称为eta

learning_method{'batch', 'online'}, 默认值='batch'

用于更新_component的方法。仅用于fit方法。通常,如果数据量很大,在线更新会比批处理更新快得多。

有效选项

  • ‘batch’: 批处理变分贝叶斯方法。在每次EM更新中使用所有训练数据。旧的components_将在每次迭代中被覆盖。

  • ‘online’: 在线变分贝叶斯方法。在每次EM更新中,使用小批量训练数据来递增更新components_变量。学习率由learning_decaylearning_offset参数控制。

在版本0.20中更改: 默认学习方法现在是"batch"

learning_decay浮点型, 默认值=0.7

这是一个在在线学习方法中控制学习率的参数。该值应设置在(0.5, 1.0]之间以保证渐近收敛。当值为0.0且batch_size是n_samples时,更新方法与批处理学习相同。在文献中,这称为kappa。

learning_offset浮点型, 默认值=10.0

一个(正)参数,用于在线学习中降低早期迭代的权重。它应该大于1.0。在文献中,这称为tau_0。

max_iter整型, 默认值=10

训练数据(又称时期)的最大遍历次数。它只影响fit方法的行为,而不影响partial_fit方法的行为。

batch_size整型, 默认值=128

每次EM迭代中使用的文档数量。仅用于在线学习。

evaluate_every整型, 默认值=-1

评估困惑度的频率。仅用于fit方法。将其设置为0或负数以完全不评估训练中的困惑度。评估困惑度可以帮助您检查训练过程中的收敛性,但也会增加总训练时间。在每次迭代中评估困惑度可能会使训练时间增加一倍。

total_samples整型, 默认值=1e6

文档总数。仅用于partial_fit方法。

perp_tol浮点型, 默认值=1e-1

困惑度容差。仅当evaluate_every大于0时使用。

mean_change_tol浮点型, 默认值=1e-3

E步中更新文档主题分布的停止容差。

max_doc_update_iter整型, 默认值=100

E步中更新文档主题分布的最大迭代次数。

n_jobsint, default=None

E步中使用的作业数。None表示1,除非在joblib.parallel_backend上下文中。-1表示使用所有处理器。有关详细信息,请参阅术语表

verboseint, default=0

详细程度。

random_stateint, RandomState instance or None, default=None

传入一个整数,以便在多次函数调用中获得可重现的结果。请参阅 词汇表

属性:
components_ndarray of shape (n_components, n_features)

主题词分布的变分参数。由于主题词分布的完全条件是狄利克雷分布,components_[i, j]可以看作是伪计数,表示词j被分配给主题i的次数。归一化后,它也可以被看作每个主题的词分布:model.components_ / model.components_.sum(axis=1)[:, np.newaxis]

exp_dirichlet_component_形状为 (n_components, n_features) 的ndarray

对数主题词分布期望的指数值。在文献中,这是exp(E[log(beta)])

n_batch_iter_整型

EM步的迭代次数。

n_features_in_int

拟合 期间看到的特征数。

0.24 版本新增。

feature_names_in_shape 为 (n_features_in_,) 的 ndarray

fit 期间看到的特征名称。仅当 X 具有全部为字符串的特征名称时才定义。

1.0 版本新增。

n_iter_int

数据集的遍历次数。

bound_浮点型

训练集上的最终困惑度分数。

doc_topic_prior_浮点型

文档主题分布theta的先验。如果值为None,则为1 / n_components

random_state_RandomState实例

RandomState实例,由种子、随机数生成器或np.random生成。

topic_word_prior_浮点型

主题词分布beta的先验。如果值为None,则为1 / n_components

另请参阅

sklearn.discriminant_analysis.LinearDiscriminantAnalysis

一个具有线性决策边界的分类器,通过将类条件密度拟合到数据并使用贝叶斯规则生成。

References

[1] (1,2,3)

“在线学习潜在狄利克雷分配 (Online Learning for Latent Dirichlet Allocation)”,Matthew D. Hoffman, David M. Blei, Francis Bach, 2010。blei-lab/onlineldavb

[2]

“随机变分推断 (Stochastic Variational Inference)”,Matthew D. Hoffman, David M. Blei, Chong Wang, John Paisley, 2013。https://jmlr.org.cn/papers/volume14/hoffman13a/hoffman13a.pdf

示例

>>> 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  ]])
fit(X, y=None)[source]#

使用变分贝叶斯方法学习数据X的模型。

learning_method是'online'时,使用小批量更新。否则,使用批处理更新。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

文档词矩阵。

y被忽略

Not used, present here for API consistency by convention.

返回:
self

拟合的估计器。

fit_transform(X, y=None, *, normalize=True)[source]#

拟合数据,然后对其进行转换。

将转换器拟合到Xy,并返回X的转换版本。

参数:
Xshape 为 (n_samples, n_features) 的 array-like

输入样本。

y形状为 (n_samples,) 或 (n_samples, n_outputs) 的类数组对象,默认=None

目标值(对于无监督转换,为 None)。

normalizebool, default=True

是否在transform中对文档主题分布进行归一化。

返回:
X_new形状为 (n_samples, n_components) 的ndarray数组

转换后的数组。

get_feature_names_out(input_features=None)[source]#

获取转换的输出特征名称。

The feature names out will prefixed by the lowercased class name. For example, if the transformer outputs 3 features, then the feature names out are: ["class_name0", "class_name1", "class_name2"].

参数:
input_featuresarray-like of str or None, default=None

Only used to validate feature names with the names seen in fit.

返回:
feature_names_outstr 对象的 ndarray

转换后的特征名称。

get_metadata_routing()[source]#

获取此对象的元数据路由。

请查阅 用户指南,了解路由机制如何工作。

返回:
routingMetadataRequest

封装路由信息的 MetadataRequest

get_params(deep=True)[source]#

获取此估计器的参数。

参数:
deepbool, default=True

如果为 True,将返回此估计器以及包含的子对象(如果它们是估计器)的参数。

返回:
paramsdict

参数名称映射到其值。

partial_fit(X, y=None)[source]#

带有小批量更新的在线VB。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

文档词矩阵。

y被忽略

Not used, present here for API consistency by convention.

返回:
self

部分拟合的估计器。

perplexity(X, sub_sampling=False)[source]#

计算数据X的近似困惑度。

困惑度定义为 exp(-1. * 每个词的对数似然)。

在版本0.19中更改: doc_topic_distr 参数已弃用并被忽略,因为用户无法再访问未归一化分布

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

文档词矩阵。

sub_sampling布尔型

是否进行子采样。

返回:
scorefloat

困惑度分数。

score(X, y=None)[source]#

计算近似对数似然作为分数。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

文档词矩阵。

y被忽略

Not used, present here for API consistency by convention.

返回:
scorefloat

使用近似边界作为分数。

set_output(*, transform=None)[source]#

设置输出容器。

请参阅 用户指南 以了解更多详细信息,并参考 引入 set_output API 获取关于如何使用该 API 的示例。

参数:
transform{“default”, “pandas”, “polars”}, default=None

配置 transformfit_transform 的输出。

  • "default": 转换器的默认输出格式

  • "pandas": DataFrame 输出

  • "polars": Polars 输出

  • None: 转换配置保持不变

1.4 版本新增: 添加了 "polars" 选项。

返回:
selfestimator instance

估计器实例。

set_params(**params)[source]#

设置此估计器的参数。

此方法适用于简单的估计器以及嵌套对象(如 Pipeline)。后者具有 <component>__<parameter> 形式的参数,以便可以更新嵌套对象的每个组件。

参数:
**paramsdict

估计器参数。

返回:
selfestimator instance

估计器实例。

set_transform_request(*, normalize: bool | None | str = '$UNCHANGED$') LatentDirichletAllocation[source]#

配置是否应请求元数据以传递给 transform 方法。

请注意,此方法仅在以下情况下相关:此估计器用作 元估计器 中的子估计器,并且通过 enable_metadata_routing=True 启用了元数据路由(请参阅 sklearn.set_config)。请查看 用户指南 以了解路由机制的工作原理。

每个参数的选项如下:

  • True:请求元数据,如果提供则传递给 transform。如果未提供元数据,则忽略该请求。

  • False:不请求元数据,并且元估计器不会将其传递给 transform

  • None:不请求元数据,如果用户提供元数据,元估计器将引发错误。

  • str:应将元数据以给定别名而不是原始名称传递给元估计器。

默认值 (sklearn.utils.metadata_routing.UNCHANGED) 保留现有请求。这允许您更改某些参数的请求而不更改其他参数。

在版本 1.3 中新增。

参数:
normalize字符串, True, False, 或 None, 默认值=sklearn.utils.metadata_routing.UNCHANGED

参数normalizetransform中的元数据路由。

返回:
selfobject

更新后的对象。

transform(X, *, normalize=True)[source]#

根据拟合模型转换数据X。

在版本0.18中更改: doc_topic_distr现在已归一化。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

文档词矩阵。

normalizebool, default=True

是否对文档主题分布进行归一化。

返回:
doc_topic_distr形状为 (n_samples, n_components) 的ndarray

X的文档主题分布。