Python 確定多項式擬合 回歸的階數

2022-02-14 09:43:14 字數 2647 閱讀 4138

通過 1至10 階來擬合對比 均方誤差及r評分,可以確定最優的「最大階數」。

import

numpy as np

import

matplotlib.pyplot as plt

from sklearn.preprocessing import

polynomialfeatures

from sklearn.linear_model import

linearregression,perceptron

from sklearn.metrics import

mean_squared_error,r2_score

from sklearn.model_selection import

train_test_split

x = np.array([-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10]).reshape(-1, 1)

y = np.array(2*(x**4) + x**2 + 9*x + 2)

#y = np.array([300,500,0,-10,0,20,200,300,1000,800,4000,5000,10000,9000,22000]).reshape(-1, 1)

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)

rmses =

degrees = np.arange(1, 10)

min_rmse, min_deg,score = 1e10, 0 ,0

for deg in

degrees:

#生成多項式特徵集(如根據degree=3 ,生成 [[x,x**2,x**3]] )

poly = polynomialfeatures(degree=deg, include_bias=false)

x_train_poly =poly.fit_transform(x_train)

#多項式擬合

poly_reg =linearregression()

poly_reg.fit(x_train_poly, y_train)

#print(poly_reg.coef_,poly_reg.intercept_) #係數及常數

#測試集比較

x_test_poly =poly.fit_transform(x_test)

y_test_pred =poly_reg.predict(x_test_poly)

#mean_squared_error(y_true, y_pred) #均方誤差回歸損失,越小越好。

poly_rmse =np.sqrt(mean_squared_error(y_test, y_test_pred))

#r2 範圍[0,1],r2越接近1擬合越好。

r2score =r2_score(y_test, y_test_pred)

#degree交叉驗證

因為因變數 y = 2*(x**4) + x**2 + 9*x + 2 ,自變數和因變數是完整的公式,看圖很明顯,degree >=4 的都符合,擬合函式都正確。(rmse 最小,r平方非負且接近於1,則模型最好)

如果將 y 值改為如下:

degree=3 是最好的,且 r 平方也最接近於1(注意:如果 r 平方為負數,則不準確,需再次測試。因樣本資料較少,可能也會判斷錯誤)。

多項式擬合缺點 多項式擬合

在網上看別人的心得 一 最小二乘法的基本原理 從整體上考慮近似函式同所給資料點 i 0,1,m 誤差 i 0,1,m 的大小,常用的方法有以下三種 一是誤差 i 0,1,m 絕對值的最大值,即誤差 向量的 範數 二是誤差絕對值的和,即誤差向量r的1 範數 三是誤差平方和的算術平方根,即誤差向量r的2...

多項式擬合

class1.cs 擬合類 using system using system.collections.generic using system.text namespace 最小二乘法擬合多項式 guass i,j sumarr arrx,i,arry,1,length return comput...

多項式擬合

多項式擬合 多項式的一般形式 y p x n p x p x p x p 多項式擬合的目的是為了找到一組p0 pn,使得擬合方程盡可能的與實際樣本資料相符合。假設擬合得到的多項式如下 f x p x n p x p x p x p 則擬合函式與真實結果的差方如下 loss y 1 f x 1 2 y...