python中使用4次多項式迴歸模型在訓練樣本中進行擬合

X_train = [[6],[8],[10],[14],[18]]
y_train = [[7],[9],[13],[17.5],[18]]

from sklearn.linear_model import LinearRegression

regressor = LinearRegression()

regressor.fit(X_train,y_train)

import numpy as np

xx = np.linspace(0,26,100)
xx = xx.reshape(xx.shape[0],1)

yy = regressor.predict(xx)

from sklearn.preprocessing import PolynomialFeatures
poly2 = PolynomialFeatures(degree=2)
X_train_poly2 = poly2.fit_transform(X_train)


regressor_poly2 = LinearRegression()

regressor_poly2.fit(X_train_poly2,y_train)

xx_poly2 = poly2.transform(xx)

yy_poly2 = regressor_poly2.predict(xx_poly2)

import matplotlib.pyplot as plt
plt.scatter(X_train,y_train)

plt1,=plt.plot(xx,yy,label="Degree=1")

plt2,=plt.plot(xx,yy_poly2,label="Degree=2")



poly4 = PolynomialFeatures(degree=4)
X_train_poly4 = poly4.fit_transform(X_train)


regressor_poly4 = LinearRegression()

regressor_poly4.fit(X_train_poly4,y_train)

xx_poly4 = poly4.transform(xx)

yy_poly4 = regressor_poly4.predict(xx_poly4)

import matplotlib.pyplot as plt
plt.scatter(X_train,y_train)

plt1,=plt.plot(xx,yy,label="Degree=1")

plt2,=plt.plot(xx,yy_poly2,label="Degree=2")

plt4,=plt.plot(xx,yy_poly4,label="Degree=4")

plt.axis([0,25,0,25])
plt.xlabel('Diameter of pizza')
輸出結果如下:
the R-squared value of Linear Regressor(Degree=2)  performing on the training data is 1.0

plt.ylabel('price of pizza')plt.legend(handles=[plt1,plt2,plt4])plt.show()print('the R-squared value of Linear Regressor(Degree=2) performing on the training data is',regressor_poly4.score(X_train_poly4,y_train))
擬合曲線如圖所示:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章