Tensorflow-fitting straight lines

1 Introduction

Tensorflow attaches great importance to structure.We have to build the structure of the neural network before we can put the numbers into it and run this structure.

2. Import the module and create data

First, we need to load two modules, tensorflow and numpy, and use numpy to create our data.

import tensorflow as tf
import numpy as np

x_data = np.random.rand(100).astype(np.float32)    #随机样本位于[0, 1)中
y_data = x_data*0.5 + 2

3. Build the model

We use tf.Variable to create parameters describing y. We can imagine y_data = x_data * 0.1 + 0.3 as y = Weights * x + biases, and then the neural network is learning to change Weights to 0.1 and biases to 0.3.

Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))   #返回一维数组,产生于low和high之间,产生的值是均匀分布的 #tf.Variable()用于生成一个初始值为initial-value的变量;必须指定初始化值
biases = tf.Variable(tf.zeros([1]))  
y = Weights*x_data + biases

4. Calculate the error and the reverse transmission of the error

Next is to calculate the error of y and y_data. The work of transferring the error back is taught to the optimizer. The error transfer method we use is the gradient descent method: Gradient Descent Let us use the optimizer to update the parameters.

loss = tf.reduce_mean(tf.square(y-y_data))   #tf.reduce_mean用于计算张量tensor沿着指定的数轴(tensor的某一维度)上的的平均值
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

5. Train the model

We just built the structure of the neural network, and have not used this structure. Before using this structure, we must first initialize all the Variables previously defined, so this step is very important

init = tf.global_variables_initializer()  #返回一个用来初始化计算图中所有global variable的op

Then, we create a Session Session. We use Session to perform the init initialization step. And, use Session to run each training data. Gradually improve the prediction accuracy of the neural network.

sess = tf.Session()    #创建一个会话
sess.run(init)   #用 Session 来执行 init 初始化

for step in range(301):   #定义300次迭代
    sess.run(train)
    if step%20 == 0:    #每隔20次打印一次权重和偏置
        print(step, sess.run(Weights),sess.run(biases))

Insert picture description here
It can be seen that the final weight and offset are very close to the weight and offset of y_data = x_data * 0.5 + 2.

Published 227 original articles · praised 633 · 30,000+ views

Guess you like

Origin blog.csdn.net/weixin_37763870/article/details/105479139