x:0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6 3.8 4 4.2 4.4 4.6 4.8 5 5 .2 5.4 5.6 5.8 6 6.2 6.4 6.6 6.8 7 7.2 7.4 7.6 7.8 8 8.2 8.4 8.6 8.8 9 9.2 9.4 9.6 9.8 10 y:1 0.93 1 1.16 1.56 1.64 1.8 2.17 2.19 2.32 2.63 2.46 2.76 2.88 2.83 2.96 2.85 2.91 3.12 3.23 3.5 3.12 3.25 3.23 3.02 3.22 3.06 3.22 3.5 3.2 3.45 3.35 3.51 3.09 3.31 3.18 3.7 3.44 3.51 将以上数据进行拟合
时间: 2024-01-04 11:02:41 浏览: 325
对于给定的数据,我们可以使用多项式回归进行拟合。具体步骤如下:
1. 导入需要的库和模块
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
```
2. 准备数据
```python
x = np.array([0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6, 2.8, 3, 3.2, 3.4, 3.6, 3.8, 4, 4.2, 4.4, 4.6, 4.8, 5, 5 .2, 5.4, 5.6, 5.8, 6, 6.2, 6.4, 6.6, 6.8, 7, 7.2, 7.4, 7.6, 7.8, 8, 8.2, 8.4, 8.6, 8.8, 9, 9.2, 9.4, 9.6, 9.8, 10]).reshape(-1, 1)
y = np.array([1, 0.93, 1, 1.16, 1.56, 1.64, 1.8, 2.17, 2.19, 2.32, 2.63, 2.46, 2.76, 2.88, 2.83, 2.96, 2.85, 2.91, 3.12, 3.23, 3.5, 3.12, 3.25, 3.23, 3.02, 3.22, 3.06, 3.22, 3.5, 3.2, 3.45, 3.35, 3.51, 3.09, 3.31, 3.18, 3.7, 3.44, 3.51]).reshape(-1, 1)
```
3. 定义多项式回归模型
```python
poly_reg = PolynomialFeatures(degree=4)
x_poly = poly_reg.fit_transform(x)
poly_reg.fit(x_poly, y)
lin_reg = LinearRegression()
lin_reg.fit(x_poly, y)
```
4. 绘制拟合图像
```python
plt.scatter(x, y, color='blue')
plt.plot(x, lin_reg.predict(poly_reg.fit_transform(x)), color='red')
plt.title('Polynomial Regression')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
```
最终的拟合结果如下所示:
![拟合结果](https://img-blog.csdnimg.cn/20210722161036855.png)
阅读全文