機器學習筆記 多項式回歸

2022-01-11 13:27:29 字數 2933 閱讀 5623

比如你的資料分布,是符合y=0.5$x^2$ + x + 2的.

那你用y=ax+b去擬合,無論如何都沒法取的很好的效果.

通過上面的分析,我們可以看出,我們想做的事情是對樣本做公升維(即增加樣本的特徵數目),sklean中完成這一功能的類叫做polynomialfeatures.

classsklearn.preprocessing.polynomialfeatures(degree=2, interaction_only=false, include_bias=true

)degree: integer

the degree of the polynomial features. default = 2.

interaction_only: boolean, default = false

if true, only interaction features are produced: features that are products of at mostdegreedistinct input features (so notx[1] ** 2

,x[0] * x[2] ** 3

, etc.).

include_bias: boolean

if true (default), then include a bias column, the feature in which all polynomial powers are zero (i.e. a column of ones - acts as an intercept term in a linear model).

假設你的樣本,原本有兩個特徵[a,b],那麼當你進行一次degree=2的公升維之後,你將得到5個特徵[1,a,b,$a^2$,ab,$b^2$],其中1又可以看做是$a^0或者b^0$。

關於degree的理解你可以參考一下下面這個例子.from sklearn.preprocessing import

polynomialfeatures

x=pd.dataframe()

print

(x)poly2 = polynomialfeatures(degree=2)

poly2.fit_transform(x)

>>> array([[ 1., 2., 3., 4., 4., 6., 8., 9., 12., 16.]])

poly3 = polynomialfeatures(degree=3)

poly3.fit_transform(x)

>>> array([[ 1., 2., 3., 4., 4., 6., 8., 9., 12., 16., 8., 12., 16.,

18., 24., 32., 27., 36., 48., 64.]])

poly4 = polynomialfeatures(degree=3,interaction_only=true)

poly4.fit_transform(x)

>>> array([[ 1.,  2.,  3.,  4.,  6.,  8., 12., 24.]])
我們的樣本有3個特徵,值分別為2,3,4,degree=2時,可能的取值有$2^0$,$3^0$,$4^0$(均為1),$2^1,2^2,3^1,3^2,4^1,4^2$,$2*3,2*4,3*4$共10個值.

degree為3時,又新增了$2^3,3^3,4^3$,$2^2*3,2^2*4,3^2*2,3^2*4,4^2*2,4^2*3,2*3*4$共10個.總計20個.

interaction_only=true時,表示新增的特徵存在互動性,不存在自己*自己,比如[2,3,4]的互動式輸出是[2*3,2*4,3*4,2*3*4].

從上面的分析可以看出來,隨著degree的增加,polynomialfeatures新生成的特徵數目是呈指數級別增加的.這將帶來模型訓練速度的嚴重下降和模型的過擬合,所以實際上一般很少用多項式回歸.

來個具體的例子

import

numpy as np

import

matplotlib.pyplot as plt

from sklearn.preprocessing import

polynomialfeatures

x = np.random.uniform(-3, 3, size=100)

x = x.reshape(-1, 1)

y = 0.5 * x**2 + x + 2 + np.random.normal(0, 1, 100)

#公升維,為樣本生成新的特徵

poly = polynomialfeatures(degree=2)

poly.fit(x)

x2 =poly.transform(x)

#對新樣本做訓練

python 機器學習多項式回歸

現實世界的曲線關係都是通過增加多項式實現的,現在解決多項式回歸問題 住房 樣本 樣本影象 import matplotlib.font manager as fm import matplotlib.pyplot as plt myfont fm.fontproperties fname c win...

多項式回歸

import numpy as np import matplotlib.pyplot as plt x np.random.uniform 3,3,size 100 x x.reshape 1,1 y 0.5 x 2 x 2 np.random.normal 0,1,100 plt.scatter...

多項式回歸

多項式回歸 import torch import numpy defmake features x 獲取 x,x 2,x 3 的矩陣 x x.unsqueeze 1 將一維資料變為 n,1 二維矩陣形式 return torch.cat x i for i in range 1 4 1 按列拼接 ...