通过TensorFlow用神经网络实现对二次函数的拟合。代码来自莫烦TensorFlow教程

 1 import tensorflow as tf
 2 import numpy as np
 3 
 4 def add_layer(inputs, in_size, out_size, activation_function=None):
 5     Weights = tf.Variable(tf.random_normal([in_size, out_size]))
 6     biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
 7     Wx_plus_b = tf.matmul(inputs, Weights) + biases
 8     if activation_function is None:
 9         outputs = Wx_plus_b
10     else:
11         outputs = activation_function(Wx_plus_b)
12     return outputs
13 
14 # Make up some real data
15 x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]   # np.newaxis的作用就是在它所在的位置增加一个一维
16 noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
17 y_data = np.square(x_data) - 0.5 + noise
18 
19 # define placeholder for inputs to network
20 xs = tf.placeholder(tf.float32, [None, 1])
21 ys = tf.placeholder(tf.float32, [None, 1])
22 # add hidden layer
23 l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
24 # add output layer
25 prediction = add_layer(l1, 10, 1, activation_function=None)
26 
27 # the error between prediction and real data
28 loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1]))
29 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
30 # important step
31 sess = tf.Session()
32 init = tf.global_variables_initializer()
33 sess.run(init)
34 
35 for i in range(500):
36     # training
37     sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
38     if i % 50 == 0:
39         # to see the step improvement
40         print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))

运行结果:

0.3695223
0.03633204
0.07279602
0.008672798
0.0063357423
0.0055126143
0.004952927
0.0045463713
0.0041970443
0.0038996863