- Scikit Learn 教程
- Scikit Learn - 首頁
- Scikit Learn - 簡介
- Scikit Learn - 建模過程
- Scikit Learn - 資料表示
- Scikit Learn - 估計器 API
- Scikit Learn - 約定
- Scikit Learn - 線性建模
- Scikit Learn - 擴充套件線性建模
- 隨機梯度下降
- Scikit Learn - 支援向量機
- Scikit Learn - 異常檢測
- Scikit Learn - K 近鄰
- Scikit Learn - KNN 學習
- 樸素貝葉斯分類
- Scikit Learn - 決策樹
- 隨機決策樹
- Scikit Learn - 整合方法
- Scikit Learn - 聚類方法
- 聚類效能評估
- 使用 PCA 進行降維
- Scikit Learn 有用資源
- Scikit Learn - 快速指南
- Scikit Learn - 有用資源
- Scikit Learn - 討論
Scikit Learn - 擴充套件線性建模
本章重點介紹 Sklearn 中的多項式特徵和管道工具。
多項式特徵簡介
在資料的非線性函式上訓練的線性模型通常保持線性方法的快速效能。它還允許它們擬合更廣泛的資料範圍。這就是機器學習中使用這種在非線性函式上訓練的線性模型的原因。
一個這樣的例子是,可以透過從係數構造多項式特徵來擴充套件簡單的線性迴歸。
在數學上,假設我們有標準線性迴歸模型,那麼對於二維資料,它將如下所示:
$$Y=W_{0}+W_{1}X_{1}+W_{2}X_{2}$$現在,我們可以將特徵組合成二階多項式,我們的模型將如下所示:
$$Y=W_{0}+W_{1}X_{1}+W_{2}X_{2}+W_{3}X_{1}X_{2}+W_{4}X_1^2+W_{5}X_2^2$$以上仍然是線性模型。在這裡,我們看到結果的多項式迴歸屬於線性模型的同一類,並且可以以類似的方式求解。
為此,scikit-learn 提供了一個名為PolynomialFeatures的模組。此模組將輸入資料矩陣轉換為給定度數的新資料矩陣。
引數
以下表格包含PolynomialFeatures模組使用的引數
| 序號 | 引數及描述 |
|---|---|
| 1 |
degree − 整數,預設 = 2 它表示多項式特徵的度數。 |
| 2 |
interaction_only − 布林值,預設 = false 預設情況下,它是 false,但如果設定為 true,則會生成大多數度數不同的輸入特徵的乘積的特徵。這些特徵稱為互動特徵。 |
| 3 |
include_bias − 布林值,預設 = true 它包括一個偏差列,即所有多項式冪都為零的特徵。 |
| 4 |
order − str in {‘C’, ‘F’},預設 = ‘C’ 此引數表示密集情況下的輸出陣列的順序。’F’ 順序意味著計算速度更快,但另一方面,它可能會減慢後續估計器的速度。 |
屬性
以下表格包含PolynomialFeatures模組使用的屬性
| 序號 | 屬性及描述 |
|---|---|
| 1 |
powers_ − 陣列,形狀 (n_output_features, n_input_features) 它顯示 powers_ [i,j] 是第 i 個輸出中第 j 個輸入的指數。 |
| 2 |
n_input_features _ − int 顧名思義,它給出輸入特徵的總數。 |
| 3 |
n_output_features _ − int 顧名思義,它給出多項式輸出特徵的總數。 |
實現示例
以下 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)
輸出
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.]
]
)
使用管道工具簡化
上述預處理方式,即將輸入資料矩陣轉換為給定度數的新資料矩陣,可以使用Pipeline工具簡化,這些工具基本上用於將多個估計器連結到一個。
示例
以下 Python 指令碼使用 Scikit-learn 的 Pipeline 工具來簡化預處理(將擬合到 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_
輸出
array([ 3., -2., 1., -1.])
上述輸出表明,在多項式特徵上訓練的線性模型能夠恢復準確的輸入多項式係數。