线性回归例: 使用分解 (Cholesky方法)
这个脚本使用TensorFlow的函数, tf.cholesky()
分解设计矩阵并求解线性回归的参数矩形。
对于线性回归,我们给定方程组 ⋅=A⋅x=y。这里 A 是我们的设计矩阵, x 是我们的参数矩阵, y 是我们的目标矩阵 (因变量)。
对于 Cholesky 分解我们假定 A 可以分解为下三解矩阵 L 及其转置 LT的积。
注意 A 是方阵。当然,对于超定系统, A 不是方阵。 所以我们用 ⋅AT⋅A 代替。然后我们假定:
对于Cholesky分解的更多信息请见: The Cholesky Decomposition
假定 A 有唯一的 Cholesky 分解, 我们可以写出线性回归方程组:
然后分解方程组:
以及
我们求解 x 的步骤如下:
1.计算 A 的Cholesky分解, 其中
#List3-39
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
ops.reset_default_graph()
# Create the data
x_vals = np.linspace(0, 10, 100)
y_vals = x_vals + np.random.normal(0, 1, 100)
# Create design matrix
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))
# Create y matrix
y = np.transpose(np.matrix(y_vals))
# Create tensors
A_tensor = tf.constant(A)
y_tensor = tf.constant(y)
# Find Cholesky Decomposition
tA_A = tf.matmul(tf.transpose(A_tensor), A_tensor)
L = tf.linalg.cholesky(tA_A)
我们解第一个方程。 (见前见介绍的第二步)
# Solve L*y=t(A)*b
tA_y = tf.matmul(tf.transpose(A_tensor), y)
sol1 = tf.linalg.solve(L, tA_y)
我们通过解第二个方程得到参数矩阵 (见介绍的第三步)。
# Solve L' * y = sol1
sol2 = tf.linalg.solve(tf.transpose(L), sol1)
提取系数并创建最佳拟合线。
# Extract coefficients
#slope = solution_eval[0][0]
#y_intercept = solution_eval[1][0]
slope = sol2[0][0]
y_intercept =sol2[1][0]
print('slope: ' + str(slope))
print('y_intercept: ' + str(y_intercept))
# Get best fit line
best_fit = []
for i in x_vals:
best_fit.append(slope*i+y_intercept)
# Plot the results
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()