写一个最小二乘回归的python代码,并给出检验。
时间: 2024-03-14 20:47:46 浏览: 50
好的,这是一个简单的最小二乘回归的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])
# 定义最小二乘回归函数
def least_squares(x, y):
n = len(x)
sx = np.sum(x)
sy = np.sum(y)
sxx = np.sum(x*x)
sxy = np.sum(x*y)
a = (n*sxy - sx*sy) / (n*sxx - sx*sx)
b = (sy - a*sx) / n
return a, b
# 计算回归方程系数
a, b = least_squares(x, y)
# 绘制样本数据和回归线
plt.scatter(x, y)
plt.plot(x, a*x+b, color='red')
plt.show()
# 计算R方值
y_pred = a*x + b
ssr = np.sum((y_pred - np.mean(y))**2)
sst = np.sum((y - np.mean(y))**2)
r_squared = ssr / sst
print("R-squared value:", r_squared)
```
输出结果:
```
R-squared value: 1.0
```
这个R-squared值为1,说明该回归方程完全拟合了样本数据。
阅读全文