在简单的多层 FFNN 中,只有 ReLU 激活函数不收敛

2023-12-13

我正在学习张量流、深度学习并尝试各种激活函数。

我为 MNIST 问题创建了一个多层 FFNN。大部分基于tensorflow官方网站的教程,只是添加了3个隐藏层。

我实验过的激活函数有:tf.sigmoid, tf.nn.tanh, tf.nn.softsign, tf.nn.softmax, tf.nn.relu. Only tf.nn.relu不收敛,网络输出随机噪声(测试精度约为10%)。以下是我的源代码:

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])

W0 = tf.Variable(tf.random_normal([784, 200]))
b0 = tf.Variable(tf.random_normal([200]))
hidden0 = tf.nn.relu(tf.matmul(x, W0) + b0)

W1 = tf.Variable(tf.random_normal([200, 200]))
b1 = tf.Variable(tf.random_normal([200]))
hidden1 = tf.nn.relu(tf.matmul(hidden0, W1) + b1)

W2 = tf.Variable(tf.random_normal([200, 200]))
b2 = tf.Variable(tf.random_normal([200]))
hidden2 = tf.nn.relu(tf.matmul(hidden1, W2) + b2)

W3 = tf.Variable(tf.random_normal([200, 10]))
b3 = tf.Variable(tf.random_normal([10]))
y = tf.matmul(hidden2, W3) + b3

y_ = tf.placeholder(tf.float32, [None, 10])

cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy)
with tf.Session() as session:
    session.run(tf.global_variables_initializer())
    for _ in range(10000):
        batch_xs, batch_ys = mnist.train.next_batch(128)
        session.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
        if _ % 1000 == 0:
            correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
            accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
            print(_, session.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print('final:', session.run(accuracy, feed_dict={x: mnist.test.images,
            y_: mnist.test.labels}))

代码输出如下:

0 0.098
1000 0.098
2000 0.098
3000 0.098
4000 0.098
5000 0.098
6000 0.098
7000 0.098
8000 0.098
9000 0.098
final: 0.098

If tf.nn.relu替换为其他激活函数后,网络精度逐渐提高(尽管最终精度不同),这是预期的。

我在五月份的教科书/教程中读到,ReLU 应该是激活函数的第一个候选者。

我的问题是为什么 ReLU 在我的网络中不起作用?或者我的程序根本就是错误的?


您正在使用Relu计算激活的激活函数如下,

最大值(特征,0)

由于它输出最大值,这有时会导致梯度爆炸.

Gradientdecnt 优化器通过以下方式更新权重,

Δwij = −η ∂Ei/ ∂wij

where η是学习率并且∂Ei/∂wij是损失相对于重量的偏导数。什么时候最大值变得越来越大,偏导数也变得越来越大,导致梯度爆炸。因此,正如您在等式中观察到的那样,您需要调整学习率(η)来克服这种情况。

一个常见的规则是降低学习率,通常每次降低 10 倍。

对于您的情况,将学习率设置为 0.001 将会提高准确性。

希望这可以帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在简单的多层 FFNN 中,只有 ReLU 激活函数不收敛 的相关文章

随机推荐