用TensorFlow内建的Cholesky矩阵分解法实现矩阵分解的线性回归

网友投稿 782 2022-11-19

用TensorFlow内建的Cholesky矩阵分解法实现矩阵分解的线性回归

用TensorFlow内建的Cholesky矩阵分解法实现矩阵分解的线性回归

用户对分解一个矩阵为多个矩阵的方法感兴趣的原因是,结果矩阵的特性使得其在应用中更高效。

# 线性回归:矩阵分解法# 通过分解矩阵的方法求解有时更高效并且数值稳定#----------------------------------## This function shows how to use TensorFlow to# solve linear regression via the matrix inverse.## Given Ax=b, and a Cholesky decomposition such that# A = L*L' then we can get solve for x via# 1) L*y=t(A)*b# 2) L'*x=yimport matplotlib.pyplot as pltimport numpy as npimport tensorflow as tffrom tensorflow.python.framework import opsops.reset_default_graph()# Create graphsess = tf.Session()# Create the datax_vals = np.linspace(0, 10, 100)y_vals = x_vals + np.random.normal(0, 1, 100)# Create design matrixx_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 b matrixb = np.transpose(np.matrix(y_vals))# Create tensorsA_tensor = tf.constant(A)b_tensor = tf.constant(b)# 找到方阵的Cholesky矩阵分解tA_A = tf.matmul(tf.transpose(A_tensor), A_tensor)# TensorFlow的cholesky()函数仅仅返回矩阵分解的下三角矩阵,# 因为上三角矩阵是下三角矩阵的转置矩阵。L = tf.cholesky(tA_A)# Solve L*y=t(A)*btA_b = tf.matmul(tf.transpose(A_tensor), b)sol1 = tf.matrix_solve(L, tA_b)# Solve L' * y = sol1sol2 = tf.matrix_solve(tf.transpose(L), sol1)solution_eval = sess.run(sol2)# 抽取系数slope = solution_eval[0][0]y_intercept = solution_eval[1][0]print('slope: ' + str(slope))print('y_intercept: ' + str(y_intercept))# Get best fit linebest_fit = []for i in x_vals: best_fit.append(slope*i+y_intercept)# Plot the resultsplt.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()

结果:

slope: 0.998921420857y_intercept: 0.0799919541665

本文是《TensorFlow机器学习实战指南》的读书笔记和动手实践结果。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Python3 获取绝对路径
下一篇:用TensorFlow实现逻辑回归算法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~