基于tensroflow的线性回归(1):直接用tensorflow求逆矩阵(python)

主要介绍使用tensorflow求逆矩阵的方法解决二维线性回归问题,线性回归算法能表示为矩阵计算,Ax=b。这里解决的是用矩阵x来求解系数。注意,如果观测矩阵不是方阵,那求解出的矩阵x如下式:

                                                                               

python代码如下:

# 求逆矩阵
#导入必要的库,初始化计算图,生成数据
import tensorflow as tf
import  matplotlib.pyplot as plt
import numpy as np
sess = tf.Session()
x_vals = np.linspace(0,10,100)
y_vals = x_vals + np.random.normal(0,1,100)
# 创建求逆方法所需矩阵,并转换成张量
x_vals_column = np.transpose(np.matrix(x_vals))
ones_column = np.transpose(np.matrix(np.repeat(1,100)))
A = np.column_stack((x_vals_column,ones_column))
B = np.transpose(np.matrix(y_vals))
A_tensor = tf.constant(A)
B_tensor = tf.constant(B)
# 使用tensorflow中的tf.matrix_inverse()方法
tA_A = tf.matmul(tf.transpose(A_tensor),A_tensor)
tA_A_inv = tf.matrix_inverse(tA_A)
product = tf.matmul(tA_A_inv,tf.transpose(A_tensor))
solution = tf.matmul(product,B_tensor)
solution_eval = sess.run(solution)
# 最终得到系数矩阵结果,第一行一列为斜率,第二行一列为截距。
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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值