大家好,又见面了,我是你们的朋友全栈君。
线性回归算法能表示为矩阵计算,Ax=b。这里要解决的是用矩阵x来求解系数。
1.导入必要的编程库,初始化计算图,并生成数据。
>>> 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)
2.创建后续求逆方法所需的矩阵。创建A矩阵,其为矩阵x_vals_column和ones_column的合并。然后以矩阵y_vals创建b矩阵。
>>> 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))
>>> b=np.transpose(np.matrix(y_vals))
3.将A和b矩阵转换成张量
>>> A_tensor=tf.constant(A)
>>> b_tensor=tf.constant(b)
4.使用tf.matrix_inverse()方法求逆
>>> tA_A=tf.matmul(tf.transpose(A_tensor),A_tensor) >>> tA_A_inv=tf.matrix_inverse(tA_A) >>> product=tf.matmul(tA_A_inv,tf.transpose(A_tensor)) >>> solution=tf.matmul(product,b_tensor)
>>> solution_eval=sess.run(solution)
5.从解中抽取系数、斜率和y截距
>>> slope=solution_eval[0][0] >>> y_intercept=solution_eval[1][0] >>> print(‘slope:’+str(slope)) slope:0.9469285572619588 >>> print(‘y_intercept:’+str(y_intercept)) y_intercept:0.2053153160416511 >>> best_fit=[] >>> for i in x_vals: … best_fit.append(slope*i+y_intercept) … >>> plt.plot(x_vals,y_vals,’o’,label=’Data’) [<matplotlib.lines.Line2D object at 0x000001ED8EA34390>] >>> plt.plot(x_vals,best_fit,’r-‘,label=’Best fit line’,linewidth=3) [<matplotlib.lines.Line2D object at 0x000001ED8BF32FD0>] >>> plt.legend(loc=’upper left’) <matplotlib.legend.Legend object at 0x000001ED8EA34D68>
>>> plt.show()
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/171648.html原文链接:https://javaforall.cn