tensorflow使用逆矩陣實現線性迴歸

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

sess = tf.Session() x_vals = np.linspace(0,10,100) y_vals = x_vals+np.random.normal(0,1,100) x_vals_column = np.transpose(np.matrix(x_vals)) one_clumn = np.transpose(np.matrix(np.repeat(1,100))) A = np.column_stack((x_vals_column,one_clumn)) b =np.transpose(np.matrix(y_vals))dom

A_tensor = tf.constant(A) b_tensor = tf.constant(b)spa

tA_A = tf.matmul(tf.transpose(A_tensor),A_tensor)orm

tA_A_inv = tf.matrix_inverse(tA_A) product = tf.matmul(tA_A_inv,tf.transpose(A_tensor)) solution = tf.matmul(product,b_tensor)it

solution_eval = sess.run(solution) print(solution_eval)io

slope = solution_eval[0][0] y_intercept = solution_eval[1][0]import

best_fit =[] for i in x_vals: best_fit.append(slope*i+y_intercept) plt.plot(x_vals,y_vals,'o',label = 'data') plt.plot(x_vals,best_fit,'r--',label='best fit line') plt.legend(loc = 'upper left') plt.show()tensorflow

相關文章
相關標籤/搜索