在安装完TensorFlow框架后,我们来做一个简单的例子,使用TensorFlow拟合简单的线性函数,并输出中间训练的结果。具体的解释就放在代码的注释里。
# encoding=utf-8
'''
Created on 2018年4月19日
@author: yanghang
'''
import numpy as np
import tensorflow as tf
# create data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
# create tensorflow structure start
Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
biases = tf.Variable(tf.zeros([1]))
y = Weights * x_data + biases
loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.initialize_all_variables()
# create tensorflow structure end
ses = tf.Session()
ses.run(init)
for step in range(201):
if step % 20 == 0:
print(step,ses.run(Weights),ses.run(biases))
ses.run(train)
输出的结果如下:
0 [ 0.27708817] [ 0.]
20 [ 0.15496725] [ 0.26999283