建造神经网络

导入数据

x_data = np.linspace(-1,1,300, dtype=np.float32)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise

None代表无论输入有多少都可以,因为输入只有一个特征,所以这里是1

xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])

搭建网络

定义隐藏层,使用 Tensorflow 自带的激励函数tf.nn.relu

#l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
l1 = tf.layers.dense(tf_x, 10, tf.nn.relu)

定义输出层。此时的输入是隐藏层的输出——l1,输入有10层(隐藏层的输出层),输出有1层。

#prediction = add_layer(l1, 10, 1, activation_function=None)
prediction =tf.layers.dense(l1, 1)
#loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
#                     axis=1))
loss = tf.losses.mean_squared_error(tf_y, output)
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for i in range(1000):
    # training
    ts_,loss_=sess.run([train_step,loss], feed_dict={xs: x_data, ys: y_data})
     if i % 50 == 0:
        # to see the step improvement
        print(i,loss_)

Last updated