用python实现一元线性回归
时间: 2023-09-20 16:13:44 浏览: 121
以下是使用Python实现一元线性回归的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 输入数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([3, 5, 7, 9, 11])
# 计算均值
x_mean = np.mean(x)
y_mean = np.mean(y)
# 计算斜率和截距
num = 0
denom = 0
for i in range(len(x)):
num += (x[i] - x_mean) * (y[i] - y_mean)
denom += (x[i] - x_mean) ** 2
slope = num / denom
intercept = y_mean - slope * x_mean
# 输出结果
print("斜率:", slope)
print("截距:", intercept)
# 绘制数据和拟合直线
plt.scatter(x, y)
plt.plot(x, slope * x + intercept, 'r')
plt.show()
```
输出:
```
斜率: 2.0
截距: 1.0
```
绘制的图形如下所示:
![一元线性回归图](https://img-blog.csdn.net/20170627101451805?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc2hvcnR5X2Jsb2dfY29kZS5wbmc=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/75)
阅读全文