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

Python 为什么在Tensorflow简单神经网络示例中再添加一层会破坏它?,python,tensorflow,neural-network,activation-function,Python,Tensorflow,Neural Network,Activation Function,以下是(基于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.Var

以下是(基于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)

需要这些不相同权重的原因与反向传播的工作方式有关-层中权重的值决定该层将如何计算梯度。如果所有权重相同,则所有渐变都相同。这意味着所有权重更新都是相同的-所有内容都会在lockstep中更改,并且行为类似于隐藏层中有一个单个神经元(因为有多个神经元,所有神经元的参数都相同),它只能选择一个类。

尼尔很好地解释了如何解决问题,我将补充一点解释为什么会发生这种情况

问题不在于梯度都是相同的,而在于它们都是0。这是因为当
W=0
b=0
relu(Wx+b)=0
。甚至还有一个名字叫“死亡神经元”


网络根本没有进展,你是否训练它1步1分钟也无关紧要。结果与随机选择的结果没有什么不同,您看到的结果的准确度为0.11(如果您随机选择内容,您将得到0.10)。

是的,运行时的准确度为0.92。将权重初始化为
tf.random\u normal
约为0.88,而
tf.random\u uniform
约为0.91。谢谢,这很好用!)它还提供了比最初的1层示例更好的(~0.95)精度。