在 tensorflow 中实现 MLP

Implement MLP in tensorflow

我想使用 tensorflow 实现 https://www.coursera.org/learn/machine-learning 中教授的 MLP 模型。这是实现。

# one hidden layer MLP

x = tf.placeholder(tf.float32, shape=[None, 784])
y = tf.placeholder(tf.float32, shape=[None, 10])

W_h1 = tf.Variable(tf.random_normal([784, 512]))
h1 = tf.nn.sigmoid(tf.matmul(x, W_h1))

W_out = tf.Variable(tf.random_normal([512, 10]))
y_ = tf.matmul(h1, W_out)

# cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(y_, y)
cross_entropy = tf.reduce_sum(- y * tf.log(y_) - (1 - y) * tf.log(1 - y_), 1)
loss = tf.reduce_mean(cross_entropy)
train_step = tf.train.GradientDescentOptimizer(0.05).minimize(loss)

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# train
with tf.Session() as s:
    s.run(tf.initialize_all_variables())

    for i in range(10000):
        batch_x, batch_y = mnist.train.next_batch(100)
        s.run(train_step, feed_dict={x: batch_x, y: batch_y})

        if i % 100 == 0:
            train_accuracy = accuracy.eval(feed_dict={x: batch_x, y: batch_y})
            print('step {0}, training accuracy {1}'.format(i, train_accuracy))

但是,它不起作用。我认为图层的定义是正确的,但问题出在 cross_entropy 中。如果我使用第一个,那个被注释掉,模型收敛得很快;但是如果我使用第二个,我 think/hope 是前一个方程的平移,模型将不会收敛。

如果您想查看成本等式,可以在 here 找到它。

更新

我已经使用 numpyscipy 实现了相同的 MLP 模型,并且它有效。

在tensorflow代码中,我在训练循环中添加了一行print,发现y_中的所有元素都是 nan...我认为是算术溢出之类的引起的。

我认为的问题是 nn.sigmoid_cross_entropy_with_logits 期望非标准化结果,而您将其替换为 cross_entropy = tf.reduce_sum(- y * tf.log(y_) - (1 - y) * tf.log(1 - y_), 1)

的函数

期望 y_ 在 0 和 1 之间归一化(通过 sigmoid)

尝试替换

y_ = tf.matmul(h1, W_out)

y_ = tf.nn.sigmoid(tf.matmul(h1, W_out))

可能是 0*log(0) 问题。

正在替换

cross_entropy = tf.reduce_sum(- y * tf.log(y_) - (1 - y) * tf.log(1 - y_), 1)

cross_entropy = tf.reduce_sum(- y * tf.log(tf.clip_by_value(y_, 1e-10, 1.0)) - (1 - y) * tf.log(tf.clip_by_value(1 - y_, 1e-10, 1.0)), 1)

请参阅