最小二乘法 (Least Squares, LSM) 算法python代码
时间: 2024-05-16 19:12:54 浏览: 168
最小二乘法(Least Squares Method)是一种数学优化技术,用于寻找函数和一组数据点之间的最小二乘误差的解析解。下面是使用Python实现最小二乘法的示例代码:
```python
import numpy as np
# 最小二乘法函数
def least_squares(x, y):
n = len(x)
sum_x = sum(x)
sum_y = sum(y)
sum_xy = sum(x * y)
sum_x2 = sum(x ** 2)
# 计算斜率和截距
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
intercept = (sum_y - slope * sum_x) / n
return slope, intercept
# 测试数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 6, 8])
# 调用函数计算斜率和截距
slope, intercept = least_squares(x, y)
# 输出结果
print("斜率:",slope)
print("截距:",intercept)
```
输出结果为:
```
斜率: 1.4
截距: 0.6000000000000001
```
该结果表明,当x增加1个单位时,y的预期增加值为1.4,而y的截距为0.6。
阅读全文