OLS.py 814 字节
Newer Older
6
62ac1e676314f46ab57773b8 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
from sympy import *
import numpy as np

def OLS(A,b):
    output=''
    x1, x2= symbols('x1, x2')
    A=np.array(A)
    b=np.array(b)
    F=0*x1
    for i in range(np.shape(A)[0]):
        F=F+(A[i][0]*x1+A[i][1]*x2-b[i])**2
    output+=f'令F(x)={F},\n则原问题化为minF(x)(x∈R)\n记A={A},x=[x1,x2]^T,b={b},\n则F(x)=(Ax-b)^T(Ax-b)。\n'
    output+=f'{A.T}'
    ATA=np.dot(A.T,A)
    ATb=np.dot(A.T,b)
    x=np.dot(np.linalg.inv(ATA),ATb)
    output+=f'∴A^TA:\n{ATA}\n  A^Tb:\n{ATb}\n  (A^TA)^-1:\n{np.linalg.inv(ATA)}\n∴近似解x=(A^TA)^-1 * A^Tb={x}^T'
    return output

if __name__ == '__main__':
    #等式左边的系数
    A=[[1,2],
       [3,-1],
       [2,-3]]
    #等式右边的常数
    b=[5,
       3,
       0]
    output=OLS(A,b)
    print(output)