国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2020-02-16 00:24:23
字體:
來源:轉載
供稿:網友

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

import numpy as npimport matplotlib.pyplot as pltfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.linear_model import LinearRegression,Perceptronfrom sklearn.metrics import mean_squared_error,r2_scorefrom 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))	rmses.append(poly_rmse)	# r2 范圍[0,1],R2越接近1擬合越好。	r2score = r2_score(y_test, y_test_pred)		# degree交叉驗證	if min_rmse > poly_rmse:		min_rmse = poly_rmse		min_deg = deg		score = r2score	print('degree = %s, RMSE = %.2f ,r2_score = %.2f' % (deg, poly_rmse,r2score))		fig = plt.figure()ax = fig.add_subplot(111)ax.plot(degrees, rmses)ax.set_yscale('log')ax.set_xlabel('Degree')ax.set_ylabel('RMSE')ax.set_title('Best degree = %s, RMSE = %.2f, r2_score = %.2f' %(min_deg, min_rmse,score)) plt.show()

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

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

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

如果將 Y 值改為如下:

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

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

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

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

以上這篇Python 確定多項式擬合/回歸的階數實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 贡嘎县| 张家口市| 佛冈县| 盐池县| 九龙城区| 高安市| 南溪县| 岑溪市| 比如县| 微博| 区。| 高阳县| 三明市| 开封市| 松桃| 扶余县| 建昌县| 沛县| 兴业县| 建平县| 新田县| 连南| 平度市| 鹤庆县| 苏尼特左旗| 洛扎县| 梓潼县| 休宁县| 延吉市| 安宁市| 贺州市| 普宁市| 通许县| 阿坝县| 独山县| 淮滨县| 和政县| 屏边| 二手房| 永城市| 白银市|