线性回归逆矩阵方法
这个脚本展示如何用tensorflow的矩阵逆完成线性回归。
给定方程组 ⋅A⋅x=y, 线性回归的矩阵逆由以下x解得到。
这里作为备忘, x 是我们的参数矩阵 (长度为 +1F+1的向量, 其中 F 是特征数)。这里, A, 我们的设计矩阵的形式为
其中 F 独立特征数, 且 n 是点数。对于超定方程组, >n>F。记住我们的方程组中的一个观测点的长度为 +1F+1 且 ℎith 点看起来像
对于这个配方recipe, 我们只考虑2-dimensional 系统 (=1F=1), 以便我们可以绘制结果。
#List3-38
我们从加载必要的库开始。
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
ops.reset_default_graph()
出于展示的目的,我们生成随机数进行拟合。
x值是从0到100的等距值。
y值拟合直线: =y=x, 但是我们会增加服从 (0,1)N(0,1)的随机误差。
# Create the data
x_vals = np.linspace(0, 10, 100)
y_vals = x_vals + np.random.normal(0, 1, 100)
我们创建设计矩阵, A, 由一列的1和x值组成。
# 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))
我们用Numpy创建y值作为矩阵。
我们得到y值和设计矩阵后,我们创建它们的张量。
# Format the y matrix
y = np.transpose(np.matrix(y_vals))
# Create tensors
A_tensor = tf.constant(A)
y_tensor = tf.constant(y)
我们用tensorflow求解参数矩阵。
# Matrix inverse solution
tA_A = tf.matmul(tf.transpose(A_tensor), A_tensor)
#tA_A_inv = tf.inverse(tA_A)
tA_A_inv = tf.linalg.inv(tA_A)
product = tf.matmul(tA_A_inv, tf.transpose(A_tensor))
solution = tf.matmul(product, y_tensor)
运行方案并从参数矩阵提取斜率和载距。
solution_eval = solution
# Extract coefficients
slope = solution_eval[0][0]
y_intercept = solution_eval[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)
我们用Matplotlib来绘制结果。
# 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()