提交 8d105784 编写于 作者: L loopyme

更新第五六章

上级 92ab9f11
此差异已折叠。
# 5.4\. 无监督降维
# 5.4 缺失值插补
校验者:
        [@程威](https://github.com/apachecn/scikit-learn-doc-zh)
        [@if only](https://github.com/apachecn/scikit-learn-doc-zh)
待二次校验
翻译者:
        [@十四号](https://github.com/apachecn/scikit-learn-doc-zh)
如果你的特征数量很多, 在监督步骤之前, 可以通过无监督的步骤来减少特征. 很多的 [无监督学习](../unsupervised_learning.html#unsupervised-learning) 方法实现了一个名为 `transform` 的方法, 它可以用来降低维度. 下面我们将讨论大量使用这种模式的两个具体示例.
## 5.4.1\. PCA: 主成份分析
[`decomposition.PCA`](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA "sklearn.decomposition.PCA") 寻找能够捕捉原始特征的差异的特征的组合. 请参阅 [分解成分中的信号(矩阵分解问题)](decomposition.html#decompositions).
**示例**
* <colgroup><col class="field-name"> <col class="field-body"></colgroup>
| ref: | ‘sphx_glr_auto_examples_applications_plot_face_recognition.py’ |
| --- | --- |
## 5.4.2\. 随机投影
模块: `random_projection` 提供了几种用于通过随机投影减少数据的工具. 请参阅文档的相关部分: [随机投影](random_projection.html#random-projection).
**示例**
* [The Johnson-Lindenstrauss bound for embedding with random projections](https://scikit-learn.org/stable/auto_examples/plot_johnson_lindenstrauss_bound.html#sphx-glr-auto-examples-plot-johnson-lindenstrauss-bound-py)
## 5.4.3\. 特征聚集
[`cluster.FeatureAgglomeration`](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.FeatureAgglomeration.html#sklearn.cluster.FeatureAgglomeration "sklearn.cluster.FeatureAgglomeration") 应用 [层次聚类](clustering.html#hierarchical-clustering) 将行为类似的特征分组在一起.
**示例**
* [Feature agglomeration vs. univariate selection](https://scikit-learn.org/stable/auto_examples/cluster/plot_feature_agglomeration_vs_univariate_selection.html#sphx-glr-auto-examples-cluster-plot-feature-agglomeration-vs-univariate-selection-py)
* [Feature agglomeration](https://scikit-learn.org/stable/auto_examples/cluster/plot_digits_agglomeration.html#sphx-glr-auto-examples-cluster-plot-digits-agglomeration-py)
**特征缩放**
请注意,如果功能具有明显不同的缩放或统计属性,则 [`cluster.FeatureAgglomeration`](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.FeatureAgglomeration.html#sklearn.cluster.FeatureAgglomeration "sklearn.cluster.FeatureAgglomeration") 可能无法捕获相关特征之间的关系.使用一个 [`preprocessing.StandardScaler`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler "sklearn.preprocessing.StandardScaler") 可以在这些 设置中使用.
        [@Trembleguy](https://github.com/apachecn/scikit-learn-doc-zh)
        [@Loopy](https://github.com/loopyme)
因为各种各样的原因,真实世界中的许多数据集都包含缺失数据,这类数据经常被编码成空格、NaNs,或者是其他的占位符。但是这样的数据集并不能scikit-learn学习算法兼容,因为大多的学习算法都默认假设数组中的元素都是数值,因而所有的元素都有自己的意义。 使用不完整的数据集的一个基本策略就是舍弃掉整行或整列包含缺失值的数据。但是这样就付出了舍弃可能有价值数据(即使是不完整的 )的代价。 处理缺失数值的一个更好的策略就是从已有的数据推断出缺失的数值。有关插补(imputation),请参阅[常用术语表和API元素条目](https://scikit-learn.org/stable/glossary.html#glossary)
## 5.4.1 单变量与多变量插补
一种类型的插补算法是单变量算法,它只使用第i个特征维度中的非缺失值(如`impute.SimpleImputer`)来插补第i个特征维中的值。相比之下,多变量插补算法使用整个可用特征维度来估计缺失的值(如`impute.IterativeImputer`)。
## 5.4.2 单变量插补
[`SimpleImputer`](https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html#sklearn.impute.SimpleImputer)类提供了计算缺失值的基本策略。缺失值可以用提供的常数值计算,也可以使用缺失值所在的行/列中的统计数据(平均值、中位数或者众数)来计算。这个类也支持不同的缺失值编码。
以下代码段演示了如何使用包含缺失值的列(轴0)的平均值来替换编码为 `np.nan` 的缺失值:
```py
>>> import numpy as np
>>> from sklearn.preprocessing import Imputer
>>> imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
>>> imp.fit([[1, 2], [np.nan, 3], [7, 6]])
Imputer(axis=0, copy=True, missing_values='NaN', strategy='mean', verbose=0)
>>> X = [[np.nan, 2], [6, np.nan], [7, 6]]
>>> print(imp.transform(X))
[[ 4. 2. ]
[ 6. 3.666...]
[ 7. 6. ]]
```
[`SimpleImputer`](https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html#sklearn.impute.SimpleImputer)类也支持稀疏矩阵:
```py
>>> import scipy.sparse as sp
>>> X = sp.csc_matrix([[1, 2], [0, 3], [7, 6]])
>>> imp = Imputer(missing_values=0, strategy='mean', axis=0)
>>> imp.fit(X)
Imputer(axis=0, copy=True, missing_values=0, strategy='mean', verbose=0)
>>> X_test = sp.csc_matrix([[0, 2], [6, 0], [7, 6]])
>>> print(imp.transform(X_test))
[[ 4. 2. ]
[ 6. 3.666...]
[ 7. 6. ]]
```
注意,此格式不用于隐式存储矩阵中的缺失值,因为它会在转换时将其密集化。编码为0的缺失值必须与密集输入一起使用。
当使用 `'most_frequent'``'constant'` 策略时,[`SimpleImputer`](https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html#sklearn.impute.SimpleImputer)类还支持以 string values 或 pandas categoricals 表示的分类数据(categorical data)
```py
>>> import pandas as pd
>>> df = pd.DataFrame([["a", "x"],
... [np.nan, "y"],
... ["a", np.nan],
... ["b", "y"]], dtype="category")
...
>>> imp = SimpleImputer(strategy="most_frequent")
>>> print(imp.fit_transform(df))
[['a' 'x']
['a' 'y']
['a' 'y']
['b' 'y']]
```
### 5.4.3 多变量插补
一种更复杂的方法是使用[IterativeImputer](https://scikit-learn.org/stable/modules/generated/sklearn.impute.IterativeImputer.html#sklearn.impute.IterativeImputer)类,它将每个缺失值的特征建模为其他特征的函数,并使用该估计值进行估算。它以迭代循环方式执行:在每个步骤中,将要素目标列指定为输出y,将其他列视为输入X。使用一个回归器来在已知(未缺失)y的样本上,对(X,y)进行拟合。然后使用这个回归器来预测缺失的y值。这是以迭代的方式对每个特征进行的,然后重复`max_iter`轮。最后一轮的计算结果被返回。
>**注意** :这个估计器目前还处于试验阶段:预测和API可能会在没有任何弃用周期的情况下发生变化要使用它您需要显式地导入`enable_iterative_imputer`
```py
>>> import numpy as np
>>> from sklearn.experimental import enable_iterative_imputer
>>> from sklearn.impute import IterativeImputer
>>> imp = IterativeImputer(max_iter=10, random_state=0)
>>> imp.fit([[1, 2], [3, 6], [4, 8], [np.nan, 3], [7, np.nan]])
IterativeImputer(add_indicator=False, estimator=None,
imputation_order='ascending', initial_strategy='mean',
max_iter=10, max_value=None, min_value=None,
missing_values=nan, n_nearest_features=None,
random_state=0, sample_posterior=False, tol=0.001,
verbose=0)
>>> X_test = [[np.nan, 2], [6, np.nan], [np.nan, 6]]
>>> # the model learns that the second feature is double the first
>>> print(np.round(imp.transform(X_test)))
[[ 1. 2.]
[ 6. 12.]
[ 3. 6.]]
```
[`SimpleImputer`](https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html#sklearn.impute.SimpleImputer)和[IterativeImputer](https://scikit-learn.org/stable/modules/generated/sklearn.impute.IterativeImputer.html#sklearn.impute.IterativeImputer)都可以用来在管道中构建支持计算的复合估计器。在构建估算器之前,请参阅[一个估算缺失值的例子](https://scikit-learn.org/stable/auto_examples/impute/plot_missing_values.html#sphx-glr-auto-examples-impute-plot-missing-values-py)。
### 5.4.3.1 多变量插补的灵活性
在R数据科学生态系统中,有许多成熟的估算包:Amelia, mi, mice, missForest等。misforest是一种很流行的算法,它是不同序列计算算法的一个特殊实例,这些算法都可以使用[IterativeImputer](https://scikit-learn.org/stable/modules/generated/sklearn.impute.IterativeImputer.html#sklearn.impute.IterativeImputer)来实现,通过传递不同的回归函数来预测缺失的特征值。在misforest的情况下,这个回归因子是一个随机森林。请参见[Imputing missing values with variants of IterativeImputer](https://scikit-learn.org/stable/auto_examples/impute/plot_iterative_imputer_variants_comparison#imputing-missing-values-with-variants-of-iterativeimputer)
### 5.4.3.2 单次与多次插补
在统计学界,通常的做法是执行多次计算,例如,为单个特征矩阵生成m个单独的计算。然后,每一个m的估算都通过后续的分析管道(例如,特征工程、聚类、回归、分类)进行。m个最终分析结果(例如,延迟验证错误)允许数据科学家了解由于缺失值所导致的固有不确定性,分析结果可能会有何不同。上述做法称为多重插补。
我们实现[IterativeImputer](https://scikit-learn.org/stable/modules/generated/sklearn.impute.IterativeImputer.html#sklearn.impute.IterativeImputer)的灵感来自于R的MICE包[1],但与之不同的是,我们返回了一个单一的插补,而不是多个插补。然而,当`sample_posterior`=True时,`IterativeImputer`也可以通过重复应用于具有不同随机种子的同一数据集来进行多次计算。参见[2]第4章,以获得更多关于多重和单次估算的讨论。
当用户对由于缺失值而导致的测量不确定性不感兴趣时,单次和多次插补在预测和分类上下文中有多大用处,这仍然是一个有待解决的问题。
注意,调用`IterativeImputer`的转换方法不允许改变样本的数量。因此,单次调用`transform`不能实现多次计算。
## 5.4.4 参考
* Stef van Buuren, Karin Groothuis-Oudshoorn (2011). “mice: Multivariate Imputation by Chained Equations in R”. Journal of Statistical Software 45: 1-67.
* Roderick J A Little and Donald B Rubin (1986). “Statistical Analysis with Missing Data”. John Wiley & Sons, Inc., New York, NY, USA.
## 5.4.5 标记缺失值
[`MissingIndicator`](https://scikit-learn.org/stable/modules/generated/sklearn.impute.MissingIndicator.html#sklearn.impute.MissingIndicator)转换器用于将数据集转换为相应的二进制矩阵,以指示数据集中缺失值的存在。这个变换与归算结合起来是有用的。当使用插补时,保存关于哪些值丢失的信息可以提供有用的信息。
`NaN`通常用作缺少值的占位符。但是,它强制数据类型为浮点数。参数`missing_values`允许指定其他占位符,如整数。 在以下示例中,我们将使用-1作为缺失值
```py
>>> from sklearn.impute import MissingIndicator
>>> X = np.array([[-1, -1, 1, 3],
... [4, -1, 0, -1],
... [8, -1, 1, 0]])
>>> indicator = MissingIndicator(missing_values=-1)
>>> mask_missing_values_only = indicator.fit_transform(X)
>>> mask_missing_values_only
array([[ True, True, False],
[False, True, True],
[False, True, False]])
```
参数`features`用于选择构造掩码的特征。默认情况下,它是 'missing-only',在`fit`时返回包含缺失值的特征的输入掩码
```py
>>> indicator.features_
array([0, 1, 3])
```
参数`features`可以设置为'all'以返回所有特征,无论它们是否包含缺失的值
```py
>>> indicator = MissingIndicator(missing_values=-1, features="all")
>>> mask_all = indicator.fit_transform(X)
>>> mask_all
array([[ True, True, False, False],
[False, True, False, True],
[False, True, False, False]])
>>> indicator.features_
array([0, 1, 2, 3])
```
当在 Pipeline 中使用 [MissingIndicator](https://scikit-learn.org/stable/modules/generated/sklearn.impute.MissingIndicator.html#sklearn.impute.MissingIndicator)时, 务必使用`FeatureUnion` 或`ColumnTransformer`来添加 indicator features 到 regular features中. 首先,我们在iris数据集上插补一些缺失值:
```py
>>> from sklearn.datasets import load_iris
>>> from sklearn.impute import SimpleImputer, MissingIndicator
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.pipeline import FeatureUnion, make_pipeline
>>> from sklearn.tree import DecisionTreeClassifier
>>> X, y = load_iris(return_X_y=True)
>>> mask = np.random.randint(0, 2, size=X.shape).astype(np.bool)
>>> X[mask] = np.nan
>>> X_train, X_test, y_train, _ = train_test_split(X, y, test_size=100,
... random_state=0)
```
现在我们创建一个FeatureUnion。为了使分类器能够处理这些数据,所有的特征都将使用[SimpleImputer](https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html#sklearn.impute.SimpleImputer)进行估算。 此外,它还从 [MissingIndicator](https://scikit-learn.org/stable/modules/generated/sklearn.impute.MissingIndicator.html#sklearn.impute.MissingIndicator)中添加指示变量。
```py
>>> transformer = FeatureUnion(
... transformer_list=[
... ('features', SimpleImputer(strategy='mean')),
... ('indicators', MissingIndicator())])
>>> transformer = transformer.fit(X_train, y_train)
>>> results = transformer.transform(X_test)
>>> results.shape
(100, 8)
```
当然,我们不能用transformer来做任何预测。我们应该用分类器(例如,`DecisionTreeClassifier`)将其封装在pipeline中, 以便能够进行预测。
```py
>>> clf = make_pipeline(transformer, DecisionTreeClassifier())
>>> clf = clf.fit(X_train, y_train)
>>> results = clf.predict(X_test)
>>> results.shape
(100,)
```
# 5.5\. 随机投影
# 5.5\. 无监督降维
校验者:
        [@FontTian](https://github.com/FontTian)
        [@程威](https://github.com/apachecn/scikit-learn-doc-zh)
翻译者:
        [@Sehriff](https://github.com/apachecn/scikit-learn-doc-zh)
        [@十四号](https://github.com/apachecn/scikit-learn-doc-zh)
[`sklearn.random_projection`](classes.html#module-sklearn.random_projection "sklearn.random_projection") 模块实现了一个简单且高效率的计算方式来减少数据维度,通过牺牲一定的精度(作为附加变量)来加速处理时间及更小的模型尺寸。 这个模型实现了两类无结构化的随机矩阵: [Gaussian random matrix](#gaussian-random-matrix)[sparse random matrix](#sparse-random-matrix).
如果你的特征数量很多, 在监督步骤之前, 可以通过无监督的步骤来减少特征. 很多的 [无监督学习](../unsupervised_learning.html#unsupervised-learning) 方法实现了一个名为 `transform` 的方法, 它可以用来降低维度. 下面我们将讨论大量使用这种模式的两个具体示例.
随机投影矩阵的维度和分布是受控制的,所以可以保存任意两个数据集的距离。因此随机投影适用于基于距离的方法。
>**Pipelining**
>非监督数据约简和监督估计器可以链接起来。 请看 [Pipeline: 链式评估器](docs/38?id=_511-pipeline-链式评估器).
参考:
## 5.5.1\. PCA: 主成份分析
* Sanjoy Dasgupta. 2000. [Experiments with random projection.](http://cseweb.ucsd.edu/~dasgupta/papers/randomf.pdf) In Proceedings of the Sixteenth conference on Uncertainty in artificial intelligence (UAI‘00), Craig Boutilier and Moisés Goldszmidt (Eds.). Morgan Kaufmann Publishers Inc., San Francisco, CA, USA, 143-151.
* Ella Bingham and Heikki Mannila. 2001. [Random projection in dimensionality reduction: applications to image and text data.](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.24.5135&rep=rep1&type=pdf) In Proceedings of the seventh ACM SIGKDD international conference on Knowledge discovery and data mining (KDD ‘01). ACM, New York, NY, USA, 245-250.
[`decomposition.PCA`](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA "sklearn.decomposition.PCA") 寻找能够捕捉原始特征的差异的特征的组合. 请参阅 [分解成分中的信号(矩阵分解问题)](docs/24?id=_25-分解成分中的信号(矩阵分解问题)).
## 5.5.1\. Johnson-Lindenstrauss 辅助定理
>**示例**
>* [Faces recognition example using eigenfaces and SVMs](https://scikit-learn.org/stable/auto_examples/applications/plot_face_recognition.html#sphx-glr-auto-examples-applications-plot-face-recognition-py)
支撑随机投影效率的主要理论成果是`Johnson-Lindenstrauss lemma (quoting Wikipedia) <[https://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma](https://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma)>`_:
## 5.5.2\. 随机投影
> 在数学中,johnson - lindenstrauss 引理是一种将高维的点从高维到低维欧几里得空间的低失真嵌入的方案。 引理阐释了高维空间下的一小部分的点集可以内嵌到非常低维的空间,这种方式下点之间的距离几乎全部被保留。 内嵌所用到的映射至少符合 Lipschitz 条件,甚至可以被当做正交投影。
模块: `random_projection` 提供了几种用于通过随机投影减少数据的工具. 请参阅文档的相关部分: [随机投影](docs/56).
有了样本数量, [`sklearn.random_projection.johnson_lindenstrauss_min_dim`](https://scikit-learn.org/stable/modules/generated/sklearn.random_projection.johnson_lindenstrauss_min_dim.html#sklearn.random_projection.johnson_lindenstrauss_min_dim "sklearn.random_projection.johnson_lindenstrauss_min_dim") 会保守估计随机子空间的最小大小来保证随机投影导致的变形在一定范围内:
>**示例**
>* [The Johnson-Lindenstrauss bound for embedding with random projections](https://scikit-learn.org/stable/auto_examples/plot_johnson_lindenstrauss_bound.html#sphx-glr-auto-examples-plot-johnson-lindenstrauss-bound-py)
```py
>>> from sklearn.random_projection import johnson_lindenstrauss_min_dim
>>> johnson_lindenstrauss_min_dim(n_samples=1e6, eps=0.5)
663
>>> johnson_lindenstrauss_min_dim(n_samples=1e6, eps=[0.5, 0.1, 0.01])
array([ 663, 11841, 1112658])
>>> johnson_lindenstrauss_min_dim(n_samples=[1e4, 1e5, 1e6], eps=0.1)
array([ 7894, 9868, 11841])`
## 5.5.3\. 特征聚集
```
[`cluster.FeatureAgglomeration`](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.FeatureAgglomeration.html#sklearn.cluster.FeatureAgglomeration "sklearn.cluster.FeatureAgglomeration") 应用 [层次聚类](clustering.html#hierarchical-clustering) 将行为类似的特征分组在一起.
[![http://sklearn.apachecn.org/cn/0.19.0/_images/sphx_glr_plot_johnson_lindenstrauss_bound_0011.png](img/01024e528443374ebac4e8cb2f6dc463.jpg)](https://scikit-learn.org/stable/auto_examples/plot_johnson_lindenstrauss_bound.html)[![http://sklearn.apachecn.org/cn/0.19.0/_images/sphx_glr_plot_johnson_lindenstrauss_bound_0021.png](img/bc0cfc8c8661055fd60ca8e90b21d1dd.jpg)](https://scikit-learn.org/stable/auto_examples/plot_johnson_lindenstrauss_bound.html)
>**示例**
>* [Feature agglomeration vs. univariate selection](https://scikit-learn.org/stable/auto_examples/cluster/plot_feature_agglomeration_vs_univariate_selection.html#sphx-glr-auto-examples-cluster-plot-feature-agglomeration-vs-univariate-selection-py)
>* [Feature agglomeration](https://scikit-learn.org/stable/auto_examples/cluster/plot_digits_agglomeration.html#sphx-glr-auto-examples-cluster-plot-digits-agglomeration-py)
例子:
* 查看 [The Johnson-Lindenstrauss bound for embedding with random projections](https://scikit-learn.org/stable/auto_examples/plot_johnson_lindenstrauss_bound.html#sphx-glr-auto-examples-plot-johnson-lindenstrauss-bound-py) 里面有Johnson-Lindenstrauss引理的理论说明和使用稀疏随机矩阵的经验验证。
参考:
* Sanjoy Dasgupta and Anupam Gupta, 1999. [An elementary proof of the Johnson-Lindenstrauss Lemma.](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.39.3334&rep=rep1&type=pdf)
## 5.5.2\. 高斯随机投影
The [`sklearn.random_projection.GaussianRandomProjection`](https://scikit-learn.org/stable/modules/generated/sklearn.random_projection.GaussianRandomProjection.html#sklearn.random_projection.GaussianRandomProjection "sklearn.random_projection.GaussianRandomProjection") 通过将原始输入空间投影到随机生成的矩阵(该矩阵的组件由以下分布中抽取) :math:[`](#id4)N(0, frac{1}{n_{components}})`降低维度。
以下小片段演示了任何使用高斯随机投影转换器:
```py
>>> import numpy as np
>>> from sklearn import random_projection
>>> X = np.random.rand(100, 10000)
>>> transformer = random_projection.GaussianRandomProjection()
>>> X_new = transformer.fit_transform(X)
>>> X_new.shape
(100, 3947)
```
## 5.5.3\. 稀疏随机矩阵
> [`sklearn.random_projection.SparseRandomProjection`](https://scikit-learn.org/stable/modules/generated/sklearn.random_projection.SparseRandomProjection.html#sklearn.random_projection.SparseRandomProjection "sklearn.random_projection.SparseRandomProjection") 使用稀疏随机矩阵,通过投影原始输入空间来降低维度。
稀疏矩阵可以替换高斯随机投影矩阵来保证相似的嵌入质量,且内存利用率更高、投影数据的计算更快。
如果我们定义 `s = 1 / density`, 随机矩阵的元素由
![\left\{
\begin{array}{c c l}
-\sqrt{\frac{s}{n_{\text{components}}}} & & 1 / 2s\\
0 &\text{with probability} & 1 - 1 / s \\
+\sqrt{\frac{s}{n_{\text{components}}}} & & 1 / 2s\\
\end{array}
\right.](img/3e233cefc937a43bb4481dd23d728b54.jpg)
抽取。
其中 ![n_{\text{components}}](img/2f6a285b749960084841d17c3c97f2d7.jpg) 是投影后的子空间大小。 默认非零元素的浓密度设置为最小浓密度,该值由Ping Li et al.:推荐,根据公式:math:[`](#id7)1 / sqrt{n_{text{features}}}`计算。
以下小片段演示了如何使用稀疏随机投影转换器:
```py
>>> import numpy as np
>>> from sklearn import random_projection
>>> X = np.random.rand(100,10000)
>>> transformer = random_projection.SparseRandomProjection()
>>> X_new = transformer.fit_transform(X)
>>> X_new.shape
(100, 3947)
```
参考:
* D. Achlioptas. 2003. [Database-friendly random projections: Johnson-Lindenstrauss with binary coins](www.cs.ucsc.edu/~optas/papers/jl.pdf). Journal of Computer and System Sciences 66 (2003) 671–687
* Ping Li, Trevor J. Hastie, and Kenneth W. Church. 2006. [Very sparse random projections.](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.62.585&rep=rep1&type=pdf) In Proceedings of the 12th ACM SIGKDD international conference on Knowledge discovery and data mining (KDD ‘06). ACM, New York, NY, USA, 287-296.
>**特征缩放**
>
>请注意,如果功能具有明显不同的缩放或统计属性,则 [`cluster.FeatureAgglomeration`](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.FeatureAgglomeration.html#sklearn.cluster.FeatureAgglomeration "sklearn.cluster.FeatureAgglomeration") 可能无法捕获相关特征之间的关系.使用一个 [`preprocessing.StandardScaler`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler "sklearn.preprocessing.StandardScaler") 可以在这些 设置中使用.
# 5.6\. 内核近似
# 5.6\. 随机投影
校验者:
        [@FontTian](https://github.com/FontTian)
        [@numpy](https://github.com/apachecn/scikit-learn-doc-zh)
翻译者:
        [@程威](https://github.com/apachecn/scikit-learn-doc-zh)
翻译者:
        [@Sehriff](https://github.com/apachecn/scikit-learn-doc-zh)
这个子模块包含与某些 kernel 对应的特征映射的函数,这个会用于例如支持向量机的算法当中(see [支持向量机](svm.html#svm))。 下面这些特征函数对输入执行非线性转换,可以用于线性分类或者其他算法。
[kernel trick](https://en.wikipedia.org/wiki/Kernel_trick) 相比,近似的进行特征映射更适合在线学习,并能够有效 减少学习大量数据的内存开销。使用标准核技巧的 svm 不能有效的适用到海量数据,但是使用近似内核映射的方法,对于线性 SVM 来说效果可能更好。 而且,使用 [`SGDClassifier`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html#sklearn.linear_model.SGDClassifier "sklearn.linear_model.SGDClassifier") 进行近似的内核映射,使得对海量数据进行非线性学习也成为了可能。
由于近似嵌入的方法没有太多经验性的验证,所以建议将结果和使用精确的内核方法的结果进行比较。
[`sklearn.random_projection`](classes.html#module-sklearn.random_projection "sklearn.random_projection") 模块实现了一个简单且高效率的计算方式来减少数据维度,通过牺牲一定的精度(作为附加变量)来加速处理时间及更小的模型尺寸。 这个模型实现了两类无结构化的随机矩阵: [Gaussian random matrix](#gaussian-random-matrix)[sparse random matrix](#sparse-random-matrix).
See also
随机投影矩阵的维度和分布是受控制的,所以可以保存任意两个数据集的距离。因此随机投影适用于基于距离的方法。
[多项式回归:用基函数展开线性模型](linear_model.html#polynomial-regression) 用于精确的多项式变换。
>参考:
>* Sanjoy Dasgupta. 2000. [Experiments with random projection.](http://cseweb.ucsd.edu/~dasgupta/papers/randomf.pdf) In Proceedings of the Sixteenth conference on Uncertainty in artificial intelligence (UAI‘00), Craig Boutilier and Moisés Goldszmidt (Eds.). Morgan Kaufmann Publishers Inc., San Francisco, CA, USA, 143-151.
>* Ella Bingham and Heikki Mannila. 2001. [Random projection in dimensionality reduction: applications to image and text data.](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.24.5135&rep=rep1&type=pdf) In Proceedings of the seventh ACM SIGKDD international conference on Knowledge discovery and data mining (KDD ‘01). ACM, New York, NY, USA, 245-250.
## 5.6.1\. 内核近似的 Nystroem 方法
## 5.6.1\. Johnson-Lindenstrauss 辅助定理
[`Nystroem`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.Nystroem.html#sklearn.kernel_approximation.Nystroem "sklearn.kernel_approximation.Nystroem") 中实现了 Nystroem 方法用于低等级的近似核。它是通过采样 kernel 已经评估好的数据。默认情况下, [`Nystroem`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.Nystroem.html#sklearn.kernel_approximation.Nystroem "sklearn.kernel_approximation.Nystroem") 使用 `rbf` kernel,但它可以使用任何内核函数和预计算内核矩阵. 使用的样本数量 - 计算的特征维数 - 由参数 `n_components` 给出.
支撑随机投影效率的主要理论成果是[Johnson-Lindenstrauss lemma (quoting Wikipedia)](https://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma):
## 5.6.2\. 径向基函数内核
> 在数学中,johnson - lindenstrauss 引理是一种将高维的点从高维到低维欧几里得空间的低失真嵌入的方案。 引理阐释了高维空间下的一小部分的点集可以内嵌到非常低维的空间,这种方式下点之间的距离几乎全部被保留。 内嵌所用到的映射至少符合 Lipschitz 条件,甚至可以被当做正交投影。
[`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler") 为径向基函数核构造一个近似映射,又称为 Random Kitchen Sinks [RR2007]. 在应用线性算法(例如线性 SVM )之前,可以使用此转换来明确建模内核映射:
有了样本数量, [`sklearn.random_projection.johnson_lindenstrauss_min_dim`](https://scikit-learn.org/stable/modules/generated/sklearn.random_projection.johnson_lindenstrauss_min_dim.html#sklearn.random_projection.johnson_lindenstrauss_min_dim "sklearn.random_projection.johnson_lindenstrauss_min_dim") 会保守估计随机子空间的最小大小来保证随机投影导致的变形在一定范围内:
```py
>>> from sklearn.kernel_approximation import RBFSampler
>>> from sklearn.linear_model import SGDClassifier
>>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]
>>> y = [0, 0, 1, 1]
>>> rbf_feature = RBFSampler(gamma=1, random_state=1)
>>> X_features = rbf_feature.fit_transform(X)
>>> clf = SGDClassifier()
>>> clf.fit(X_features, y)
SGDClassifier(alpha=0.0001, average=False, class_weight=None, epsilon=0.1,
eta0=0.0, fit_intercept=True, l1_ratio=0.15,
learning_rate='optimal', loss='hinge', max_iter=5, n_iter=None,
n_jobs=1, penalty='l2', power_t=0.5, random_state=None,
shuffle=True, tol=None, verbose=0, warm_start=False)
>>> clf.score(X_features, y)
1.0
>>> from sklearn.random_projection import johnson_lindenstrauss_min_dim
>>> johnson_lindenstrauss_min_dim(n_samples=1e6, eps=0.5)
663
>>> johnson_lindenstrauss_min_dim(n_samples=1e6, eps=[0.5, 0.1, 0.01])
array([ 663, 11841, 1112658])
>>> johnson_lindenstrauss_min_dim(n_samples=[1e4, 1e5, 1e6], eps=0.1)
array([ 7894, 9868, 11841])`
```
这个映射依赖于内核值的 Monte Carlo 近似. `fit` 方法执行 Monte Carlo 采样,而该 `transform` 方法执行 数据的映射.由于过程的固有随机性,结果可能会在不同的 `fit` 函数调用之间变化。
`fit` 函数有两个参数: `n_components` 是特征变换的目标维数. `gamma` 是 RBF-kernel 的参数. `n_components` 越高,会导致更好的内核近似, 并且将产生与内核 SVM 产生的结果更相似的结果。请注意,”拟合” 特征函数实际上不取决于 `fit` 函数传递的数据。只有数据的维数被使用。 详情可以参考 [[RR2007]](#rr2007).
对于给定的值 `n_components` [`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler")[`Nystroem`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.Nystroem.html#sklearn.kernel_approximation.Nystroem "sklearn.kernel_approximation.Nystroem") 中使用通常不太准确, 但是 [`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler") 使用更大的特征空间,更容易计算。
[![http://sklearn.apachecn.org/cn/0.19.0/_images/sphx_glr_plot_kernel_approximation_0021.png](img/d90bb77f4f60c523c2bc041f768e8a49.jpg)](https://scikit-learn.org/stable/auto_examples/plot_kernel_approximation.html)
将精确的 RBF kernel (左) 与 approximation (右) 进行比较。
示例:
* [Explicit feature map approximation for RBF kernels](https://scikit-learn.org/stable/auto_examples/plot_kernel_approximation.html#sphx-glr-auto-examples-plot-kernel-approximation-py)
[![http://sklearn.apachecn.org/cn/0.19.0/_images/sphx_glr_plot_johnson_lindenstrauss_bound_0011.png](img/01024e528443374ebac4e8cb2f6dc463.jpg)](https://scikit-learn.org/stable/auto_examples/plot_johnson_lindenstrauss_bound.html)[![http://sklearn.apachecn.org/cn/0.19.0/_images/sphx_glr_plot_johnson_lindenstrauss_bound_0021.png](img/bc0cfc8c8661055fd60ca8e90b21d1dd.jpg)](https://scikit-learn.org/stable/auto_examples/plot_johnson_lindenstrauss_bound.html)
## 5.6.3\. 加性卡方核
>例子:
>* 查看 [The Johnson-Lindenstrauss bound for embedding with random projections](https://scikit-learn.org/stable/auto_examples/plot_johnson_lindenstrauss_bound.html#sphx-glr-auto-examples-plot-johnson-lindenstrauss-bound-py) 里面有Johnson-Lindenstrauss引理的理论说明和使用稀疏随机矩阵的经验验证。
Additive Chi Squared Kernel (加性卡方核)是直方图的核心,通常用于计算机视觉。
>参考:
>* Sanjoy Dasgupta and Anupam Gupta, 1999. [An elementary proof of the Johnson-Lindenstrauss Lemma.](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.39.3334&rep=rep1&type=pdf)
这里使用的 Additive Chi Squared Kernel 给出
## 5.6.2\. 高斯随机投影
![k(x, y) = \sum_i \frac{2x_iy_i}{x_i+y_i}](img/bc7418a3ab8f749f1abd139faa96bee2.jpg)
The [`sklearn.random_projection.GaussianRandomProjection`](https://scikit-learn.org/stable/modules/generated/sklearn.random_projection.GaussianRandomProjection.html#sklearn.random_projection.GaussianRandomProjection "sklearn.random_projection.GaussianRandomProjection") 通过将原始输入空间投影到随机生成的矩阵(该矩阵的组件由以下分布中抽取):![N(0, \frac{1}{n_{components}})](img/projection001.png)降低维度。
这个和 `sklearn.metrics.additive_chi2_kernel` 不完全一样.[VZ2010]_ 的作者喜欢上面的版本,因为它总是积极的。 由于这个 kernel 是可添加的,因此可以分别处理嵌入的 ![x_i](img/cf52655ee609af9f3c27c06448a5bf67.jpg). 这使得在规则的间隔类对傅里叶变换进行性才赢,代替近似的 Monte Carlo 采样。
以下小片段演示了任何使用高斯随机投影转换器:
> [`AdditiveChi2Sampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.AdditiveChi2Sampler.html#sklearn.kernel_approximation.AdditiveChi2Sampler "sklearn.kernel_approximation.AdditiveChi2Sampler") 类实现了这个组件采样方法. 每个组件都被采样 ![n](img/c87d9110f3d32ffa5fa08671e4af11fb.jpg) 次,每一个输入维数都会产生 *2n+1* 维(来自傅立叶变换的实部和复数部分的两个数据段的倍数). 在文献中,![n](img/c87d9110f3d32ffa5fa08671e4af11fb.jpg) 经常取为 1 或者 2,将数据集转换为 `n_samples * 5 * n_features` 大小(在 ![n=2](img/b94b3a3837e7741f704e3b9b23ba0880.jpg) 的情况下 ).
[`AdditiveChi2Sampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.AdditiveChi2Sampler.html#sklearn.kernel_approximation.AdditiveChi2Sampler "sklearn.kernel_approximation.AdditiveChi2Sampler") 提供的近似特征映射可以和 [`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler") 提供的近似特征映射合并,得到一个取幂的 chi squared kerne。可以查看 [[VZ2010]](#vz2010)[[VVZ2010]](#vvz2010) [`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler") 的合并.
## 5.6.4\. Skewed Chi Squared Kernel (偏斜卡方核?暂译)
skewed chi squared kernel 给出下面公式
![k(x,y) = \prod_i \frac{2\sqrt{x_i+c}\sqrt{y_i+c}}{x_i + y_i + 2c}](img/dd310c2fa94418ac4f4d12638444fd3b.jpg)
它有和 指数卡方核 相似的属性,用于计算机视觉.但是允许进行简单的 蒙特卡洛 近似 的特征映射。
[`SkewedChi2Sampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.SkewedChi2Sampler.html#sklearn.kernel_approximation.SkewedChi2Sampler "sklearn.kernel_approximation.SkewedChi2Sampler") 的使用和之前描述的 [`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler") 一样.唯一的区别是自由参数,称之为 ![c](img/d5c9a11453ea30a1be50a1034052bd6b.jpg). 这种映射和数学细节可以参考 [[LS2010]](#ls2010).
```py
>>> import numpy as np
>>> from sklearn import random_projection
>>> X = np.random.rand(100, 10000)
>>> transformer = random_projection.GaussianRandomProjection()
>>> X_new = transformer.fit_transform(X)
>>> X_new.shape
(100, 3947)
## 5.6.5\. 数学方面的细节
```
核技巧 像支持向量机,或者 核化 PCA 依赖于 再生核希尔伯特空间(RKHS) 对于任何 核函数 ![k](img/f93871977da52a6d11045d57c3e18728.jpg) (叫做 Mercer kernel),保证了 ![\phi](img/ff5e98366afa13070d3b410c55a80db1.jpg) 进入 希尔伯特空间 ![\mathcal{H}](img/433fedd575581cddbd612624b65e5dac.jpg) 的映射,例如:
## 5.6.3\. 稀疏随机矩阵
![k(x,y) = \langle \phi(x), \phi(y) \rangle](img/e56abe6d36f21c0c6dd22d2a84535415.jpg)
[`sklearn.random_projection.SparseRandomProjection`](https://scikit-learn.org/stable/modules/generated/sklearn.random_projection.SparseRandomProjection.html#sklearn.random_projection.SparseRandomProjection "sklearn.random_projection.SparseRandomProjection") 使用稀疏随机矩阵,通过投影原始输入空间来降低维度。
![\langle \cdot, \cdot \rangle](img/e668ecc249e709e47f6955a74528bf7b.jpg) 是在 Hilbert space 中做内积.
稀疏矩阵可以替换高斯随机投影矩阵来保证相似的嵌入质量,且内存利用率更高、投影数据的计算更快。
如果一个算法,例如线性支持向量机或者 PCA,依赖于数据集的数量级 ![x_i](img/cf52655ee609af9f3c27c06448a5bf67.jpg) ,可能会使用 ![k(x_i, x_j)](img/2b117c8d0556a027e7ee3bb265a6bf63.jpg) , 符合孙发的映射 ![\phi(x_i)](img/c03e9014ab434e11e9323f87908ed15e.jpg) . 使用 ![k](img/f93871977da52a6d11045d57c3e18728.jpg) 的优点在于 ![\phi](img/ff5e98366afa13070d3b410c55a80db1.jpg) 永远不会直接计算,允许大量的特征计算(甚至是无限的).
如果我们定义 `s = 1 / density`, 随机矩阵的元素由下式抽取。
kernel 方法的一个缺点是,在优化过程中有可能存储大量的 kernel 值 ![k(x_i, x_j)](img/2b117c8d0556a027e7ee3bb265a6bf63.jpg). 如果使用核函数的分类器应用于新的数据 ![y_j](img/8610705cf45aa68b12197abd65653479.jpg) , ![k(x_i, y_j)](img/1375f487efd6b9db955b7f7aafecc441.jpg) 需要计算用来做预测,训练集中的 ![x_i](img/cf52655ee609af9f3c27c06448a5bf67.jpg) 有可能有很多不同的。
这个子模块的这些类中允许嵌入 ![\phi](img/ff5e98366afa13070d3b410c55a80db1.jpg),从而明确的与 ![\phi(x_i)](img/c03e9014ab434e11e9323f87908ed15e.jpg) 一起工作, 这消除了使用 kernel 的需要和存储训练样本.
![\left\{\begin{array}{c c l}-\sqrt{\frac{s}{n_{\text{components}}}} & & 1 / 2s\\0 &\text{with probability} & 1 - 1 / s \\+\sqrt{\frac{s}{n_{\text{components}}}} & & 1 / 2s\\\end{array}\right.](img/3e233cefc937a43bb4481dd23d728b54.jpg)
参考:
| [[RR2007]](#id3) | [“Random features for large-scale kernel machines”](http://www.robots.ox.ac.uk/~vgg/rg/papers/randomfeatures.pdf) Rahimi, A. and Recht, B. - Advances in neural information processing 2007, |
其中 ![n_{\text{components}}](img/2f6a285b749960084841d17c3c97f2d7.jpg) 是投影后的子空间大小。 默认非零元素的浓密度设置为最小浓密度,该值由Ping Li et al.:推荐,根据公式:![1 / \sqrt{n_{\text{features}}}](img/projection002.png)计算。
| [[LS2010]](#id7) | [“Random Fourier approximations for skewed multiplicative histogram kernels”](http://www.maths.lth.se/matematiklth/personal/sminchis/papers/lis_dagm10.pdf) Random Fourier approximations for skewed multiplicative histogram kernels - Lecture Notes for Computer Sciencd (DAGM) |
以下小片段演示了如何使用稀疏随机投影转换器:
| [[VZ2010]](#id5) | [“Efficient additive kernels via explicit feature maps”](https://www.robots.ox.ac.uk/~vgg/publications/2011/Vedaldi11/vedaldi11.pdf) Vedaldi, A. and Zisserman, A. - Computer Vision and Pattern Recognition 2010 |
```py
>>> import numpy as np
>>> from sklearn import random_projection
>>> X = np.random.rand(100,10000)
>>> transformer = random_projection.SparseRandomProjection()
>>> X_new = transformer.fit_transform(X)
>>> X_new.shape
(100, 3947)
```
| [[VVZ2010]](#id6) | [“Generalized RBF feature maps for Efficient Detection”](https://www.robots.ox.ac.uk/~vgg/publications/2010/Sreekanth10/sreekanth10.pdf) Vempati, S. and Vedaldi, A. and Zisserman, A. and Jawahar, CV - 2010 |
>参考:
>* D. Achlioptas. 2003. [Database-friendly random projections: Johnson-Lindenstrauss with binary coins](www.cs.ucsc.edu/~optas/papers/jl.pdf). Journal of Computer and System Sciences 66 (2003) 671–687
>* Ping Li, Trevor J. Hastie, and Kenneth W. Church. 2006. [Very sparse random projections.](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.62.585&rep=rep1&type=pdf) In Proceedings of the 12th ACM SIGKDD international conference on Knowledge discovery and data mining (KDD ‘06). ACM, New York, NY, USA, 287-296.
# 5.7\. 成对的矩阵, 类别和核函数
# 5.7\. 内核近似
校验者:
        [@FontTian](https://github.com/FontTian)
        [@numpy](https://github.com/apachecn/scikit-learn-doc-zh)
        [@Loopy](https://github.com/loopyme)
翻译者:
        [@程威](https://github.com/apachecn/scikit-learn-doc-zh)
The [`sklearn.metrics.pairwise`](classes.html#module-sklearn.metrics.pairwise "sklearn.metrics.pairwise") 子模块实现了用于评估成对距离或样本集合之间的联系的实用程序
这个子模块包含与某些 kernel 对应的特征映射的函数,这个会用于例如支持向量机的算法当中(see [支持向量机](svm.html#svm))。 下面这些特征函数对输入执行非线性转换,可以用于线性分类或者其他算法
本模块同时包含距离度量和核函数,对于这两者这里提供一个简短的总结
[kernel trick](https://en.wikipedia.org/wiki/Kernel_trick) 相比,近似的进行特征映射更适合在线学习,并能够有效 减少学习大量数据的内存开销。使用标准核技巧的 svm 不能有效的适用到海量数据,但是使用近似内核映射的方法,对于线性 SVM 来说效果可能更好。 而且,使用 [`SGDClassifier`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html#sklearn.linear_model.SGDClassifier "sklearn.linear_model.SGDClassifier") 进行近似的内核映射,使得对海量数据进行非线性学习也成为了可能
距离度量是形如 `d(a, b)` 例如 `d(a, b) < d(a, c)` 如果对象 `a``b` 被认为 “更加相似” 相比于 `a``c`. 两个完全相同的目标的距离是零。最广泛使用的例子就是欧几里得距离。 为了保证是 ‘真实的’ 度量, 其必须满足以下条件:
由于近似嵌入的方法没有太多经验性的验证,所以建议将结果和使用精确的内核方法的结果进行比较。
> 1. 对于所有的 a 和 b,d(a, b) >= 0
> 2. 正定性:当且仅当 a = b时,d(a, b) == 0
> 3. 对称性:d(a, b) == d(b, a)
> 4. 三角不等式:d(a, c) <= d(a, b) + d(b, c)
也可参阅[多项式回归:用基函数展开线性模型](docs/2?id=_1116-多项式回归:用基函数展开线性模型) 用于精确的多项式变换。
核函数是相似度的标准. 如果对象 `a``b` 被认为 “更加相似” 相比对象 `a``c`,那么 `s(a, b) > s(a, c)`. 核函数必须是半正定性的.
## 5.7.1\. 内核近似的 Nystroem 方法
存在许多种方法将距离度量转换为相似度标准,例如核函数。 假定 `D` 是距离, and `S` 是核函数:
[`Nystroem`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.Nystroem.html#sklearn.kernel_approximation.Nystroem "sklearn.kernel_approximation.Nystroem") 中实现了 Nystroem 方法用于低等级的近似核。它是通过采样 kernel 已经评估好的数据。默认情况下, [`Nystroem`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.Nystroem.html#sklearn.kernel_approximation.Nystroem "sklearn.kernel_approximation.Nystroem") 使用 `rbf` kernel,但它可以使用任何内核函数和预计算内核矩阵. 使用的样本数量 - 计算的特征维数 - 由参数 `n_components` 给出.
> 1. `S = np.exp(-D * gamma)`, 其中 `gamma` 的一种选择是 `1 / num_features`
> 2. `S = 1. / (D / np.max(D))`
## 5.7.2\. 径向基函数内核
## 5.7.1\. 余弦相似度
[`cosine_similarity`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html#sklearn.metrics.pairwise.cosine_similarity "sklearn.metrics.pairwise.cosine_similarity") 计算L2正则化的向量的点积. 也就是说, if ![x](img/5c82dbae35dc43d2f556f9f284d9d184.jpg) 和 ![y](img/0775c03fc710a24df297dedcec515aaf.jpg) 都是行向量,, 它们的余弦相似度 ![k](img/f93871977da52a6d11045d57c3e18728.jpg) 定义为:
![k(x, y) = \frac{x y^\top}{\|x\| \|y\|}](img/e5b3516a2cd7fbf2916643478e0bed70.jpg)
这被称为余弦相似度, 因为欧几里得(L2) 正则化将向量投影到单元球面内,那么它们的点积就是被向量表示的点之间的角度。
这种核函数对于计算以tf-idf向量表示的文档之间的相似度是一个通常的选择. [`cosine_similarity`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html#sklearn.metrics.pairwise.cosine_similarity "sklearn.metrics.pairwise.cosine_similarity") 接受 `scipy.sparse` 矩阵. (注意到 `sklearn.feature_extraction.text` 中的tf-idf函数能计算归一化的向量,在这种情况下 [`cosine_similarity`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html#sklearn.metrics.pairwise.cosine_similarity "sklearn.metrics.pairwise.cosine_similarity") 等同于 [`linear_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.linear_kernel.html#sklearn.metrics.pairwise.linear_kernel "sklearn.metrics.pairwise.linear_kernel"), 只是慢一点而已.)
References:
* C.D. Manning, P. Raghavan and H. Schütze (2008). Introduction to Information Retrieval. Cambridge University Press. [http://nlp.stanford.edu/IR-book/html/htmledition/the-vector-space-model-for-scoring-1.html](http://nlp.stanford.edu/IR-book/html/htmledition/the-vector-space-model-for-scoring-1.html)
## 5.7.2\. 线性核函数
函数 [`linear_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.linear_kernel.html#sklearn.metrics.pairwise.linear_kernel "sklearn.metrics.pairwise.linear_kernel") 是计算线性核函数, 也就是一种在 `degree=1``coef0=0` (同质化) 情况下的 [`polynomial_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.polynomial_kernel.html#sklearn.metrics.pairwise.polynomial_kernel "sklearn.metrics.pairwise.polynomial_kernel") 的特殊形式. 如果 `x``y` 是列向量, 它们的线性核函数是:
![k(x, y) = x^\top y](img/adc60d285d73d89dac7cb76f51617e64.jpg)
## 5.7.3\. 多项式核函数
[`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler") 为径向基函数核构造一个近似映射,又称为 Random Kitchen Sinks [RR2007]. 在应用线性算法(例如线性 SVM )之前,可以使用此转换来明确建模内核映射:
```py
函数 计算两个向量的d次方的多项式核函数. 多项式核函数代表着两个向量之间的相似度.
```
概念上来说,多项式核函数不仅考虑相同维度还考虑跨维度的向量的相似度。当被用在机器学习中的时候,这可以原来代表着特征之间的 相互作用。
多项式函数定义为:
![k(x, y) = (\gamma x^\top y +c_0)^d](img/5b87e1a1b34a0ac402ef602b152ee2f9.jpg)
其中:
>>> from sklearn.kernel_approximation import RBFSampler
>>> from sklearn.linear_model import SGDClassifier
>>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]
>>> y = [0, 0, 1, 1]
>>> rbf_feature = RBFSampler(gamma=1, random_state=1)
>>> X_features = rbf_feature.fit_transform(X)
>>> clf = SGDClassifier()
>>> clf.fit(X_features, y)
SGDClassifier(alpha=0.0001, average=False, class_weight=None, epsilon=0.1,
eta0=0.0, fit_intercept=True, l1_ratio=0.15,
learning_rate='optimal', loss='hinge', max_iter=5, n_iter=None,
n_jobs=1, penalty='l2', power_t=0.5, random_state=None,
shuffle=True, tol=None, verbose=0, warm_start=False)
>>> clf.score(X_features, y)
1.0
> * `x`, `y` 是输入向量
> * `d` 核函数维度
如果 ![c_0 = 0](img/c95237387255f824359f6c772cbb1df0.jpg) 那么核函数就被定义为同质化的.
## 5.7.4\. Sigmoid 核函数
```
函数 [`sigmoid_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.sigmoid_kernel.html#sklearn.metrics.pairwise.sigmoid_kernel "sklearn.metrics.pairwise.sigmoid_kernel") 计算两个向量之间的S型核函数. S型核函数也被称为双曲切线或者 多层感知机(因为在神经网络领域,它经常被当做激活函数). S型核函数定义为:
这个映射依赖于内核值的 Monte Carlo 近似. `fit` 方法执行 Monte Carlo 采样,而该 `transform` 方法执行 数据的映射.由于过程的固有随机性,结果可能会在不同的 `fit` 函数调用之间变化。
![k(x, y) = \tanh( \gamma x^\top y + c_0)](img/11265c80ea298a58e0a1010736d28b38.jpg)
`fit` 函数有两个参数: `n_components` 是特征变换的目标维数. `gamma` 是 RBF-kernel 的参数. `n_components` 越高,会导致更好的内核近似, 并且将产生与内核 SVM 产生的结果更相似的结果。请注意,”拟合” 特征函数实际上不取决于 `fit` 函数传递的数据。只有数据的维数被使用。 详情可以参考 [[RR2007]](#rr2007).
where:
对于给定的值 `n_components` [`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler")[`Nystroem`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.Nystroem.html#sklearn.kernel_approximation.Nystroem "sklearn.kernel_approximation.Nystroem") 中使用通常不太准确, 但是 [`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler") 使用更大的特征空间,更容易计算。
> * `x`, `y` 是输入向量
> * ![\gamma](img/6552bde3d3999c1a9728016416932af7.jpg) 是斜度
> * ![c_0](img/64ccaf1b6c08784a30158f809c081987.jpg) 是截距
[![http://sklearn.apachecn.org/cn/0.19.0/_images/sphx_glr_plot_kernel_approximation_0021.png](img/d90bb77f4f60c523c2bc041f768e8a49.jpg)](https://scikit-learn.org/stable/auto_examples/plot_kernel_approximation.html)
## 5.7.5\. RBF 核函数
将精确的 RBF kernel (左) 与 approximation (右) 进行比较。
函数 [`rbf_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.rbf_kernel.html#sklearn.metrics.pairwise.rbf_kernel "sklearn.metrics.pairwise.rbf_kernel") 计算计算两个向量之间的径向基函数核 (RBF) 。 其定义为:
>示例:
>* [Explicit feature map approximation for RBF kernels](https://scikit-learn.org/stable/auto_examples/plot_kernel_approximation.html#sphx-glr-auto-examples-plot-kernel-approximation-py)
![k(x, y) = \exp( -\gamma \| x-y \|^2)](img/a35122280170c396ab3c9d8fa3b62446.jpg)
## 5.7.3\. 加性卡方核
其中 `x``y` 是输入向量. 如果 ![\gamma = \sigma^{-2}](img/11336a74b43f75a360b60ce81f9cbdc0.jpg) 核函数就变成方差为 ![\sigma^2](img/d69db8c22e9315a6fb454b276d5ce534.jpg) 的高斯核函数.
Additive Chi Squared Kernel (加性卡方核)是直方图的核心,通常用于计算机视觉。
## 5.7.6\. 拉普拉斯核函数
这里使用的 Additive Chi Squared Kernel 给出
函数 [`laplacian_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.laplacian_kernel.html#sklearn.metrics.pairwise.laplacian_kernel "sklearn.metrics.pairwise.laplacian_kernel") 是一种径向基函数核的变体,定义为:
![k(x, y) = \sum_i \frac{2x_iy_i}{x_i+y_i}](img/bc7418a3ab8f749f1abd139faa96bee2.jpg)
![k(x, y) = \exp( -\gamma \| x-y \|_1)](img/99dfcad081b3f6e1f4648a9f7d24f103.jpg)
这个和 `sklearn.metrics.additive_chi2_kernel` 不完全一样.[VZ2010]_ 的作者喜欢上面的版本,因为它总是积极的。 由于这个 kernel 是可添加的,因此可以分别处理嵌入的 ![x_i](img/cf52655ee609af9f3c27c06448a5bf67.jpg). 这使得在规则的间隔类对傅里叶变换进行性才赢,代替近似的 Monte Carlo 采样。
其中 `x``y` 是输入向量 并且 ![\|x-y\|_1](img/b3ea6ae2442e72f261f037571e580979.jpg) 是输入向量之间的曼哈顿距离.
[`AdditiveChi2Sampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.AdditiveChi2Sampler.html#sklearn.kernel_approximation.AdditiveChi2Sampler "sklearn.kernel_approximation.AdditiveChi2Sampler") 类实现了这个组件采样方法. 每个组件都被采样 ![n](img/c87d9110f3d32ffa5fa08671e4af11fb.jpg) 次,每一个输入维数都会产生 *2n+1* 维(来自傅立叶变换的实部和复数部分的两个数据段的倍数). 在文献中,![n](img/c87d9110f3d32ffa5fa08671e4af11fb.jpg) 经常取为 1 或者 2,将数据集转换为 `n_samples * 5 * n_features` 大小(在 ![n=2](img/b94b3a3837e7741f704e3b9b23ba0880.jpg) 的情况下 ).
已被证明在机器学习中运用到无噪声数据中是有用的. 可见例如 [Machine learning for quantum mechanics in a nutshell](http://onlinelibrary.wiley.com/doi/10.1002/qua.24954/abstract/).
[`AdditiveChi2Sampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.AdditiveChi2Sampler.html#sklearn.kernel_approximation.AdditiveChi2Sampler "sklearn.kernel_approximation.AdditiveChi2Sampler") 提供的近似特征映射可以和 [`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler") 提供的近似特征映射合并,得到一个取幂的 chi squared kerne。可以查看 [[VZ2010]](#vz2010)[[VVZ2010]](#vvz2010) [`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler") 的合并.
## 5.7.7\. 卡方核函数
## 5.7.4\. Skewed Chi Squared Kernel (偏斜卡方核?暂译)
```py
在计算机视觉应用中训练非线性支持向量机时卡方核函数是一种非常流行的选择.
```
skewed chi squared kernel 给出下面公式
它能以 [`chi2_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.chi2_kernel.html#sklearn.metrics.pairwise.chi2_kernel "sklearn.metrics.pairwise.chi2_kernel") 计算然后将参数 [``](#id7)kernel=”precomputed”[``](#id9)传递到
![k(x,y) = \prod_i \frac{2\sqrt{x_i+c}\sqrt{y_i+c}}{x_i + y_i + 2c}](img/dd310c2fa94418ac4f4d12638444fd3b.jpg)
[`sklearn.svm.SVC`](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC "sklearn.svm.SVC") :
它有和 指数卡方核 相似的属性,用于计算机视觉.但是允许进行简单的蒙特卡洛近似的特征映射。
```py
>>> from sklearn.svm import SVC
>>> from sklearn.metrics.pairwise import chi2_kernel
>>> X = [[0, 1], [1, 0], [.2, .8], [.7, .3]]
>>> y = [0, 1, 0, 1]
>>> K = chi2_kernel(X, gamma=.5)
>>> K
array([[ 1\. , 0.36..., 0.89..., 0.58...],
[ 0.36..., 1\. , 0.51..., 0.83...],
[ 0.89..., 0.51..., 1\. , 0.77... ],
[ 0.58..., 0.83..., 0.77... , 1\. ]])
[`SkewedChi2Sampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.SkewedChi2Sampler.html#sklearn.kernel_approximation.SkewedChi2Sampler "sklearn.kernel_approximation.SkewedChi2Sampler") 的使用和之前描述的 [`RBFSampler`](https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.RBFSampler.html#sklearn.kernel_approximation.RBFSampler "sklearn.kernel_approximation.RBFSampler") 一样.唯一的区别是自由参数,称之为 ![c](img/d5c9a11453ea30a1be50a1034052bd6b.jpg). 这种映射和数学细节可以参考 [[LS2010]](#ls2010).
```
## 5.7.5\. 数学方面的细节
```py
>>> svm = SVC(kernel='precomputed').fit(K, y)
>>> svm.predict(K)
array([0, 1, 0, 1])
```
也可以直接使用 `kernel` 变量:
```py
>>> svm = SVC(kernel=chi2_kernel).fit(X, y)
>>> svm.predict(X)
array([0, 1, 0, 1])
```
核技巧 像支持向量机,或者 核化 PCA 依赖于 再生核希尔伯特空间(RKHS) 对于任何 核函数 ![k](img/f93871977da52a6d11045d57c3e18728.jpg) (叫做 Mercer kernel),保证了 ![\phi](img/ff5e98366afa13070d3b410c55a80db1.jpg) 进入 希尔伯特空间 ![\mathcal{H}](img/433fedd575581cddbd612624b65e5dac.jpg) 的映射,例如:
卡方核函数定义为
![k(x,y) = \langle \phi(x), \phi(y) \rangle](img/e56abe6d36f21c0c6dd22d2a84535415.jpg)
![k(x, y) = \exp \left (-\gamma \sum_i \frac{(x[i] - y[i]) ^ 2}{x[i] + y[i]} \right )](img/33b1cdc0654561cadac36a1232552b99.jpg)
![\langle \cdot, \cdot \rangle](img/e668ecc249e709e47f6955a74528bf7b.jpg) 是在 Hilbert space 中做内积.
数据假定为非负的,并且已经以L1正则化。 归一化随着与卡方平方距离的连接而被合理化,其是离散概率分布之间的距离。
如果一个算法,例如线性支持向量机或者 PCA,依赖于数据集的数量级 ![x_i](img/cf52655ee609af9f3c27c06448a5bf67.jpg) ,可能会使用 ![k(x_i, x_j)](img/2b117c8d0556a027e7ee3bb265a6bf63.jpg) , 符合孙发的映射 ![\phi(x_i)](img/c03e9014ab434e11e9323f87908ed15e.jpg) . 使用 ![k](img/f93871977da52a6d11045d57c3e18728.jpg) 的优点在于 ![\phi](img/ff5e98366afa13070d3b410c55a80db1.jpg) 永远不会直接计算,允许大量的特征计算(甚至是无限的).
卡方核函数最常用于可视化词汇的矩形图
kernel 方法的一个缺点是,在优化过程中有可能存储大量的 kernel 值 ![k(x_i, x_j)](img/2b117c8d0556a027e7ee3bb265a6bf63.jpg). 如果使用核函数的分类器应用于新的数据 ![y_j](img/8610705cf45aa68b12197abd65653479.jpg) , ![k(x_i, y_j)](img/1375f487efd6b9db955b7f7aafecc441.jpg) 需要计算用来做预测,训练集中的 ![x_i](img/cf52655ee609af9f3c27c06448a5bf67.jpg) 有可能有很多不同的
参考:
这个子模块的这些类中允许嵌入 ![\phi](img/ff5e98366afa13070d3b410c55a80db1.jpg),从而明确的与 ![\phi(x_i)](img/c03e9014ab434e11e9323f87908ed15e.jpg) 一起工作, 这消除了使用 kernel 的需要和存储训练样本.
* Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 [http://research.microsoft.com/en-us/um/people/manik/projects/trade-off/papers/ZhangIJCV06.pdf](http://research.microsoft.com/en-us/um/people/manik/projects/trade-off/papers/ZhangIJCV06.pdf)
>参考:
>* [[RR2007]](#id3) [“Random features for large-scale kernel machines”](http://www.robots.ox.ac.uk/~vgg/rg/papers/randomfeatures.pdf) Rahimi, A. and Recht, B. - Advances in neural information processing 2007,
>* [[LS2010]](#id7) [“Random Fourier approximations for skewed multiplicative histogram kernels”](http://www.maths.lth.se/matematiklth/personal/sminchis/papers/lis_dagm10.pdf) Random Fourier approximations for skewed multiplicative histogram kernels - Lecture Notes for Computer Sciencd (DAGM)
>* [[VZ2010]](#id5) [“Efficient additive kernels via explicit feature maps”](https://www.robots.ox.ac.uk/~vgg/publications/2011/Vedaldi11/vedaldi11.pdf) Vedaldi, A. and Zisserman, A. - Computer Vision and Pattern Recognition 2010
>* [[VVZ2010]](#id6) [“Generalized RBF feature maps for Efficient Detection”](https://www.robots.ox.ac.uk/~vgg/publications/2010/Sreekanth10/sreekanth10.pdf) Vempati, S. and Vedaldi, A. and Zisserman, A. and Jawahar, CV - 2010
# 5.8\. 预测目标 (`y`) 的转换
# 5.8\. 成对的矩阵, 类别和核函数
校验者:
        [@FontTian](https://github.com/FontTian)
......@@ -6,64 +6,146 @@
翻译者:
        [@程威](https://github.com/apachecn/scikit-learn-doc-zh)
## 5.8.1\. 标签二值化
The [`sklearn.metrics.pairwise`](classes.html#module-sklearn.metrics.pairwise "sklearn.metrics.pairwise") 子模块实现了用于评估成对距离或样本集合之间的联系的实用程序。
[`LabelBinarizer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html#sklearn.preprocessing.LabelBinarizer "sklearn.preprocessing.LabelBinarizer") 是一个用来从多类别列表创建标签矩阵的工具类:
本模块同时包含距离度量和核函数,对于这两者这里提供一个简短的总结。
```py
>>> from sklearn import preprocessing
>>> lb = preprocessing.LabelBinarizer()
>>> lb.fit([1, 2, 6, 4, 2])
LabelBinarizer(neg_label=0, pos_label=1, sparse_output=False)
>>> lb.classes_
array([1, 2, 4, 6])
>>> lb.transform([1, 6])
array([[1, 0, 0, 0],
[0, 0, 0, 1]])
距离度量是形如 `d(a, b)` 例如 `d(a, b) < d(a, c)` 如果对象 `a``b` 被认为 “更加相似” 相比于 `a``c`. 两个完全相同的目标的距离是零。最广泛使用的例子就是欧几里得距离。 为了保证是 ‘真实的’ 度量, 其必须满足以下条件:
```
> 1. 对于所有的 a 和 b,d(a, b) >= 0
> 2. 正定性:当且仅当 a = b时,d(a, b) == 0
> 3. 对称性:d(a, b) == d(b, a)
> 4. 三角不等式:d(a, c) <= d(a, b) + d(b, c)
对于多类别是实例,可以使用 [`MultiLabelBinarizer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html#sklearn.preprocessing.MultiLabelBinarizer "sklearn.preprocessing.MultiLabelBinarizer"):
核函数是相似度的标准. 如果对象 `a``b` 被认为 “更加相似” 相比对象 `a``c`,那么 `s(a, b) > s(a, c)`. 核函数必须是半正定性的.
```py
>>> lb = preprocessing.MultiLabelBinarizer()
>>> lb.fit_transform([(1, 2), (3,)])
array([[1, 1, 0],
[0, 0, 1]])
>>> lb.classes_
array([1, 2, 3])
存在许多种方法将距离度量转换为相似度标准,例如核函数。 假定 `D` 是距离, and `S` 是核函数:
> 1. `S = np.exp(-D * gamma)`, 其中 `gamma` 的一种选择是 `1 / num_features`
> 2. `S = 1. / (D / np.max(D))`
X 的行向量和 Y 的行向量之间的距离可以用函数 [pairwise_distances](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise_distances.html#sklearn.metrics.pairwise_distances) 进行计算。 如果 Y 被忽略,则 X 的所有行向量的成对距离就会被计算。 类似的,函数 [pairwise.pairwise_kernels](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_kernels.html#sklearn.metrics.pairwise.pairwise_kernels) 可以使用不同的核函数(kernel functions)来计算 X 和 Y 之间的 kernel。 请查看API获得更多详情。
```py
>>> import numpy as np
>>> from sklearn.metrics import pairwise_distances
>>> from sklearn.metrics.pairwise import pairwise_kernels
>>> X = np.array([[2, 3], [3, 5], [5, 8]])
>>> Y = np.array([[1, 0], [2, 1]])
>>> pairwise_distances(X, Y, metric='manhattan')
array([[ 4., 2.],
[ 7., 5.],
[12., 10.]])
>>> pairwise_distances(X, metric='manhattan')
array([[0., 3., 8.],
[3., 0., 5.],
[8., 5., 0.]])
>>> pairwise_kernels(X, Y, metric='linear')
array([[ 2., 7.],
[ 3., 11.],
[ 5., 18.]])
```
## 5.8.2\. 标签编码
## 5.8.1\. 余弦相似度
[`cosine_similarity`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html#sklearn.metrics.pairwise.cosine_similarity "sklearn.metrics.pairwise.cosine_similarity") 计算L2正则化的向量的点积. 也就是说, if ![x](img/5c82dbae35dc43d2f556f9f284d9d184.jpg) 和 ![y](img/0775c03fc710a24df297dedcec515aaf.jpg) 都是行向量,, 它们的余弦相似度 ![k](img/f93871977da52a6d11045d57c3e18728.jpg) 定义为:
![k(x, y) = \frac{x y^\top}{\|x\| \|y\|}](img/e5b3516a2cd7fbf2916643478e0bed70.jpg)
这被称为余弦相似度, 因为欧几里得(L2) 正则化将向量投影到单元球面内,那么它们的点积就是被向量表示的点之间的角度。
这种核函数对于计算以tf-idf向量表示的文档之间的相似度是一个通常的选择. [`cosine_similarity`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html#sklearn.metrics.pairwise.cosine_similarity "sklearn.metrics.pairwise.cosine_similarity") 接受 `scipy.sparse` 矩阵. (注意到 `sklearn.feature_extraction.text` 中的tf-idf函数能计算归一化的向量,在这种情况下 [`cosine_similarity`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html#sklearn.metrics.pairwise.cosine_similarity "sklearn.metrics.pairwise.cosine_similarity") 等同于 [`linear_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.linear_kernel.html#sklearn.metrics.pairwise.linear_kernel "sklearn.metrics.pairwise.linear_kernel"), 只是慢一点而已.)
>参考:
>* C.D. Manning, P. Raghavan and H. Schütze (2008). Introduction to Information Retrieval. Cambridge University Press. [http://nlp.stanford.edu/IR-book/html/htmledition/the-vector-space-model-for-scoring-1.html](http://nlp.stanford.edu/IR-book/html/htmledition/the-vector-space-model-for-scoring-1.html)
## 5.8.2\. 线性核函数
函数 [`linear_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.linear_kernel.html#sklearn.metrics.pairwise.linear_kernel "sklearn.metrics.pairwise.linear_kernel") 是计算线性核函数, 也就是一种在 `degree=1``coef0=0` (同质化) 情况下的 [`polynomial_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.polynomial_kernel.html#sklearn.metrics.pairwise.polynomial_kernel "sklearn.metrics.pairwise.polynomial_kernel") 的特殊形式. 如果 `x``y` 是列向量, 它们的线性核函数是:
![k(x, y) = x^\top y](img/adc60d285d73d89dac7cb76f51617e64.jpg)
## 5.8.3\. 多项式核函数
函数[polynomial_kernel](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.polynomial_kernel.html#sklearn.metrics.pairwise.polynomial_kernel)计算两个向量的d次方的多项式核函数. 多项式核函数代表着两个向量之间的相似度.概念上来说,多项式核函数不仅考虑相同维度还考虑跨维度的向量的相似度。当被用在机器学习中的时候,这可以原来代表着特征之间的 相互作用。
多项式函数定义为:
![k(x, y) = (\gamma x^\top y +c_0)^d](img/5b87e1a1b34a0ac402ef602b152ee2f9.jpg)
其中:
* `x`, `y` 是输入向量
* `d` 核函数维度
如果 ![c_0 = 0](img/c95237387255f824359f6c772cbb1df0.jpg) 那么核函数就被定义为同质化的.
## 5.8.4\. Sigmoid 核函数
[`LabelEncoder`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html#sklearn.preprocessing.LabelEncoder "sklearn.preprocessing.LabelEncoder") 是一个可以用来将标签规范化的工具类,它可以将标签的编码值范围限定在[0,n_classes-1]. 这在编写高效的Cython程序时是非常有用的. [`LabelEncoder`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html#sklearn.preprocessing.LabelEncoder "sklearn.preprocessing.LabelEncoder") 可以如下使用:
函数 [`sigmoid_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.sigmoid_kernel.html#sklearn.metrics.pairwise.sigmoid_kernel "sklearn.metrics.pairwise.sigmoid_kernel") 计算两个向量之间的S型核函数. S型核函数也被称为双曲切线或者 多层感知机(因为在神经网络领域,它经常被当做激活函数). S型核函数定义为:
![k(x, y) = \tanh( \gamma x^\top y + c_0)](img/11265c80ea298a58e0a1010736d28b38.jpg)
其中:
* `x`, `y` 是输入向量
* ![\gamma](img/6552bde3d3999c1a9728016416932af7.jpg) 是斜度
* ![c_0](img/64ccaf1b6c08784a30158f809c081987.jpg) 是截距
## 5.8.5\. RBF 核函数
函数 [`rbf_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.rbf_kernel.html#sklearn.metrics.pairwise.rbf_kernel "sklearn.metrics.pairwise.rbf_kernel") 计算计算两个向量之间的径向基函数核 (RBF) 。 其定义为:
![k(x, y) = \exp( -\gamma \| x-y \|^2)](img/a35122280170c396ab3c9d8fa3b62446.jpg)
其中 `x``y` 是输入向量. 如果 ![\gamma = \sigma^{-2}](img/11336a74b43f75a360b60ce81f9cbdc0.jpg) 核函数就变成方差为 ![\sigma^2](img/d69db8c22e9315a6fb454b276d5ce534.jpg) 的高斯核函数.
## 5.8.6\. 拉普拉斯核函数
函数 [`laplacian_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.laplacian_kernel.html#sklearn.metrics.pairwise.laplacian_kernel "sklearn.metrics.pairwise.laplacian_kernel") 是一种径向基函数核的变体,定义为:
![k(x, y) = \exp( -\gamma \| x-y \|_1)](img/99dfcad081b3f6e1f4648a9f7d24f103.jpg)
其中 `x``y` 是输入向量 并且 ![\|x-y\|_1](img/b3ea6ae2442e72f261f037571e580979.jpg) 是输入向量之间的曼哈顿距离.
已被证明在机器学习中运用到无噪声数据中是有用的. 可见例如 [Machine learning for quantum mechanics in a nutshell](http://onlinelibrary.wiley.com/doi/10.1002/qua.24954/abstract/).
## 5.8.7\. 卡方核函数
在计算机视觉应用中训练非线性支持向量机时,卡方核函数是一种非常流行的选择.它能以 [`chi2_kernel`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.chi2_kernel.html#sklearn.metrics.pairwise.chi2_kernel "sklearn.metrics.pairwise.chi2_kernel") 计算然后将参数`kernel=”precomputed”`传递到
[`sklearn.svm.SVC`](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC "sklearn.svm.SVC") :
```py
>>> from sklearn import preprocessing
>>> le = preprocessing.LabelEncoder()
>>> le.fit([1, 2, 2, 6])
LabelEncoder()
>>> le.classes_
array([1, 2, 6])
>>> le.transform([1, 1, 2, 6])
array([0, 0, 1, 2])
>>> le.inverse_transform([0, 0, 1, 2])
array([1, 1, 2, 6])
>>> from sklearn.svm import SVC
>>> from sklearn.metrics.pairwise import chi2_kernel
>>> X = [[0, 1], [1, 0], [.2, .8], [.7, .3]]
>>> y = [0, 1, 0, 1]
>>> K = chi2_kernel(X, gamma=.5)
>>> K
array([[1. , 0.36787944, 0.89483932, 0.58364548],
[0.36787944, 1. , 0.51341712, 0.83822343],
[0.89483932, 0.51341712, 1. , 0.7768366 ],
[0.58364548, 0.83822343, 0.7768366 , 1. ]])
>>> svm = SVC(kernel='precomputed').fit(K, y)
>>> svm.predict(K)
array([0, 1, 0, 1])
```
当然,它也可以用于非数值型标签的编码转换成数值标签(只要它们是可哈希并且可比较的):
也可以直接使用 `kernel` 变量:
```py
>>> le = preprocessing.LabelEncoder()
>>> le.fit(["paris", "paris", "tokyo", "amsterdam"])
LabelEncoder()
>>> list(le.classes_)
['amsterdam', 'paris', 'tokyo']
>>> le.transform(["tokyo", "tokyo", "paris"])
array([2, 2, 1])
>>> list(le.inverse_transform([2, 2, 1]))
['tokyo', 'tokyo', 'paris']
>>> svm = SVC(kernel=chi2_kernel).fit(X, y)
>>> svm.predict(X)
array([0, 1, 0, 1])
```
卡方核函数定义为
![k(x, y) = \exp \left (-\gamma \sum_i \frac{(x[i] - y[i]) ^ 2}{x[i] + y[i]} \right )](img/33b1cdc0654561cadac36a1232552b99.jpg)
数据假定为非负的,并且已经以L1正则化。 归一化随着与卡方平方距离的连接而被合理化,其是离散概率分布之间的距离。
卡方核函数最常用于可视化词汇的矩形图。
>参考:
>* Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 [http://research.microsoft.com/en-us/um/people/manik/projects/trade-off/papers/ZhangIJCV06.pdf](http://research.microsoft.com/en-us/um/people/manik/projects/trade-off/papers/ZhangIJCV06.pdf)
# 5.9\. 预测目标 (`y`) 的转换
校验者:
        [@FontTian](https://github.com/FontTian)
        [@numpy](https://github.com/apachecn/scikit-learn-doc-zh)
翻译者:
        [@程威](https://github.com/apachecn/scikit-learn-doc-zh)
本章要介绍的这些变换器不是被用于特征的,而是只被用于变换监督学习的目标。 如果你希望变换预测目标以进行学习,但是在原始空间中评估模型,请参考[回归中的目标转换](docs/38?id=_512-回归中的目标转换)
## 5.9.1\. 标签二值化
[`LabelBinarizer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html#sklearn.preprocessing.LabelBinarizer "sklearn.preprocessing.LabelBinarizer") 是一个用来从多类别列表创建标签矩阵的工具类:
```py
>>> from sklearn import preprocessing
>>> lb = preprocessing.LabelBinarizer()
>>> lb.fit([1, 2, 6, 4, 2])
LabelBinarizer(neg_label=0, pos_label=1, sparse_output=False)
>>> lb.classes_
array([1, 2, 4, 6])
>>> lb.transform([1, 6])
array([[1, 0, 0, 0],
[0, 0, 0, 1]])
```
对于多类别是实例,可以使用 [`MultiLabelBinarizer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html#sklearn.preprocessing.MultiLabelBinarizer "sklearn.preprocessing.MultiLabelBinarizer"):
```py
>>> lb = preprocessing.MultiLabelBinarizer()
>>> lb.fit_transform([(1, 2), (3,)])
array([[1, 1, 0],
[0, 0, 1]])
>>> lb.classes_
array([1, 2, 3])
```
## 5.9.2\. 标签编码
[`LabelEncoder`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html#sklearn.preprocessing.LabelEncoder "sklearn.preprocessing.LabelEncoder") 是一个可以用来将标签规范化的工具类,它可以将标签的编码值范围限定在[0,n_classes-1]. 这在编写高效的Cython程序时是非常有用的. [`LabelEncoder`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html#sklearn.preprocessing.LabelEncoder "sklearn.preprocessing.LabelEncoder") 可以如下使用:
```py
>>> from sklearn import preprocessing
>>> le = preprocessing.LabelEncoder()
>>> le.fit([1, 2, 2, 6])
LabelEncoder()
>>> le.classes_
array([1, 2, 6])
>>> le.transform([1, 1, 2, 6])
array([0, 0, 1, 2])
>>> le.inverse_transform([0, 0, 1, 2])
array([1, 1, 2, 6])
```
当然,它也可以用于非数值型标签的编码转换成数值标签(只要它们是可哈希并且可比较的):
```py
>>> le = preprocessing.LabelEncoder()
>>> le.fit(["paris", "paris", "tokyo", "amsterdam"])
LabelEncoder()
>>> list(le.classes_)
['amsterdam', 'paris', 'tokyo']
>>> le.transform(["tokyo", "tokyo", "paris"])
array([2, 2, 1])
>>> list(le.inverse_transform([2, 2, 1]))
['tokyo', 'tokyo', 'paris']
```
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册