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

2024-04-27 03:39:59 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是a basic Tensorflow network example(基于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左右?在

^{pr2}$

Tags: run代码importreduceinputdatatftensorflow
2条回答

这个例子没有正确初始化权重,但是没有隐藏层,结果证明演示所做的有效线性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)

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

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

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

网络根本没有进展,不管你是否训练它1步或1步。结果与随机选择没有什么不同,你可以看到你的准确度为0.11(如果你随机选择的东西,你会得到0.10)。在

相关问题 更多 >