python 线性回归代码
时间: 2023-10-14 16:30:24 浏览: 98
以下是一个简单的Python线性回归代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
# 输入数据
X = np.array([1, 2, 3, 4, 5])
Y = np.array([5, 7, 9, 11, 13])
# 均值
x_mean = np.mean(X)
y_mean = np.mean(Y)
# 总数据个数
n = len(X)
# 使用公式计算斜率和截距
numerator = 0
denominator = 0
for i in range(n):
numerator += (X[i] - x_mean) * (Y[i] - y_mean)
denominator += (X[i] - x_mean) ** 2
slope = numerator / denominator
intercept = y_mean - (slope * x_mean)
# 输出结果
print("斜率:", slope)
print("截距:", intercept)
# 绘制图像
plt.scatter(X, Y)
plt.plot(X, slope * X + intercept, 'r')
plt.show()
```
这个代码计算输入数据的线性回归,并绘制了一个散点图和回归线。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![ipynb](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)