最小二乘法

参考:

https://en.wikipedia.org/wiki/Least_squares

https://en.wikipedia.org/wiki/Matrix_calculus

https://baike.baidu.com/item/%E6%9C%80%E5%B0%8F%E4%BA%8C%E4%B9%98%E6%B3%95/2522346?fr=aladdin

线性最小二乘的基本公式:

考虑超定方程组(未知数个数小于方程组个数):

 

其中m代表m个等式,n代表n个未知数,m>n;将其向量化后为:

 

该方程组一般没有解,为了选取最合适的让该等式尽量成立,引入残差平方和函数S

 

转为求函数最小值问题。

S进行微分求最值,可以得到:

 

如果矩阵非奇异则有唯一解:

 

线性方程组最小二乘法实现:

数据:

 

python实现:

import numpy as np

import matplotlib.pyplot as plt

# y = 7x + 1

X = []

y = []

M = 100

Nerror = np.random.normal(0, 20, M)

for i in range(M):

    X.append([i,1])

    y.append(7*i + 1 + Nerror[i])

y = np.array(y)

y = y.T

X = np.array(X)

B = inv((X.T).dot(X)).dot(X.T).dot(y)

Px = [0,M]

Py = []

for x in Px:

    Py.append(B[0]*x + B[1])

fig = plt.figure()

ax = fig.add_subplot(1,1,1)

plt.scatter(list(range(100)),list(y))

plt.plot(Px,Py,color='r')

plt.grid()

plt.title('Ordinary Least Square')

plt.show()

RTKLIBC实现:

rtkcmn.c

 lsq()

原文地址:https://www.cnblogs.com/sunnypoem/p/10421792.html