Scikit Learn 简明教程

Scikit Learn - Extended Linear Modeling

本章重点介绍了 Sklearn 中的多项式特征和管道工具。

Introduction to Polynomial Features

针对数据非线性函数训练的线性模型,通常保持线性方法的快速性能。它还允许它们拟合更广泛的数据范围。这就是机器学习中使用针对非线性函数训练的这种线性模型的原因。

一个这样的示例是简单的线性回归可以通过从系数构造多项式特征来扩展。

在数学上,假设我们有标准线性回归模型,那么对于 2-D 数据而言,它会如下所示:

现在,我们可以将特征组合成二次多项式,我们的模型将如下所示:

以上仍然是线性模型。在这里,我们看到生成的多项式回归属于相同的线性模型类别,并且可以类似地求解。

为此,scikit-learn 提供了一个名为 PolynomialFeatures 的模块。此模块将输入数据矩阵转换为给定度的新数据矩阵。

Parameters

下表包含 PolynomialFeatures 模块使用的参数

Sr.No

Parameter & Description

1

degree − 整数,默认值 = 2它表示多项式特征的度。

2

interaction_only − 布尔值,默认值为 false默认情况下,它为 false,但如果设置为 true,则会生成大多数度不同输入特征的乘积的特征。此类特征称为交互特征。

3

include_bias - 布尔值,默认值为 true 它包括偏差列,即所有多项式幂为零的特征。

4

order - str 在 {‘C’, ‘F’} 中,默认值为 ‘C’ 此参数表示稠密情况下的输出数组的顺序。‘F’ 顺序表示计算速度更快,但另一方面,它可能会减慢后续估计器的速度。

Attributes

下表包含 PolynomialFeatures 模块使用的属性

Sr.No

Attributes & Description

1

powers_ - 数组,形状 (n_output_features, n_input_features) 它显示 powers_ [i,j] 是第 i 个输出中第 j 个输入的指数。

2

n_input_features _ - 整数 名称暗示了这一点,它给出了输入特征的总数。

3

n_output_features _ - 整数 名称暗示了这一点,它给出了多项式输出特征的总数。

Implementation Example

以下 Python 脚本使用 PolynomialFeatures 转换器将数组从 8 转换为形状 (4,2) −

from sklearn.preprocessing import PolynomialFeatures
import numpy as np
Y = np.arange(8).reshape(4, 2)
poly = PolynomialFeatures(degree=2)
poly.fit_transform(Y)

Output

array(
   [
      [ 1., 0., 1., 0., 0., 1.],
      [ 1., 2., 3., 4., 6., 9.],
      [ 1., 4., 5., 16., 20., 25.],
      [ 1., 6., 7., 36., 42., 49.]
   ]
)

Streamlining using Pipeline tools

上述预处理(即将输入数据矩阵转换为给定次数的新数据矩阵)可以用 Pipeline 工具简化,这些工具主要用于将多个估计器链接为一个。

Example

以下使用 Scikit-learn 的管道工具的 Python 脚本简化了预处理(将拟合到 3 阶多项式数据)。

#First, import the necessary packages.
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
import numpy as np

#Next, create an object of Pipeline tool
Stream_model = Pipeline([('poly', PolynomialFeatures(degree=3)), ('linear', LinearRegression(fit_intercept=False))])

#Provide the size of array and order of polynomial data to fit the model.
x = np.arange(5)
y = 3 - 2 * x + x ** 2 - x ** 3
Stream_model = model.fit(x[:, np.newaxis], y)

#Calculate the input polynomial coefficients.
Stream_model.named_steps['linear'].coef_

Output

array([ 3., -2., 1., -1.])

以上输出结果表明,在多项式特征上训练的线性模型能够恢复确切的输入多项式系数。