【详细】使用正定分解矩阵拟合线性一次方程

1.如何对方程 A X = b AX=b AX=b求解,A=[x1,x2,x3,…xn], b=[y1,y2,y3…yn]都为列向量。
输入A,b的散点图如下:
在这里插入图片描述
数学推导如下:

令 C = A T ∗ A 令C=A^{T}*A C=ATA 变 换 为 : A T ∗ A X = A T ∗ b 变换为:A^{T}*AX=A^{T}*b ATAX=ATb 即 : C X = A T ∗ b = B 即:CX=A^{T}*b=B CX=ATb=B

C 为 正 定 矩 阵 可 以 表 示 为 一 个 下 三 角 矩 阵 L 和 其 转 置 L T 的 积 : C为正定矩阵可以表示为一个下三角矩阵L和其转置L^{T}的积: CLLT
L ∗ L T X = B L*L^{T}X=B LLTX=B
令 : L T X = Y 、 先 通 过 L ∗ Y = B 求 得 Y , 再 通 过 L T X = Y 求 得 X 令:L^{T}X=Y 、 先通过 L*Y=B求得Y,再通过 L^{T}X=Y求得X LTX=YLY=BYLTX=YX

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

sess = tf.Session()
A = np.linspace(0, 10, 100)
b = A + np.random.normal(0, 1, 100)
x_vals_column = np.transpose(np.matrix(A))
ones_column = np.transpose(np.matrix(np.repeat(1, 100)))
A = np.column_stack((x_vals_column, ones_column))
b = np.transpose(np.matrix(b))
A_tensor = tf.constant(A)   #输入矩阵A
b_tensor = tf.constant(b)   #输出矩阵B

tA_A = tf.matmul(tf.transpose(A_tensor), A_tensor)   #求得正定矩阵C
L = tf.cholesky(tA_A)  #三角矩阵L
tA_b = tf.matmul(tf.transpose(A_tensor), b)
sol1 = tf.matrix_solve(L, tA_b) #求得Y
sol2 = tf.matrix_solve(tf.transpose(L), sol1) #求得X

solution_eval = sess.run(sol2)
slope = solution_eval[0][0]
y_intercept = solution_eval[1][0]
print('slope: ' + str(slope))
print('y'_intercept: ' + str(y_intercept))

best_fit = []
for i in x_vals:
	best_fit.append(slope*i+y_intercept)
plt.plot(x_vals, y_vals, 'o', label='Data')
plt.plot(x_vals, best_fit, 'r-', label='Best' fit line',
linewidth=3)
plt.legend(loc='upper left')
plt.show()

拟合一次方程图像如下:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值