提交 28a56b94 编写于 作者: L loopyme

更新第五章标题序号

上级 e98327d0
# 4\. 数据集转换
# 5\. 数据集转换
scikit-learn 提供了一个用于转换数据集的库, 它也许会 clean(清理)(请参阅 [预处理数据](modules/preprocessing.html#preprocessing)), reduce(减少)(请参阅 [无监督降维](modules/unsupervised_reduction.html#data-reduction)), expand(扩展)(请参阅 [内核近似](modules/kernel_approximation.html#kernel-approximation))或 generate(生成)(请参阅 [特征提取](modules/feature_extraction.html#feature-extraction)) feature representations(特征表示).
......
# 4.1\. Pipeline(管道)和 FeatureUnion(特征联合): 合并的评估器
# 5.1\. Pipeline(管道)和 FeatureUnion(特征联合): 合并的评估器
校验者:
        [@程威](https://github.com/apachecn/scikit-learn-doc-zh)
翻译者:
        [@Sehriff](https://github.com/apachecn/scikit-learn-doc-zh)
## 4.1.1\. Pipeline: 链式评估器
## 5.1.1\. Pipeline: 链式评估器
```py
可以把多个评估器链接成一个这个是很有用的因为处理数据的步骤一般都是固定的例如特征选择标准化和分类
......@@ -33,21 +33,21 @@
管道中的所有评估器,除了最后一个评估器,管道的所有评估器必须是转换器。 (例如,必须有 `transform` 方法). 最后一个评估器的类型不限(转换器、分类器等等)
### 4.1.1.1\. 用法
### 5.1.1.1\. 用法
> [`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline "sklearn.pipeline.Pipeline") 使用一系列 `(key, value)` 键值对来构建,其中 `key` 是你给这个步骤起的名字, `value` 是一个评估器对象:
>
>
> ```py
> >>> from sklearn.pipeline import Pipeline
> >>> from sklearn.svm import SVC
> >>> from sklearn.decomposition import PCA
> >>> estimators = [('reduce_dim', PCA()), ('clf', SVC())]
> >>> pipe = Pipeline(estimators)
> >>> pipe
> >>> pipe
> Pipeline(memory=None,
> steps=[('reduce_dim', PCA(copy=True,...)),
> ('clf', SVC(C=1.0,...))])
>
>
> ```
功能函数 [`make_pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.make_pipeline.html#sklearn.pipeline.make_pipeline "sklearn.pipeline.make_pipeline") 是构建管道的缩写; 它接收多个评估器并返回一个管道,自动填充评估器名:
......@@ -56,7 +56,7 @@
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.naive_bayes import MultinomialNB
>>> from sklearn.preprocessing import Binarizer
>>> make_pipeline(Binarizer(), MultinomialNB())
>>> make_pipeline(Binarizer(), MultinomialNB())
Pipeline(memory=None,
steps=[('binarizer', Binarizer(copy=True, threshold=0.0)),
('multinomialnb', MultinomialNB(alpha=1.0,
......@@ -86,7 +86,7 @@ PCA(copy=True, iterated_power='auto', n_components=None, random_state=None,
管道中的评估器参数可以通过 `<estimator>__<parameter>` 语义来访问:
```py
>>> pipe.set_params(clf__C=10)
>>> pipe.set_params(clf__C=10)
Pipeline(memory=None,
steps=[('reduce_dim', PCA(copy=True, iterated_power='auto',...)),
('clf', SVC(C=10, cache_size=200, class_weight=None,...))])
......@@ -135,11 +135,11 @@ True
* [调整估计器的超参数](grid_search.html#grid-search)
### 4.1.1.2\. 注意点
### 5.1.1.2\. 注意点
对管道调用 `fit` 方法的效果跟依次对每个评估器调用 `fit` 方法一样, 都是``transform`` 输入并传递给下个步骤。 管道中最后一个评估器的所有方法,管道都有,例如,如果最后的评估器是一个分类器, [`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline "sklearn.pipeline.Pipeline") 可以当做分类器来用。如果最后一个评估器是转换器,管道也一样可以。
### 4.1.1.3\. 缓存转换器:避免重复计算
### 5.1.1.3\. 缓存转换器:避免重复计算
适配转换器是很耗费计算资源的。设置了``memory`` 参数, [`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline "sklearn.pipeline.Pipeline") 将会在调用``fit``方法后缓存每个转换器。 如果参数和输入数据相同,这个特征用于避免重复计算适配的转换器。典型的例子是网格搜索转换器,该转化器只要适配一次就可以多次使用。
......@@ -156,7 +156,7 @@ True
>>> estimators = [('reduce_dim', PCA()), ('clf', SVC())]
>>> cachedir = mkdtemp()
>>> pipe = Pipeline(estimators, memory=cachedir)
>>> pipe
>>> pipe
Pipeline(...,
steps=[('reduce_dim', PCA(copy=True,...)),
('clf', SVC(C=1.0,...))])
......@@ -178,11 +178,11 @@ Warning
>>> svm1 = SVC()
>>> pipe = Pipeline([('reduce_dim', pca1), ('clf', svm1)])
>>> pipe.fit(digits.data, digits.target)
...
...
Pipeline(memory=None,
steps=[('reduce_dim', PCA(...)), ('clf', SVC(...))])
>>> # The pca instance can be inspected directly
>>> print(pca1.components_)
>>> print(pca1.components_)
[[ -1.77484909e-19 ... 4.07058917e-18]]
```
......@@ -196,11 +196,11 @@ Pipeline(memory=None,
>>> cached_pipe = Pipeline([('reduce_dim', pca2), ('clf', svm2)],
... memory=cachedir)
>>> cached_pipe.fit(digits.data, digits.target)
...
...
Pipeline(memory=...,
steps=[('reduce_dim', PCA(...)), ('clf', SVC(...))])
>>> print(cached_pipe.named_steps['reduce_dim'].components_)
...
...
[[ -1.77484909e-19 ... 4.07058917e-18]]
>>> # Remove the cache directory
>>> rmtree(cachedir)
......@@ -211,7 +211,7 @@ Pipeline(memory=None,
* [Selecting dimensionality reduction with Pipeline and GridSearchCV](https://scikit-learn.org/stable/auto_examples/plot_compare_reduction.html#sphx-glr-auto-examples-plot-compare-reduction-py)
## 4.1.2\. FeatureUnion(特征联合): 个特征层面
## 5.1.2\. FeatureUnion(特征联合): 个特征层面
[`FeatureUnion`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.FeatureUnion.html#sklearn.pipeline.FeatureUnion "sklearn.pipeline.FeatureUnion") 合并了多个转换器对象形成一个新的转换器,该转换器合并了他们的输出。一个 [`FeatureUnion`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.FeatureUnion.html#sklearn.pipeline.FeatureUnion "sklearn.pipeline.FeatureUnion") 可以接收多个转换器对象。在适配期间,每个转换器都单独的和数据适配。 对于转换数据,转换器可以并发使用,且输出的样本向量被连接成更大的向量。
......@@ -221,7 +221,7 @@ Pipeline(memory=None,
(一个 [`FeatureUnion`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.FeatureUnion.html#sklearn.pipeline.FeatureUnion "sklearn.pipeline.FeatureUnion") 没办法检查两个转换器是否会产出相同的特征。它仅仅在特征集合不相关时产生联合并确认是调用者的职责。)
### 4.1.2.1\. 用法
### 5.1.2.1\. 用法
一个 [`FeatureUnion`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.FeatureUnion.html#sklearn.pipeline.FeatureUnion "sklearn.pipeline.FeatureUnion") 是通过一系列 `(key, value)` 键值对来构建的,其中的 `key` 给转换器指定的名字 (一个绝对的字符串; 他只是一个代号), `value` 是一个评估器对象:
......@@ -231,7 +231,7 @@ Pipeline(memory=None,
>>> from sklearn.decomposition import KernelPCA
>>> estimators = [('linear_pca', PCA()), ('kernel_pca', KernelPCA())]
>>> combined = FeatureUnion(estimators)
>>> combined
>>> combined
FeatureUnion(n_jobs=1,
transformer_list=[('linear_pca', PCA(copy=True,...)),
('kernel_pca', KernelPCA(alpha=1.0,...))],
......@@ -245,7 +245,7 @@ FeatureUnion(n_jobs=1,
```py
>>> combined.set_params(kernel_pca=None)
...
...
FeatureUnion(n_jobs=1,
transformer_list=[('linear_pca', PCA(copy=True,...)),
('kernel_pca', None)],
......@@ -256,4 +256,4 @@ FeatureUnion(n_jobs=1,
例子:
* [Concatenating multiple feature extraction methods](https://scikit-learn.org/stable/auto_examples/plot_feature_stacker.html#sphx-glr-auto-examples-plot-feature-stacker-py)
* [Feature Union with Heterogeneous Data Sources](https://scikit-learn.org/stable/auto_examples/hetero_feature_union.html#sphx-glr-auto-examples-hetero-feature-union-py)
\ No newline at end of file
* [Feature Union with Heterogeneous Data Sources](https://scikit-learn.org/stable/auto_examples/hetero_feature_union.html#sphx-glr-auto-examples-hetero-feature-union-py)
# 4.2\. 特征提取
# 5.2\. 特征提取
校验者:
        [@if only](https://github.com/apachecn/scikit-learn-doc-zh)
......@@ -11,7 +11,7 @@ Note
特征特征提取与 特征选择 有很大的不同:前者包括将任意数据(如文本或图像)转换为可用于机器学习的数值特征。后者是将这些特征应用到机器学习中。
## 4.2.1\. 从字典类型加载特征
## 5.2.1\. 从字典类型加载特征
[`DictVectorizer`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.DictVectorizer.html#sklearn.feature_extraction.DictVectorizer "sklearn.feature_extraction.DictVectorizer") 可用于将标准的Python字典(dict)对象列表的要素数组转换为 scikit-learn 估计器使用的 NumPy/SciPy 表示形式。
......@@ -77,7 +77,7 @@ array([[ 1., 1., 1., 1., 1., 1.]])
你可以想象,如果一个文本语料库的每一个单词都提取了这样一个上下文,那么所得的矩阵将会非常宽(许多 one-hot-features),其中大部分通常将会是0。 为了使结果数据结构能够适应内存,该类``DictVectorizer```scipy.sparse` 默认使用一个矩阵而不是一个 `numpy.ndarray`
## 4.2.2\. 特征哈希(相当于一种降维技巧)
## 5.2.2\. 特征哈希(相当于一种降维技巧)
[`FeatureHasher`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.FeatureHasher.html#sklearn.feature_extraction.FeatureHasher "sklearn.feature_extraction.FeatureHasher") 是一种高速,低内存消耗的向量化方法,它使用了`特征散列 feature hashing <[https://en.wikipedia.org/wiki/Feature_hashing](https://en.wikipedia.org/wiki/Feature_hashing)>`_ 技术 ,或可称为 “散列法” (hashing trick)的技术。 代替在构建训练中遇到的特征的哈希表,如向量化所做的那样 [`FeatureHasher`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.FeatureHasher.html#sklearn.feature_extraction.FeatureHasher "sklearn.feature_extraction.FeatureHasher") 将哈希函数应用于特征,以便直接在样本矩阵中确定它们的列索引。 结果是以牺牲可检测性为代价,提高速度和减少内存的使用; 哈希表不记得输入特性是什么样的,没有 `inverse_transform` 办法。
......@@ -123,7 +123,7 @@ X = hasher.transform(raw_X)
注意使用发生器的理解,它将懒惰引入到特征提取中:词令牌(token)只能根据需要从哈希值进行处理。
### 4.2.2.1\. 实现细节
### 5.2.2.1\. 实现细节
[`FeatureHasher`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.FeatureHasher.html#sklearn.feature_extraction.FeatureHasher "sklearn.feature_extraction.FeatureHasher") 使用签名的 32-bit 变体的 MurmurHash3。 因此导致(并且由于限制 `scipy.sparse`),当前支持的功能的最大数量 ![2^{31} - 1](img/7a79f764bd3db11876c1065b6677af80.jpg).
......@@ -138,9 +138,9 @@ X = hasher.transform(raw_X)
* Kilian Weinberger, Anirban Dasgupta, John Langford, Alex Smola and Josh Attenberg (2009). [用于大规模多任务学习的特征散列](http://alex.smola.org/papers/2009/Weinbergeretal09.pdf). Proc. ICML.
* [MurmurHash3](https://github.com/aappleby/smhasher).
## 4.2.3\. 文本特征提取
## 5.2.3\. 文本特征提取
### 4.2.3.1\. 话语表示
### 5.2.3.1\. 话语表示
文本分析是机器学习算法的主要应用领域。 然而,原始数据,符号文字序列不能直接传递给算法,因为它们大多数要求具有固定长度的数字矩阵特征向量,而不是具有可变长度的原始文本文档。
......@@ -159,7 +159,7 @@ X = hasher.transform(raw_X)
我们称**向量化**是将文本文档集合转换为数字集合特征向量的普通方法。 这种特殊思想(令牌化,计数和归一化)被称为 **Bag of Words** 或 “Bag of n-grams” 模型。 文档由单词出现来描述,同时完全忽略文档中单词的相对位置信息。
### 4.2.3.2\. 稀疏
### 5.2.3.2\. 稀疏
由于大多数文本文档通常只使用文本词向量全集中的一个小子集,所以得到的矩阵将具有许多特征值为零(通常大于99%)。
......@@ -167,7 +167,7 @@ X = hasher.transform(raw_X)
为了能够将这样的矩阵存储在存储器中,并且还可以加速代数的矩阵/向量运算,实现通常将使用诸如 `scipy.sparse` 包中的稀疏实现。
### 4.2.3.3\. 常见 Vectorizer 使用方法
### 5.2.3.3\. 常见 Vectorizer 使用方法
[`CountVectorizer`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer "sklearn.feature_extraction.text.CountVectorizer") 在单个类中实现了 tokenization (词语切分)和 occurrence counting (出现频数统计):
......@@ -283,7 +283,7 @@ array([0, 0, 0, 1]...)
```
### 4.2.3.4\. Tf–idf 项加权
### 5.2.3.4\. Tf–idf 项加权
在一个大的文本语料库中,一些单词将出现很多次(例如 “the”, “a”, “is” 是英文),因此对文档的实际内容没有什么有意义的信息。 如果我们将直接计数数据直接提供给分类器,那么这些频繁词组会掩盖住那些我们关注但很少出现的词。
......@@ -425,7 +425,7 @@ array([ 1\. ..., 2.25..., 1.84...])
> * 用于文本特征提取和评估的样本管道 [Sample pipeline for text feature extraction and evaluation](https://scikit-learn.org/stable/auto_examples/model_selection/grid_search_text_feature_extraction.html#sphx-glr-auto-examples-model-selection-grid-search-text-feature-extraction-py)
### 4.2.3.5\. 解码文本文件
### 5.2.3.5\. 解码文本文件
文本由字符组成,但文件由字节组成。字节转化成字符依照一定的编码(encoding)方式。 为了在Python中的使用文本文档,这些字节必须被 _解码_ 为 Unicode 的字符集。 常用的编码方式有 ASCII,Latin-1(西欧),KOI8-R(俄语)和通用编码 UTF-8 和 UTF-16。还有许多其他的编码存在
......@@ -461,7 +461,7 @@ scikit-learn 中的文本提取器知道如何解码文本文件, 但只有当
(根据 `chardet` 的版本,可能会返回第一个值错误的结果。) 有关 Unicode 和字符编码的一般介绍,请参阅Joel Spolsky的 [绝对最小每个软件开发人员必须了解 Unicode](http://www.joelonsoftware.com/articles/Unicode.html).
### 4.2.3.6\. 应用和实例
### 5.2.3.6\. 应用和实例
词汇表达方式相当简单,但在实践中却非常有用。
......@@ -477,7 +477,7 @@ scikit-learn 中的文本提取器知道如何解码文本文件, 但只有当
> * 主题提取与非负矩阵分解和潜在Dirichlet分配 [Topic extraction with Non-negative Matrix Factorization and Latent Dirichlet Allocation](https://scikit-learn.org/stable/auto_examples/applications/plot_topics_extraction_with_nmf_lda.html#sphx-glr-auto-examples-applications-plot-topics-extraction-with-nmf-lda-py)
### 4.2.3.7\. 词语表示的限制
### 5.2.3.7\. 词语表示的限制
一组单词(什么是单词)无法捕获短语和多字表达,有效地忽略任何单词顺序依赖。另外,这个单词模型不包含潜在的拼写错误或词汇导出。
......@@ -528,7 +528,7 @@ True
为了处理自然语言理解的更广泛的任务,因此应考虑到句子和段落的地方结构。因此,许多这样的模型将被称为 “结构化输出” 问题,这些问题目前不在 scikit-learn 的范围之内。
### 4.2.3.8\. 用哈希技巧矢量化大文本语料库
### 5.2.3.8\. 用哈希技巧矢量化大文本语料库
上述向量化方案是简单的,但是它存在 **从字符串令牌到整数特征索引的内存映射**`vocabulary_` 属性),在处理 **大型数据集时会引起几个问题** :
......@@ -576,7 +576,7 @@ True
* 不能反转模型(没有inverse_transform方法),也无法访问原始的字符串表征,因为,进行mapping的哈希方法是单向本性。
* 没有提供了IDF权重,因为这需要在模型中引入状态。如果需要的话,可以在管道中添加 [`TfidfTransformer`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html#sklearn.feature_extraction.text.TfidfTransformer "sklearn.feature_extraction.text.TfidfTransformer")
### 4.2.3.9\. 使用 HashingVectorizer 执行外核缩放
### 5.2.3.9\. 使用 HashingVectorizer 执行外核缩放
使用 [`HashingVectorizer`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.HashingVectorizer.html#sklearn.feature_extraction.text.HashingVectorizer "sklearn.feature_extraction.text.HashingVectorizer") 的一个有趣的开发是执行外核 [out-of-core](https://en.wikipedia.org/wiki/Out-of-core_algorithm) 缩放的能力。 这意味着我们可以从无法放入电脑主内存的数据中进行学习。
......@@ -584,7 +584,7 @@ True
对于文本分类任务中的外核缩放的完整示例,请参阅文本文档的外核分类 [Out-of-core classification of text documents](https://scikit-learn.org/stable/auto_examples/applications/plot_out_of_core_classification.html#sphx-glr-auto-examples-applications-plot-out-of-core-classification-py).
### 4.2.3.10\. 自定义矢量化器类
### 5.2.3.10\. 自定义矢量化器类
通过将可调用传递给向量化程序构造函数可以定制行为:
......@@ -613,9 +613,9 @@ True
> * 如果文档由外部包进行预先标记,则将它们存储在文件(或字符串)中,令牌由空格分隔,并通过 `analyzer=str.split`
> * Fancy 令牌级分析,如词干,词法,复合分割,基于词性的过滤等不包括在 scikit-learn 代码库中,但可以通过定制分词器或分析器来添加。
>
>
> 这是一个 `CountVectorizer`, 使用 [NLTK](http://www.nltk.org) 的 tokenizer 和 lemmatizer:
>
>
> ```py
> >>> from nltk import word_tokenize # doctest: +SKIP
> >>> from nltk.stem import WordNetLemmatizer # doctest: +SKIP
......@@ -626,10 +626,10 @@ True
> ... return [self.wnl.lemmatize(t) for t in word_tokenize(doc)]
> ...
> >>> vect = CountVectorizer(tokenizer=LemmaTokenizer()) # doctest: +SKIP
>
>
> (请注意,这不会过滤标点符号。)
> 例如,以下例子将英国的一些拼写变成美国拼写::
>
>
> >>> import re
> >>> def to_british(tokens):
> ... for t in tokens:
......@@ -646,18 +646,18 @@ True
> ...
> >>> print(CustomVectorizer().build_analyzer()(u"color colour")) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
> [...'color', ...'color']
>
>
> 用于其他样式的预处理; 例子包括 stemming, lemmatization, 或 normalizing numerical tokens, 后者说明如下:
>
>
> * :ref:`sphx_glr_auto_examples_bicluster_plot_bicluster_newsgroups.py`
>
>
> ```
在处理不使用显式字分隔符(例如空格)的亚洲语言时,自定义向量化器也是有用的。
## 4.2.4\. 图像特征提取
## 5.2.4\. 图像特征提取
### 4.2.4.1\. 补丁提取
### 5.2.4.1\. 补丁提取
[`extract_patches_2d`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.image.extract_patches_2d.html#sklearn.feature_extraction.image.extract_patches_2d "sklearn.feature_extraction.image.extract_patches_2d") 函数从存储为二维数组的图像或沿着第三轴的颜色信息三维提取修补程序。 要从其所有补丁重建图像,请使用 [`reconstruct_from_patches_2d`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.image.reconstruct_from_patches_2d.html#sklearn.feature_extraction.image.reconstruct_from_patches_2d "sklearn.feature_extraction.image.reconstruct_from_patches_2d"). 例如让我们使用3个彩色通道(例如 RGB 格式)生成一个 4x4 像素的图像:
......@@ -709,7 +709,7 @@ array([[15, 18],
```
### 4.2.4.2\. 图像的连接图
### 5.2.4.2\. 图像的连接图
scikit-learn 中的几个估计可以使用特征或样本之间的连接信息。 例如,Ward聚类(层次聚类 [层次聚类](clustering.html#hierarchical-clustering) )可以聚集在一起,只有图像的相邻像素,从而形成连续的斑块:
......@@ -727,4 +727,4 @@ Note
* [A demo of structured Ward hierarchical clustering on a raccoon face image](https://scikit-learn.org/stable/auto_examples/cluster/plot_face_ward_segmentation.html#sphx-glr-auto-examples-cluster-plot-face-ward-segmentation-py)
* [Spectral clustering for image segmentation](https://scikit-learn.org/stable/auto_examples/cluster/plot_segmentation_toy.html#sphx-glr-auto-examples-cluster-plot-segmentation-toy-py)
* [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)
\ No newline at end of file
* [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)
# 4.3\. 预处理数据
# 5.3\. 预处理数据
校验者:
        [@if only](https://github.com/apachecn/scikit-learn-doc-zh)
......@@ -9,7 +9,7 @@
一般来说,机器学习算法受益于数据集的标准化。如果数据集中存在一些离群值,那么稳定的缩放或转换更合适。不同缩放、转换以及归一在一个包含边缘离群值的数据集中的表现在 [Compare the effect of different scalers on data with outliers](https://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html#sphx-glr-auto-examples-preprocessing-plot-all-scaling-py) 中有着重说明。
## 4.3.1\. 标准化,也称去均值和方差按比例缩放
## 5.3.1\. 标准化,也称去均值和方差按比例缩放
数据集的 **标准化** 对scikit-learn中实现的大多数机器学习算法来说是 **常见的要求** 。如果个别特征或多或少看起来不是很像标准正态分布(**具有零均值和单位方差**),那么它们的表现力可能会较差。
......@@ -76,7 +76,7 @@ array([[-2.44..., 1.22..., -0.26...]])
你也可以通过在构造函数 :class:StandardScaler 中传入参数 `with_mean=False` 或者``with_std=False` 来取消中心化或缩放操作。
### 4.3.1.1\. 将特征缩放至特定范围内
### 5.3.1.1\. 将特征缩放至特定范围内
一种标准化是将特征缩放到给定的最小值和最大值之间,通常在零和一之间,或者也可以将每个特征的最大绝对值转换至单位大小。可以分别使用 [`MinMaxScaler`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html#sklearn.preprocessing.MinMaxScaler "sklearn.preprocessing.MinMaxScaler") 和 [`MaxAbsScaler`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MaxAbsScaler.html#sklearn.preprocessing.MaxAbsScaler "sklearn.preprocessing.MaxAbsScaler") 实现。
......@@ -154,7 +154,7 @@ array([ 2., 1., 2.])
在 [`scale`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.scale.html#sklearn.preprocessing.scale "sklearn.preprocessing.scale") 模块中进一步提供了方便的功能。当你不想创建对象时,可以使用如 [`minmax_scale`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.minmax_scale.html#sklearn.preprocessing.minmax_scale "sklearn.preprocessing.minmax_scale") 以及 [`maxabs_scale`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.maxabs_scale.html#sklearn.preprocessing.maxabs_scale "sklearn.preprocessing.maxabs_scale") 。
### 4.3.1.2\. 缩放稀疏(矩阵)数据
### 5.3.1.2\. 缩放稀疏(矩阵)数据
中心化稀疏(矩阵)数据会破坏数据的稀疏结构,因此很少有一个比较明智的实现方式。但是缩放稀疏输入是有意义的,尤其是当几个特征在不同的量级范围时。
......@@ -164,7 +164,7 @@ array([ 2., 1., 2.])
最后,最后,如果已经中心化的数据并不是很大,使用 `toarray` 方法将输入的稀疏矩阵显式转换为数组是另一种选择。
### 4.3.1.3\. 缩放有离群值的数据
### 5.3.1.3\. 缩放有离群值的数据
如果你的数据包含许多异常值,使用均值和方差缩放可能并不是一个很好的选择。这种情况下,你可以使用 [`robust_scale`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.robust_scale.html#sklearn.preprocessing.robust_scale "sklearn.preprocessing.robust_scale") 以及 [`RobustScaler`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.RobustScaler.html#sklearn.preprocessing.RobustScaler "sklearn.preprocessing.RobustScaler") 作为替代品。它们对你的数据的中心和范围使用更有鲁棒性的估计。
......@@ -180,11 +180,11 @@ Scaling vs Whitening 有时候独立地中心化和缩放数据是不够的,
[`scale`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.scale.html#sklearn.preprocessing.scale "sklearn.preprocessing.scale") 以及 [`StandardScaler`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler "sklearn.preprocessing.StandardScaler") 可以直接处理一维数组。在回归中,缩放目标/相应变量时非常有用。
### 4.3.1.4\. 核矩阵的中心化
### 5.3.1.4\. 核矩阵的中心化
如果你有一个核矩阵 ![K](img/e279b8169ddd6581c5606c868ba52fae.jpg) ,它计算由函数 ![phi](img/a8e210a94f6eac6c32bc219dbc049288.jpg) 定义的特征空间的点积,那么一个 [`KernelCenterer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.KernelCenterer.html#sklearn.preprocessing.KernelCenterer "sklearn.preprocessing.KernelCenterer") 类能够转化这个核矩阵,通过移除特征空间的平均值,使它包含由函数 ![phi](img/a8e210a94f6eac6c32bc219dbc049288.jpg) 定义的内部产物。
## 4.3.2\. 非线性转换
## 5.3.2\. 非线性转换
类似于缩放, [`QuantileTransformer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.QuantileTransformer.html#sklearn.preprocessing.QuantileTransformer "sklearn.preprocessing.QuantileTransformer") 类将每个特征缩放在同样的范围或分布情况下。但是,通过执行一个秩转换能够使异常的分布平滑化,并且能够比缩放更少地受到离群值的影响。但是它的确使特征间及特征内的关联和距离失真了。
......@@ -199,7 +199,7 @@ Scaling vs Whitening 有时候独立地中心化和缩放数据是不够的,
>>> quantile_transformer = preprocessing.QuantileTransformer(random_state=0)
>>> X_train_trans = quantile_transformer.fit_transform(X_train)
>>> X_test_trans = quantile_transformer.transform(X_test)
>>> np.percentile(X_train[:, 0], [0, 25, 50, 75, 100])
>>> np.percentile(X_train[:, 0], [0, 25, 50, 75, 100])
array([ 4.3, 5.1, 5.8, 6.5, 7.9])
```
......@@ -208,7 +208,7 @@ array([ 4.3, 5.1, 5.8, 6.5, 7.9])
```py
>>> np.percentile(X_train_trans[:, 0], [0, 25, 50, 75, 100])
...
...
array([ 0.00... , 0.24..., 0.49..., 0.73..., 0.99... ])
```
......@@ -217,10 +217,10 @@ array([ 0.00... , 0.24..., 0.49..., 0.73..., 0.99... ])
```py
>>> np.percentile(X_test[:, 0], [0, 25, 50, 75, 100])
...
...
array([ 4.4 , 5.125, 5.75 , 6.175, 7.3 ])
>>> np.percentile(X_test_trans[:, 0], [0, 25, 50, 75, 100])
...
...
array([ 0.01..., 0.25..., 0.46..., 0.60... , 0.94...])
```
......@@ -231,7 +231,7 @@ array([ 0.01..., 0.25..., 0.46..., 0.60... , 0.94...])
>>> quantile_transformer = preprocessing.QuantileTransformer(
... output_distribution='normal', random_state=0)
>>> X_trans = quantile_transformer.fit_transform(X)
>>> quantile_transformer.quantiles_
>>> quantile_transformer.quantiles_
array([[ 4.3..., 2..., 1..., 0.1...],
[ 4.31..., 2.02..., 1.01..., 0.1...],
[ 4.32..., 2.05..., 1.02..., 0.1...],
......@@ -244,7 +244,7 @@ array([[ 4.3..., 2..., 1..., 0.1...],
这样,输入的中值称为输出的平均值,并且以0为中心。正常输出被剪切,使得输入的最小和最大值分别对应于1e-7和1-1e-7分位数——在变换下不会变得无限大。
## 4.3.3\. 归一化
## 5.3.3\. 归一化
**归一化** 是 **缩放单个样本以具有单位范数** 的过程。如果你计划使用二次形式(如点积或任何其他核函数)来量化任何样本间的相似度,则此过程将非常有用。
......@@ -295,9 +295,9 @@ array([[-0.70..., 0.70..., 0\. ...]])
对于稀疏输入,在被提交给高效Cython例程前,数据被 **转化为压缩的稀疏行形式** (参见 `scipy.sparse.csr_matrix` )。为了避免不必要的内存复制,推荐在上游选择CSR表示。
## 4.3.4\. 二值化
## 5.3.4\. 二值化
### 4.3.4.1\. 特征二值化
### 5.3.4.1\. 特征二值化
**特征二值化** 是 **将数值特征用阈值过滤得到布尔值** 的过程。这对于下游的概率型模型是有用的,它们假设输入数据是多值 [伯努利分布(Bernoulli distribution)](https://en.wikipedia.org/wiki/Bernoulli_distribution) 。例如这个例子 [`sklearn.neural_network.BernoulliRBM`](https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.BernoulliRBM.html#sklearn.neural_network.BernoulliRBM "sklearn.neural_network.BernoulliRBM") 。
......@@ -340,7 +340,7 @@ array([[ 0., 0., 1.],
对于稀疏输入,数据被 **转化为压缩的稀疏行形式** (参见 `scipy.sparse.csr_matrix` )。为了避免不必要的内存复制,推荐在上游选择CSR表示。
## 4.3.5\. 分类特征编码
## 5.3.5\. 分类特征编码
在机器学习中,特征经常不是数值型的而是分类型的。举个例子,一个人可能有 `["male", "female"]` , `["from Europe", "from US", "from Asia"]` , `["uses Firefox", "uses Chrome", "uses Safari", "uses Internet Explorer"]` 等分类的特征。这些特征能够被有效地编码成整数,比如 `["male", "from US", "uses Internet Explorer"]` 可以被表示为 `[0, 1, 3]` , `["female", "from Asia", "uses Chrome"]` 表示为 `[1, 2, 1]` 。
......@@ -378,7 +378,7 @@ array([[ 0., 1., 1., 0., 0., 1., 0., 0., 0.]])
参见 [从字典类型加载特征](feature_extraction.html#dict-feature-extraction) ,它对于分类特征代表一个dict,而不是整数。
## 4.3.6\. 缺失值插补
## 5.3.6\. 缺失值插补
因为各种各样的原因,真实世界中的许多数据集都包含缺失数据,这类数据经常被编码成空格、NaNs,或者是其他的占位符。但是这样的数据集并不能scikit-learn学习算法兼容,因为大多的学习算法都默认假设数组中的元素都是数值,因而所有的元素都有自己的意义。 使用不完整的数据集的一个基本策略就是舍弃掉整行或整列包含缺失值的数据。但是这样就付出了舍弃可能有价值数据(即使是不完整的 )的代价。 处理缺失数值的一个更好的策略就是从已有的数据推断出缺失的数值。
......@@ -420,7 +420,7 @@ Imputer(axis=0, copy=True, missing_values=0, strategy='mean', verbose=0)
[`Imputer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Imputer.html#sklearn.preprocessing.Imputer "sklearn.preprocessing.Imputer") 可以在 Pipeline 中用作构建支持插补的合成模型。参见 [Imputing missing values before building an estimator](https://scikit-learn.org/stable/auto_examples/plot_missing_values.html#sphx-glr-auto-examples-plot-missing-values-py) 。
## 4.3.7\. 生成多项式特征
## 5.3.7\. 生成多项式特征
在机器学习中,通过增加一些输入数据的非线性特征来增加模型的复杂度通常是有效的。一个简单通用的办法是使用多项式特征,这可以获得特征的更高维度和互相间关系的项。这在 [`PolynomialFeatures`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html#sklearn.preprocessing.PolynomialFeatures "sklearn.preprocessing.PolynomialFeatures") 中实现:
......@@ -464,7 +464,7 @@ X的特征已经从 ![(X_1, X_2, X_3)](img/300d1995dc6050bbfd575b2c14ec81ae.jpg)
创建并使用多项式特征的岭回归实例请见 [Polynomial interpolation](https://scikit-learn.org/stable/auto_examples/linear_model/plot_polynomial_interpolation.html#sphx-glr-auto-examples-linear-model-plot-polynomial-interpolation-py) 。
## 4.3.8\. 自定义转换器
## 5.3.8\. 自定义转换器
在机器学习中,想要将一个已有的 Python 函数转化为一个转换器来协助数据清理或处理。可以使用 [`FunctionTransformer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.FunctionTransformer.html#sklearn.preprocessing.FunctionTransformer "sklearn.preprocessing.FunctionTransformer") 从任意函数中实现一个转换器。例如,在一个管道中构建一个实现日志转换的转化器,这样做:
......@@ -479,4 +479,4 @@ array([[ 0\. , 0.69314718],
```
使用一个 [`FunctionTransformer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.FunctionTransformer.html#sklearn.preprocessing.FunctionTransformer "sklearn.preprocessing.FunctionTransformer") 类来做定制化特征选择的例子,请见 [Using FunctionTransformer to select columns](https://scikit-learn.org/stable/auto_examples/preprocessing/plot_function_transformer.html#sphx-glr-auto-examples-preprocessing-plot-function-transformer-py)
\ No newline at end of file
使用一个 [`FunctionTransformer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.FunctionTransformer.html#sklearn.preprocessing.FunctionTransformer "sklearn.preprocessing.FunctionTransformer") 类来做定制化特征选择的例子,请见 [Using FunctionTransformer to select columns](https://scikit-learn.org/stable/auto_examples/preprocessing/plot_function_transformer.html#sphx-glr-auto-examples-preprocessing-plot-function-transformer-py)
# 4.4\. 无监督降维
# 5.4\. 无监督降维
校验者:
        [@程威](https://github.com/apachecn/scikit-learn-doc-zh)
......@@ -7,7 +7,7 @@
如果你的特征数量很多, 在监督步骤之前, 可以通过无监督的步骤来减少特征. 很多的 [无监督学习](../unsupervised_learning.html#unsupervised-learning) 方法实现了一个名为 `transform` 的方法, 它可以用来降低维度. 下面我们将讨论大量使用这种模式的两个具体示例.
## 4.4.1\. PCA: 主成份分析
## 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).
......@@ -17,7 +17,7 @@
| ref: | ‘sphx_glr_auto_examples_applications_plot_face_recognition.py’ |
| --- | --- |
## 4.4.2\. 随机投影
## 5.4.2\. 随机投影
模块: `random_projection` 提供了几种用于通过随机投影减少数据的工具. 请参阅文档的相关部分: [随机投影](random_projection.html#random-projection).
......@@ -25,7 +25,7 @@
* [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)
## 4.4.3\. 特征聚集
## 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) 将行为类似的特征分组在一起.
......@@ -36,4 +36,4 @@
**特征缩放**
请注意,如果功能具有明显不同的缩放或统计属性,则 [`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") 可以在这些 设置中使用.
\ No newline at end of file
请注意,如果功能具有明显不同的缩放或统计属性,则 [`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") 可以在这些 设置中使用.
# 4.5\. 随机投影
# 5.5\. 随机投影
校验者:
        [@FontTian](https://github.com/FontTian)
......@@ -15,7 +15,7 @@
* 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.
## 4.5.1\. Johnson-Lindenstrauss 辅助定理
## 5.5.1\. Johnson-Lindenstrauss 辅助定理
支撑随机投影效率的主要理论成果是`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)>`_:
......@@ -44,7 +44,7 @@ array([ 7894, 9868, 11841])`
* 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)
## 4.5.2\. 高斯随机投影
## 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}})`降低维度。
......@@ -61,7 +61,7 @@ The [`sklearn.random_projection.GaussianRandomProjection`](https://scikit-learn.
```
## 4.5.3\. 稀疏随机矩阵
## 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") 使用稀疏随机矩阵,通过投影原始输入空间来降低维度。
......@@ -99,4 +99,4 @@ The [`sklearn.random_projection.GaussianRandomProjection`](https://scikit-learn.
参考:
* 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.
\ No newline at end of file
* 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.
# 4.6\. 内核近似
# 5.6\. 内核近似
校验者:
        [@FontTian](https://github.com/FontTian)
......@@ -16,11 +16,11 @@ See also
[多项式回归:用基函数展开线性模型](linear_model.html#polynomial-regression) 用于精确的多项式变换。
## 4.6.1\. 内核近似的 Nystroem 方法
## 5.6.1\. 内核近似的 Nystroem 方法
[`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` 给出.
## 4.6.2\. 径向基函数内核
## 5.6.2\. 径向基函数内核
[`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 )之前,可以使用此转换来明确建模内核映射:
......@@ -57,7 +57,7 @@ SGDClassifier(alpha=0.0001, average=False, class_weight=None, epsilon=0.1,
* [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)
## 4.6.3\. 加性卡方核
## 5.6.3\. 加性卡方核
Additive Chi Squared Kernel (加性卡方核)是直方图的核心,通常用于计算机视觉。
......@@ -71,7 +71,7 @@ Additive Chi Squared Kernel (加性卡方核)是直方图的核心,通常用
[`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") 的合并.
## 4.6.4\. Skewed Chi Squared Kernel (偏斜卡方核?暂译)
## 5.6.4\. Skewed Chi Squared Kernel (偏斜卡方核?暂译)
skewed chi squared kernel 给出下面公式
......@@ -81,7 +81,7 @@ skewed chi squared kernel 给出下面公式
[`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).
## 4.6.5\. 数学方面的细节
## 5.6.5\. 数学方面的细节
核技巧 像支持向量机,或者 核化 PCA 依赖于 再生核希尔伯特空间(RKHS) 对于任何 核函数 ![k](img/f93871977da52a6d11045d57c3e18728.jpg) (叫做 Mercer kernel),保证了 ![\phi](img/ff5e98366afa13070d3b410c55a80db1.jpg) 进入 希尔伯特空间 ![\mathcal{H}](img/433fedd575581cddbd612624b65e5dac.jpg) 的映射,例如:
......@@ -103,4 +103,4 @@ kernel 方法的一个缺点是,在优化过程中有可能存储大量的 ker
| [[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 |
\ No newline at end of file
| [[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 |
# 4.7\. 成对的矩阵, 类别和核函数
# 5.7\. 成对的矩阵, 类别和核函数
校验者:
        [@FontTian](https://github.com/FontTian)
......@@ -24,7 +24,7 @@ The [`sklearn.metrics.pairwise`](classes.html#module-sklearn.metrics.pairwise "s
> 1. `S = np.exp(-D * gamma)`, 其中 `gamma` 的一种选择是 `1 / num_features`
> 2. `S = 1. / (D / np.max(D))`
## 4.7.1\. 余弦相似度
## 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) 定义为:
......@@ -38,13 +38,13 @@ 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)
## 4.7.2\. 线性核函数
## 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)
## 4.7.3\. 多项式核函数
## 5.7.3\. 多项式核函数
```py
函数 计算两个向量的d次方的多项式核函数. 多项式核函数代表着两个向量之间的相似度.
......@@ -63,7 +63,7 @@ References:
如果 ![c_0 = 0](img/c95237387255f824359f6c772cbb1df0.jpg) 那么核函数就被定义为同质化的.
## 4.7.4\. Sigmoid 核函数
## 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型核函数定义为:
......@@ -75,7 +75,7 @@ where:
> * ![\gamma](img/6552bde3d3999c1a9728016416932af7.jpg) 是斜度
> * ![c_0](img/64ccaf1b6c08784a30158f809c081987.jpg) 是截距
## 4.7.5\. RBF 核函数
## 5.7.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) 。 其定义为:
......@@ -83,7 +83,7 @@ where:
其中 `x``y` 是输入向量. 如果 ![\gamma = \sigma^{-2}](img/11336a74b43f75a360b60ce81f9cbdc0.jpg) 核函数就变成方差为 ![\sigma^2](img/d69db8c22e9315a6fb454b276d5ce534.jpg) 的高斯核函数.
## 4.7.6\. 拉普拉斯核函数
## 5.7.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") 是一种径向基函数核的变体,定义为:
......@@ -93,7 +93,7 @@ where:
已被证明在机器学习中运用到无噪声数据中是有用的. 可见例如 [Machine learning for quantum mechanics in a nutshell](http://onlinelibrary.wiley.com/doi/10.1002/qua.24954/abstract/).
## 4.7.7\. 卡方核函数
## 5.7.7\. 卡方核函数
```py
在计算机视觉应用中训练非线性支持向量机时卡方核函数是一种非常流行的选择.
......@@ -143,4 +143,4 @@ array([0, 1, 0, 1])
参考:
* 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)
\ No newline at end of file
* 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)
# 4.8\. 预测目标 (`y`) 的转换
# 5.8\. 预测目标 (`y`) 的转换
校验者:
        [@FontTian](https://github.com/FontTian)
......@@ -6,7 +6,7 @@
翻译者:
        [@程威](https://github.com/apachecn/scikit-learn-doc-zh)
## 4.8.1\. 标签二值化
## 5.8.1\. 标签二值化
[`LabelBinarizer`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html#sklearn.preprocessing.LabelBinarizer "sklearn.preprocessing.LabelBinarizer") 是一个用来从多类别列表创建标签矩阵的工具类:
......@@ -35,7 +35,7 @@ array([1, 2, 3])
```
## 4.8.2\. 标签编码
## 5.8.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") 可以如下使用:
......@@ -66,4 +66,4 @@ array([2, 2, 1])
>>> list(le.inverse_transform([2, 2, 1]))
['tokyo', 'tokyo', 'paris']
```
\ No newline at end of file
```
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册