一元回归方程 python
时间: 2023-11-03 19:59:49 浏览: 50
一元回归方程是指只有一个自变量的回归方程。在Python中,可以使用scikit-learn库中的线性回归模型来拟合一元回归方程。具体的步骤如下:
1. 导入所需的库和模块:
```python
from sklearn.linear_model import LinearRegression
import numpy as np
```
2. 准备数据:
首先,定义自变量x和因变量y的数据。可以使用NumPy库来创建这些数据,例如:
```python
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])
```
3. 创建回归模型对象并拟合数据:
```python
model = LinearRegression()
model.fit(x.reshape(-1, 1), y)
```
4. 获取回归方程的系数和截距:
```python
coefficient = model.coef_
intercept = model.intercept_
```
5. 组合回归方程:
```python
regression_equation = f"y = {coefficient}x + {intercept}"
```
所以,一元回归方程的Python代码如下所示:
```python
from sklearn.linear_model import LinearRegression
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])
model = LinearRegression()
model.fit(x.reshape(-1, 1), y)
coefficient = model.coef_
intercept = model.intercept_
regression_equation = f"y = {coefficient}x + {intercept}"
```