基于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()

实验结果:


可以看到利用矩阵求逆可以拟合二维数据点。


猜你喜欢

转载自blog.csdn.net/forever0_0love/article/details/81061443
今日推荐