tensorflow(四)搭建一个简单的神经网络模型

基于tensorflow的简单神经网络模型,神经网络模型的基本搭建思路。

import tensorflow as tf
import numpy as np

#使用numpy生成100个随机点
x_data = np.random.rand(100)
y_data = x_data*0.1 + 0.2

#构造一个线性模型
b = tf.Variable(0.)
k = tf.Variable(0.)
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.048859432, 0.09853307]
20 [0.099597774, 0.20019919]
40 [0.099762924, 0.2001175]
60 [0.099860236, 0.20006926]
80 [0.099917606, 0.20004085]
100 [0.09995142, 0.20002408]
120 [0.099971354, 0.2000142]
140 [0.09998311, 0.20000838]
160 [0.09999005, 0.20000494]
180 [0.09999413, 0.20000291]
200 [0.09999653, 0.20000173]

运行结果显示逐渐趋近于0.1和0.2

你可能感兴趣的:(深度学习,tensorflow)