定义一个自动增加网络层数的函数
权重weight的设置:在生成初始参数时,随机变量(normal distribution)会比全部为0要好很多,所以我们这里的weights为一个in_size行, out_size列的随机变量矩阵。
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases:的推荐值不为0,所以我们这里是在0向量的基础上又加了0.1。
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
#定义一个自动增加网络层数的函数
# inputs:输入值、
# in_size:输入神经元个数
# out_size:输出神经元个数
# activation_function:激励函数,默认的激励函数是None。
def add_layer(inputs, in_size, out_size, activation_function=None):
Weights = tf.Variable(tf.random_normal([in_size, out_size]))#一个in_size行, out_size列的随机变量矩阵。
biases = tf.Variable(tf.zeros([1, out_size])+0.1)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
搭建网络
# Author Qian Chenglong
import tensorflow as tf
import numpy as np
#定义一个自动增加网络层数的函数
# inputs:输入值、
# in_size:输入神经元个数
# out_size:输出神经元个数
# activation_function:激励函数,默认的激励函数是None。
def add_layer(inputs, in_size, out_size, activation_function=None):
Weights = tf.Variable(tf.random_normal([in_size, out_size]))#一个in_size行, out_size列的随机变量矩阵。
biases = tf.Variable(tf.zeros([1, out_size])+0.1)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
#生成数据
x_data = np.linspace(-1,1,300, dtype=np.float32)[:, np.newaxis]
noise = np.random.normal(0, 0.02, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.tanh) #隐藏层
prediction=add_layer(l1,10,1, activation_function=tf.nn.tanh) #输出层
loss=tf.reduce_mean(tf.square(prediction-ys)) #损失函数
train_step =tf.train.GradientDescentOptimizer(0.1).minimize(loss)
with tf.Session() as sess:
# 变量初始化
sess.run(tf.global_variables_initializer())
for i in range(2000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0:
# to see the step improvement
print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))