1)简单优化器的构建代码:
import tensorflow as tf
import numpy as np
#create data
#生成100个一维随机数列
x_data = np.random.rand(100).astype(np.float32)
#这里表示我们要预测的Weight和biases
y_data = x_data*0.1 + 0.3
**##create tensorflow structure start##**
#Weights之所以大写是因为他可能是个多元矩阵的,大写好辨识,随机数列生成的1维的结构,范围在(-1.0,1.0)
Weights =tf.Variable(tf.random_uniform([1],-1.0,1.0))
biases = tf.Variable(tf.zeros([1]))
#预测的y值
y = Weights*x_data + biases
#预测y和实际的y_data的差异
loss =tf.reduce_mean(tf.square(y-y_data))
**#训练部分的网络:建立优化器,使用优化器减少误差**
optimizer = tf.train.GradientDescentOptimizer(0.5)#0.5表示lr
train = optimizer.minimize(loss)
#神经网络初始化所有变量
init = tf.initialize_all_variables()
**#create tensorflow structure end##**
#激活神经网络的结构
sess = tf.Session()
sess.run(init) #very important
#训练201次,每隔20步打印一次weights和biases
for step in range(201):
sess.run(train)
if step % 20 ==0:
print(step,sess.run(Weights),sess.run(biases))
实验结果:
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.71626151] [-0.06535698]
20 [ 0.28147861] [ 0.19988234]
40 [ 0.15252745] [ 0.27102178]
60 [ 0.11520365] [ 0.29161251]
80 [ 0.10440055] [ 0.29757231]
100 [ 0.10127372] [ 0.29929733]
120 [ 0.10036866] [ 0.29979664]
140 [ 0.10010672] [ 0.29994115]
160 [ 0.1000309] [ 0.29998296]
180 [ 0.10000893] [ 0.29999509]
200 [ 0.10000261] [ 0.29999858]