In [98]:
import tensorflow as tf
In [99]:
import numpy as np
In [100]:
x_data = np.linspace(-1,1,300)[:,np.newaxis]
In [101]:
noise = np.random.normal(0,0.05,x_data.shape)
In [102]:
y_data = np.square(x_data) - 0.5 + noise
In [103]:
xs = tf.placeholder(tf.float32,[None,1])
In [104]:
ys = tf.placeholder(tf.float32,[None,1])
In [105]:
def add_layer(inputs,in_size,out_size,activation_function=None):
weights = tf.Variable(tf.random_normal([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
In [106]:
hl = add_layer(xs,1,20,activation_function=tf.nn.relu) # 构建隐藏层 假设隐藏层有10个神经元
In [107]:
predication = add_layer(hl,20,1,activation_function=None) # 构建输出层 假设输出层和输入层一样 有一个神经元
In [108]:
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - predication),reduction_indices=[1]))
In [109]:
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
In [110]:
init = tf.global_variables_initializer() # 初始化所有变量
In [111]:
sess = tf.Session()
In [112]:
sess.run(init)
In [113]:
for i in range(1000):
sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
if i % 50 == 0:
print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))