python中使用4次多项式回归模型在训练样本中进行拟合

本文通过使用线性回归和多项式回归模型,基于披萨直径预测其价格。展示了一维和二维特征下的拟合效果,并比较了不同阶数的多项式回归模型的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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))
拟合曲线如图所示:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值