DictionaryLearning#

class sklearn.decomposition.DictionaryLearning(n_components=None, *, alpha=1, max_iter=1000, tol=1e-08, fit_algorithm='lars', transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, n_jobs=None, code_init=None, dict_init=None, callback=None, verbose=False, split_sign=False, random_state=None, positive_code=False, positive_dict=False, transform_max_iter=1000)[source]#

字典学习。

寻找一个字典(一组原子),该字典在对拟合数据进行稀疏编码时表现良好。

求解优化问题

(U^*,V^*) = argmin 0.5 || X - U V ||_Fro^2 + alpha * || U ||_1,1
            (U,V)
            with || V_k ||_2 <= 1 for all  0 <= k < n_components

||.||_Fro 代表 Frobenius 范数,||.||_1,1 代表逐项矩阵范数,它是矩阵中所有项的绝对值之和。

用户指南中了解更多信息。

参数:
n_componentsint, default=None

要提取的字典元素的数量。如果为 None,则将 n_components 设置为 n_features

alphafloat, default=1.0

稀疏性控制参数。

max_iterint, default=1000

要执行的最大迭代次数。

tolfloat, default=1e-8

数值误差的容忍度。

fit_algorithm{‘lars’, ‘cd’}, default=’lars’
  • 'lars': 使用最小角回归方法解决 lasso 问题(lars_path);

  • 'cd': 使用坐标下降方法计算 Lasso 解(Lasso)。如果估计的组件是稀疏的,Lars 会更快。

0.17 版本新增: cd 坐标下降方法以提高速度。

transform_algorithm{‘lasso_lars’, ‘lasso_cd’, ‘lars’, ‘omp’, ‘threshold’}, default=’omp’

用于转换数据的算法

  • 'lars': 使用最小角回归方法(lars_path);

  • 'lasso_lars': 使用 Lars 计算 Lasso 解。

  • 'lasso_cd': 使用坐标下降方法计算 Lasso 解(Lasso)。如果估计的组件是稀疏的,'lasso_lars' 会更快。

  • 'omp': 使用正交匹配追踪来估计稀疏解。

  • 'threshold': 将投影 dictionary * X' 中小于 alpha 的所有系数压缩为零。

0.17 版本新增: lasso_cd 坐标下降方法以提高速度。

transform_n_nonzero_coefsint, default=None

解中每列要定位的非零系数数量。这仅用于 algorithm='lars'algorithm='omp'。如果为 None,则 transform_n_nonzero_coefs=int(n_features / 10)

transform_alphafloat, default=None

如果 algorithm='lasso_lars'algorithm='lasso_cd'alpha 是应用于 L1 范数的惩罚项。如果 algorithm='threshold'alpha 是阈值的绝对值,低于该阈值的系数将被压缩为零。如果为 None,则默认为 alpha

1.2 版本更改: 当 None 时,默认值从 1.0 更改为 alpha

n_jobsint or None, default=None

要并行运行的作业数量。None 表示 1,除非在 joblib.parallel_backend 上下文中。-1 表示使用所有处理器。有关更多详细信息,请参阅词汇表

code_initndarray of shape (n_samples, n_components), default=None

代码的初始值,用于热启动。仅当 code_initdict_init 不为 None 时使用。

dict_initndarray of shape (n_components, n_features), default=None

字典的初始值,用于热启动。仅当 code_initdict_init 不为 None 时使用。

callbackcallable, default=None

每五次迭代调用一次的回调函数。

在版本 1.3 中新增。

verbosebool, default=False

控制过程的详细程度。

split_signbool, default=False

是否将稀疏特征向量拆分为其负部分和正部分的连接。这可以提高下游分类器的性能。

random_stateint, RandomState instance or None, default=None

用于在未指定 dict_init 时初始化字典,在 shuffle 设置为 True 时随机打乱数据,以及更新字典。传入一个整数可以在多次函数调用中获得可重现的结果。参阅词汇表

positive_codebool, default=False

查找代码时是否强制执行非负性。

0.20 版本新增。

positive_dictbool, default=False

查找字典时是否强制执行非负性。

0.20 版本新增。

transform_max_iterint, default=1000

如果 algorithm='lasso_cd''lasso_lars',要执行的最大迭代次数。

版本 0.22 新增。

属性:
components_ndarray of shape (n_components, n_features)

从数据中提取的字典原子

error_array

每次迭代的误差向量

n_features_in_int

拟合 期间看到的特征数。

0.24 版本新增。

feature_names_in_shape 为 (n_features_in_,) 的 ndarray

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

1.0 版本新增。

n_iter_int

运行的迭代次数。

另请参阅

MiniBatchDictionaryLearning

字典学习算法的一个更快、更不准确的版本。

MiniBatchSparsePCA

Mini-batch 稀疏主成分分析。

SparseCoder

从固定的、预先计算的字典中找到数据的稀疏表示。

SparsePCA

稀疏主成分分析。

References

J. Mairal, F. Bach, J. Ponce, G. Sapiro, 2009: Online dictionary learning for sparse coding (https://www.di.ens.fr/~fbach/mairal_icml09.pdf)

示例

>>> import numpy as np
>>> from sklearn.datasets import make_sparse_coded_signal
>>> from sklearn.decomposition import DictionaryLearning
>>> X, dictionary, code = make_sparse_coded_signal(
...     n_samples=30, n_components=15, n_features=20, n_nonzero_coefs=10,
...     random_state=42,
... )
>>> dict_learner = DictionaryLearning(
...     n_components=15, transform_algorithm='lasso_lars', transform_alpha=0.1,
...     random_state=42,
... )
>>> X_transformed = dict_learner.fit(X).transform(X)

我们可以检查 X_transformed 的稀疏度水平

>>> np.mean(X_transformed == 0)
np.float64(0.527)

我们可以比较稀疏编码信号的重构误差的平均平方欧几里得范数与原始信号的平方欧几里得范数

>>> X_hat = X_transformed @ dict_learner.components_
>>> np.mean(np.sum((X_hat - X) ** 2, axis=1) / np.sum(X ** 2, axis=1))
np.float64(0.056)
fit(X, y=None)[source]#

根据 X 中的数据拟合模型。

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

训练向量,其中 n_samples 是样本数,n_features 是特征数。

y被忽略

未使用,按照惯例为保持 API 一致性而存在。

返回:
selfobject

返回实例本身。

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

根据 X 中的数据拟合模型并返回转换后的数据。

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

训练向量,其中 n_samples 是样本数,n_features 是特征数。

y被忽略

未使用,按照惯例为保持 API 一致性而存在。

返回:
Vndarray of shape (n_samples, n_components)

转换后的数据。

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

参数名称映射到其值。

inverse_transform(X)[source]#

将数据转换回其原始空间。

参数:
Xarray-like of shape (n_samples, n_components)

要转换回的数据。必须具有与用于训练模型的数据相同的组件数。

返回:
X_original形状为 (n_samples, n_features) 的 ndarray

转换后的数据。

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

估计器实例。

transform(X)[source]#

将数据编码为字典原子的稀疏组合。

编码方法由对象参数 transform_algorithm 确定。

参数:
Xndarray of shape (n_samples, n_features)

要转换的测试数据,必须具有与用于训练模型的数据相同的特征数。

返回:
X_newndarray of shape (n_samples, n_components)

转换后的数据。