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_componentsint, default=10

主题数。

版本 0.19 中的变更: n_topics 已重命名为 n_components

doc_topic_priorfloat, default=None

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

topic_word_priorfloat, default=None

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

learning_method{‘batch’, ‘online’}, default=’batch’

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

有效选项

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

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

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

learning_decayfloat, default=0.7

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

learning_offsetfloat, default=10.0

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

max_iterint, default=10

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

batch_sizeint, default=128

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

evaluate_everyint, default=-1

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

total_samplesint, default=1e6

文档总数。仅在 partial_fit 方法中使用。

perp_tolfloat, default=1e-1

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

mean_change_tolfloat, default=1e-3

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

max_doc_update_iterint, default=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)

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

exp_dirichlet_component_shape 为 (n_components, n_features) 的 ndarray

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

n_batch_iter_int

EM 步骤的迭代次数。

n_features_in_int

拟合 期间看到的特征数。

0.24 版本新增。

feature_names_in_shape 为 (n_features_in_,) 的 ndarray

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

1.0 版本新增。

n_iter_int

数据集的遍历次数。

bound_float

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

doc_topic_prior_float

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

random_state_RandomState instance

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

topic_word_prior_float

主题词分布 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/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_newshape 为 (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]#

使用 Mini-Batch 更新进行在线 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. * log-likelihood per word)

版本 0.19 中的变更: doc_topic_distr 参数已被弃用并被忽略,因为用户不再能访问未归一化的分布。

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

文档词矩阵。

sub_samplingbool

是否进行子采样。

返回:
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]#

设置输出容器。

有关如何使用 API 的示例,请参阅引入 set_output 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 中新增。

参数:
normalizestr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

transformnormalize 参数的元数据路由。

返回:
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_distrshape 为 (n_samples, n_components) 的 ndarray

X 的文档主题分布。