tensorflow learning (4) - with tensorflow training slope and intercept of the linear function

Foreword

Previous blog: tensorflow learning (3) - Fetch Feed &
b station watching the teacher of the course is still very conscience, starts with practical examples makes me feel learning has a great understanding of this section to help - direct linear function of training to get started the slope and intercept.

Import Package

import tensorflow as tf
import numpy as np

Generating training samples

#使用numpy生成100个随机点
x_data = np.random.rand(100)
#构建y关于x的线性关系
y_data = x_data * 0.1 + 0.2

A linear model structure

b = tf.Variable(0.)
k = tf.Variable(0.)
y = k * x_data + b
  • Note here that the value of k is required b and float, it is necessary to keep up with a 0 in the back. "."

Design Optimizer

#二次代价函数
loss = tf.reduce_mean(tf.square(y_data - y))
#定义一个梯度下降算法来进行训练的优化器
optimizer = tf.train.GradientDescentOptimizer(0.2)
#最小化代价函数
train = optimizer.minimize(loss)
  • Note here that this parameter is 0.2 learning rate, the higher the rate, the worse the accuracy, here is probably the next test, when the result is far greater than the 0.8 training, basic values ​​of 0.7 or accurate.

Start training

#初始化变量
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for step in range(201):
        sess.run(train)
        if step % 20 == 0:
            print(step,sess.run([k,b]))

Output

Here Insert Picture Description

Published 53 original articles · won praise 5 · Views 2212

Guess you like

Origin blog.csdn.net/qq_37668436/article/details/104808000
Recommended