tensorflow (2) Using tensorflow to implement linear regression

1. Randomly generate 1000 points, distribute them around the y=0.1x+0.3 line, and draw them

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

num_points = 1000
vectors_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()

Second, construct the linear regression function

#生成一维的w矩阵,取值为[-1,1]之间的随机数
w = tf.Variable(tf.random_uniform([1],-1.0,1.0),name='W')
#生成一维的b矩阵,初始值为0
b = 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)
#最小化loss
train = 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()

3. Part of the training results are as follows:

W= [ 0.10559751] b= [ 0.29925063] loss= 0.000887708
W= [ 0.10417549] b= [ 0.29926425] loss= 0.000884275
W= [ 0.10318361] b= [ 0.29927373] loss= 0.000882605
W= [ 0.10249177] b= [ 0.29928035] loss= 0.000881792
W= [ 0.10200921] b= [ 0.29928496] loss= 0.000881397
W= [ 0.10167261] b= [ 0.29928818] loss= 0.000881205
W= [ 0.10143784] b= [ 0.29929042] loss= 0.000881111
W= [ 0.10127408] b= [ 0.29929197] loss= 0.000881066

The fitted straight line is shown in the figure:
write picture description here

Conclusion: In the end, w tends to 0.1, and b tends to 0.3, which satisfies the data distribution set in advance.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325387906&siteId=291194637