TensorFlow通過Cholesky矩陣分解實現線性迴歸
阿新 • • 發佈:2019-02-19
這裡將用TensorFlow實現矩陣分解,對於一般的線性迴歸演算法,求解Ax=b,則x=(A'A)^(-1)A'b,然而該方法在大部分情況下是低效率的,特別是當矩陣非常大時效率更低。另一種方式則是通過矩陣分解來提高效率。這裡採用TensorFlow內建的Cholesky矩陣分解法實現線性迴歸。
Cholesky可以將一個矩陣分解為上三角矩陣和下三角矩陣,即A = LL'
這裡,要求解Ax=b ==>A'Ax=A'b,我們將A'A進行Cholesky分解.即A'A = LL'因此上式可以變為
LL'x = A'b
因此我們可以分兩步進行求解X
(1)Ly = A'b求出y
(2)y = L'x
下面我們具體實現:
首先引入相應的庫並建立計算圖會話,宣告佔位符和變數並構建資料
#A通過Cholesky分解為LL'因此Ax = b ==>A'Ax = A'b ==>LL'x = A'b ==>Ly = A'b ,L'x = y(L與L'矩陣為上三角與下三角矩陣,且互為轉置) import numpy as np import matplotlib.pyplot as plt import tensorflow as tf sess = tf.Session() x_vals = np.linspace(0,10,100) y_vals = x_vals + np.random.normal(0,1,100) x_vals_colum = np.transpose(np.matrix(x_vals)) ones_column = np.transpose(np.matrix(np.ones([1,100]))) A = np.column_stack((x_vals_colum,ones_column)) #之所以加1矩陣,是為了後面可以使用矩陣計算 b = np.transpose(np.matrix(y_vals)) #將A和b轉化為張量 A_tensor = tf.constant(A) b_tensor = tf.constant(b)
接下來通過tf.cholesky函式計算L,由於該函式返回的是矩陣分解的下三角矩陣,上三角矩陣為該矩陣的轉置
tf.matrix_solve()函式返回Ax=b的解
#Ax = b ==> ATAx = ATb ==> LL'x = A'b ==> Ly = A'b , L'x = y tA_A = tf.matmul(tf.transpose(A_tensor),A_tensor)#ATA L = tf.cholesky(tA_A) #返回下三角矩陣 tA_b = tf.matmul(tf.transpose(A_tensor),b) #ATb sol1 = tf.matrix_solve(L,tA_b) #Ly = A'b sol2 = tf.matrix_solve(tf.transpose(L),sol1) #L'x = y
抽取係數並繪製圖像
#抽取係數
solution_eval = sess.run(sol2)
#從解中抽取係數、斜率和y截距
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)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x_vals,y_vals,'o',label = 'Data')
ax.plot(x_vals,best_fit,'r-',label = 'Best fit line')
handles , labels = ax.get_legend_handles_labels()
ax.legend(handles,labels)
plt.show()