import tensorflow as tfimport numpy as npimport matplotlib.pyplot as pltnum_points = 1000vectors_set = []for i in range(num_points): x1 = np.random.normal(0.0,0.55) //设置一定范围的浮动 y1 = x1*0.1+0.3+np.random.normal(0.0,0.03) vectors_set.append([x1,y1])x_data = [v[0] for v in vectors_set]y_data = [v[1] for v in vectors_set]plt.scatter(x_data,y_data,c='r')plt.show()
#生成一维的w矩阵,取值为[-1,1]之间的随机数w = tf.Variable(tf.random_uniform([1],-1.0,1.0),name='W')#生成一维的b矩阵,初始值为0b = tf.Variable(tf.zeros([1]),name='b')y = w*x_data+b#均方误差loss = tf.reduce_mean(tf.square(y-y_data),name='loss')#梯度下降optimizer = tf.train.GradientDescentOptimizer(0.5)#最小化losstrain = optimizer.minimize(loss,name='train')sess=tf.Session()init = tf.global_variables_initializer()sess.run(init)#print("W",sess.run(w),"b=",sess.run(b),"loss=",sess.run(loss))for step in range(20): sess.run(train) print("W=",sess.run(w),"b=",sess.run(b),"loss=",sess.run(loss))//显示拟合后的直线plt.scatter(x_data,y_data,c='r')plt.plot(x_data,sess.run(w)*x_data+sess.run(b))plt.show()
W= [ 0.10559751] b= [ 0.29925063] loss= 0.000887708W= [ 0.10417549] b= [ 0.29926425] loss= 0.000884275W= [ 0.10318361] b= [ 0.29927373] loss= 0.000882605W= [ 0.10249177] b= [ 0.29928035] loss= 0.000881792W= [ 0.10200921] b= [ 0.29928496] loss= 0.000881397W= [ 0.10167261] b= [ 0.29928818] loss= 0.000881205W= [ 0.10143784] b= [ 0.29929042] loss= 0.000881111W= [ 0.10127408] b= [ 0.29929197] loss= 0.000881066