为什么在 Tensorflow 简单神经网络示例中再添加一层会破坏它?



这是一个基本的Tensorflow网络示例(基于MNIST),完整的代码,其精度约为0.92:

import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run() # or 
tf.initialize_all_variables().run()
for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

问题:为什么添加一个额外的层,如下面的代码,会使它变得更糟,以至于它的精度下降到大约 0.11?

W = tf.Variable(tf.zeros([784, 100]))
b = tf.Variable(tf.zeros([100]))
h0 = tf.nn.relu(tf.matmul(x, W) + b)
W2 = tf.Variable(tf.zeros([100, 10]))
b2 = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(h0, W2) + b2)

该示例没有正确初始化权重,但是如果没有隐藏层,事实证明演示所做的有效线性softmax回归不受该选择的影响。将它们全部设置为零是安全的,但仅适用于单层网络

但是,当您建立更深层次的网络时,这是一个灾难性的选择。您必须使用神经网络权重的非相等初始化,通常的快速方法是随机的。

试试这个:

W = tf.Variable(tf.random_uniform([784, 100], -0.01, 0.01))
b = tf.Variable(tf.zeros([100]))
h0 = tf.nn.relu(tf.matmul(x, W) + b)
W2 = tf.Variable(tf.random_uniform([100, 10], -0.01, 0.01))
b2 = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(h0, W2) + b2)

您需要这些不相同的权重的原因与反向传播的工作方式有关 - 图层中的权重值决定了该图层将如何计算梯度。如果所有权重都相同,则所有梯度都将相同。这意味着所有的权重更新都是相同的——一切都在同步变化,行为类似于你在隐藏层中有一个神经元(因为你有多个神经元,所有神经元都有相同的参数),它实际上只能选择一个类。

Neil 很好地解释了如何解决您的问题,我将添加一些解释为什么会发生这种情况。

问题不在于梯度都相同,还在于它们都是 0。发生这种情况是因为relu(Wx + b) = 0W = 0b = 0.甚至还有一个名字——死神经元。

网络根本没有进展,你是否训练它 1 步 100 万并不重要。结果不会与随机选择不同,你看到它的准确率为 0.11(如果你随机选择东西,你会得到 0.10)。

最新更新