TensorFlow(二) 用TensorFlow为线性回归算法实现矩阵分解

import matplotlib.pyplot as plt
import  numpy as np
import tensorflow as tf

sess=tf.Session()
x_vals=np.linspace(0,10,100)
y_vals=x_vals+np.random.normal(0,1,100)

#装换成矩阵 reshape成 (None,1)
x_vals_column=np.transpose(np.matrix(x_vals))

#用来合并 100个元素 (100,2)*(2,1)=(100,1) ==> 若为一个元素  (1,2)*(2,1)=(1,1) 符合运算形式 [2,1]*[[1],[2]]=[4] 即为 kx+b=y  =>(x,1)*(k,b)=y==>A*x=b
ones_column=np.transpose(np.matrix(np.repeat(1,100)))
#tuple 参数
A=np.column_stack((x_vals_column,ones_column))
b=np.transpose(np.matrix(y_vals))
#reshape
A_tensor=tf.constant(A)
b_tensor=tf.constant(b)
#(2,2) 简化运算 *转置矩阵 降维
#A*x=b ==> A^T*A*x=A^t*b  ==> tA_A * x = A^T*b
tA_A=tf.matmul(tf.transpose(A_tensor),A_tensor)

#A*x=b  =>  cholseky() 分解矩阵  tA_A=LL'  ==>    LL'* x=A^T*b
L=tf.cholesky(tA_A)
#得到A^t*b
tA_b=tf.matmul(tf.transpose(A_tensor),b_tensor)
# L'* x
solve1=tf.matrix_solve(L,tA_b)
#x
solve2=tf.matrix_solve(tf.transpose(L),solve1)
solution_eval=sess.run(solve2)
#获取最终结果
slope=solution_eval[0][0]
y_intercept=solution_eval[1][0]
print(str(slope))
print(str(y_intercept))
best_fit=[]
for i in x_vals:
    best_fit.append(slope*i+y_intercept)
plt.plot(x_vals,y_vals,'o')
plt.plot(x_vals,best_fit,'r-')
plt.show()

猜你喜欢

转载自www.cnblogs.com/x0216u/p/9167279.html
今日推荐