五.TensorFlow小例子2

TensorFlow小例子2

eg.每一次训练之后的参数是多少,每隔20次输出参数.

y = 0.1x + 0.3

import tensorflow as tf
import numpy as np

#create data
x_data  = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3

###create tensorflow structure start ###
#为大写,因为可能为矩阵
#用一个随机数列生成.1列,-1到1的范围
Weights = tf.Variable(tf.random_uniform([1],-1.0,1))
#初始值为0,一步步学习到0.1及0.3
biases = tf.Variable(tf.zeros([1]))

y = Weights * x_data + biases
#预测的y与真实值的差别,刚开始loss会很大
loss = tf.reduce_mean(tf.square(y - y_data))
#优化器,0.5为学习效率.
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
#前面只是建立结构,现在初始化一下
init = tf.initialize_all_variables()
###create tensorflow structure end ###

#结构激活
sess = tf.Session()
#这里激活,开始飞起来
sess.run(init)     #very important

for step in range(201):
    #开始训练
    sess.run(train)
    if step % 20 == 0:
        print(step,sess.run(Weights),sess.run(biases))
= RESTART: /Users/dongsai/Documents/MachineLearning/tensorflow/tf_lesson5.py =
WARNING:tensorflow:From /Users/dongsai/Documents/MachineLearning/tensorflow/tf_lesson5.py:22: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
0 [ 0.035458] [ 0.4381814]
20 [ 0.06898844] [ 0.31556118]
40 [ 0.09100783] [ 0.30451214]
60 [ 0.0973926] [ 0.30130836]
80 [ 0.09924397] [ 0.30037937]
100 [ 0.09978078] [ 0.30011001]
120 [ 0.09993643] [ 0.30003193]
140 [ 0.09998157] [ 0.30000925]
160 [ 0.09999464] [ 0.30000269]
180 [ 0.09999847] [ 0.30000079]
200 [ 0.09999955] [ 0.30000025]

注:

Use `tf.global_variables_initializer` instead.

因为版本问题,代码中修改成新版的接口即可.

关注微信公众号:玉麒麟百科

回复'tensorflow代码',即可获取系列教程源码.

你可能感兴趣的:(tensorflow)