编写python代码,线性回归模型
时间: 2023-03-21 22:00:54 浏览: 126
下面是一个使用Python实现的简单线性回归模型:
```python
import numpy as np
import matplotlib.pyplot as plt
# 输入数据
X = np.array([1, 2, 3, 4, 5])
Y = np.array([2, 4, 5, 4, 5])
# 计算X和Y的均值
mean_x = np.mean(X)
mean_y = np.mean(Y)
# 计算回归系数
numerator = 0
denominator = 0
for i in range(len(X)):
numerator += (X[i] - mean_x) * (Y[i] - mean_y)
denominator += (X[i] - mean_x) ** 2
b1 = numerator / denominator
b0 = mean_y - (b1 * mean_x)
# 打印回归系数
print("回归系数:")
print("b0 = ", b0)
print("b1 = ", b1)
# 绘制回归线
max_x = np.max(X) + 1
min_x = np.min(X) - 1
x = np.linspace(min_x, max_x, 1000)
y = b0 + b1 * x
plt.plot(x, y, color='#58b970', label='Regression Line')
# 绘制散点图
plt.scatter(X, Y, c='#ef5423', label='Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.show()
```
这个程序使用Numpy和Matplotlib库来实现简单线性回归模型,并绘制出回归线和散点图。您可以将输入数据`X`和`Y`替换为您自己的数据,以应用该程序。
阅读全文