TensorFlow训练二次函数

我们建造一个完整的神经网络
我们将训练一个二次函数y=x*x-0.5,包括添加神经层,计算误差,训练步骤。
TensorFlow训练二次函数
文章图片

构建所需的数据。 这里的x_data和y_data并不是严格的一元二次函数的关系,因为我们多加了一个噪点noise,这样看起来会更像真实情况。

x_data = https://www.it610.com/article/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

利用占位符定义我们所需的神经网络的输入。 tf.placeholder()就是代表占位符,这里的None代表无论输入有多少都可以,因为输入和输出都只有一个特征,所以这里都是1。
xs = tf.placeholder(tf.float32, [None, 1]) ys = tf.placeholder(tf.float32, [None, 1])

接下来,我们就可以开始定义神经层了。 通常神经层都包括输入层、隐藏层和输出层。这里的输入层只有一个属性, 所以我们就只有一个输入;隐藏层我们假设有10个神经元; 输出层和输入层的结构是一样的,所以我们的输出层也是只有一层。 所以,我们构建的是——输入层1个、隐藏层10个、输出层1个的神经网络。
# 隐藏层,激励函数为TensorFlow自带的tf.nn.relu hidden_Weights = tf.Variable(tf.random_normal([1, 10])) hidden_biases = tf.Variable(tf.zeros([1, 10]) + 0.1) hidden_layer = tf.nn.relu(tf.matmul(xs, hidden_Weights) + hidden_biases)# 输出层,不需要激励函数 output_Weights = tf.Variable(tf.random_normal([10, 1])) output_biases = tf.Variable(tf.zeros([1, 1]) + 0.1) prediction = tf.matmul(hidden_layer, output_Weights) + output_biases

【TensorFlow训练二次函数】计算预测值prediction和真实值的误差,对二者差的平方求和再取平均。
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))

接下来,我们利用GradientDescentOptimizer来最小化误差loss。
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

下面,我们让机器训练吧。我们让机器学习1000次,机器学习的内容是train_step,用 Session 来 run 每一次 training 的数据,逐步提升神经网络的预测准确性。每50步我们输出一下机器学习的误差。
session = tf.Session() init = tf.global_variables_initializer() session.run(init)for i in range(1000): # 训练 session.run(train_step, feed_dict={xs: x_data, ys: y_data}) if i % 50 == 0: # 输出误差 print(session.run(loss, feed_dict={xs: x_data, ys: y_data}))

训练的结果为:
0.45505300 0.01627140 0.00706166 0.00655277 0.00633455 0.00616494 0.00601985 0.00589210 0.00577352 0.00565306 0.00553244 0.00541153 0.00527759 0.00512993 0.00498288 0.00483543 0.00468928 0.00455415 0.00442295 0.00430277

通过输出的结果可以看出,误差在逐渐减小,我们的训练取得了很好的效果。

    推荐阅读