tensorflow学习笔记——简单的线性模型

import tensorflow as tf
import numpy as np

#使用numpy生成100个随机点,数值范围为[0,1)
x_data = np.random.rand(100)
y_data = x_data*0.1 + 0.2

#构造一个线性模型
b = tf.Variable(0.5)
k = tf.Variable(0.5)
y = k * x_data + b

#二次代价函数
loss = tf.reduce_mean(tf.square(y_data-y))
#定义一个梯度下降法来训练的优化器
optimizer = tf.train.GradientDescentOptimizer(0.2)
#最小化代价函数
train = optimizer.minimize(loss)
#初始化变量
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]))

运行结果:

0 [0.40405247, 0.3106143]
20 [0.21564536, 0.14596945]
40 [0.16456008, 0.16983667]
60 [0.1360413, 0.18316102]
80 [0.12012042, 0.19059947]
100 [0.11123243, 0.19475205]
120 [0.1062706, 0.1970703]
140 [0.103500605, 0.19836447]
160 [0.10195425, 0.19908695]
180 [0.10109096, 0.1994903]
200 [0.100609034, 0.19971545
发布了33 篇原创文章 · 获赞 148 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40692109/article/details/104084903