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

Mas*_*nya 4 python neural-network tensorflow activation-function

这是一个基本的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}))
Run Code Online (Sandbox Code Playgroud)

问题:为什么添加一个额外的图层,如下面的代码所示,使得它更糟糕,它降低到约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)
Run Code Online (Sandbox Code Playgroud)

Nei*_*ter 6

该示例未正确初始化权重,但没有隐藏层,结果证明演示所做的有效线性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)
Run Code Online (Sandbox Code Playgroud)

您需要这些不相同权重的原因与背向传播的工作原理有关 - 图层中权重的值决定了图层计算渐变的方式.如果所有权重都相同,那么所有梯度都是相同的.这又意味着,所有的更新权重都是一样的-步调一致一切都变了,并且行为类似,如果你有一个单一的隐藏层神经元(因为你有多个神经元都具有相同的参数),可有效地只能选择一节课.