sklearn 一元非线性回归
时间: 2023-12-28 11:05:24 浏览: 99
非线性回归
好的,针对你的问题,我可以给出以下步骤:
1. 导入需要的库和数据集
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# 生成数据集
np.random.seed(0)
x = np.linspace(-3, 3, 100)
y = 2 + x + 0.5 * x**2 + np.random.normal(0, 1, 100)
# 可视化数据集
plt.scatter(x, y)
plt.show()
```
2. 将一元非线性回归转化为多项式回归
```python
# 转化为多项式回归
poly = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly.fit_transform(x.reshape(-1, 1))
```
3. 训练模型并进行预测
```python
# 训练模型
lin_reg = LinearRegression()
lin_reg.fit(X_poly, y)
# 进行预测
X_test = np.linspace(-3, 3, 100).reshape(-1, 1)
X_test_poly = poly.transform(X_test)
_pred = lin_reg.predict(X_test_poly)
# 可视化结果
plt.scatter(x, y)
plt.plot(X_test, y_pred, color='r')
plt.show()
```
阅读全文