gpt4 book ai didi

machine-learning - 在 tensorflow 中实现 MLP

转载 作者:行者123 更新时间:2023-11-30 08:54:55 28 4
gpt4 key购买 nike

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

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

但是,它不起作用。我认为层的定义是正确的,但问题出在交叉熵上。如果我使用第一个,那个被注释掉了,模型很快收敛;但如果我使用第二个(我认为/希望是前一个方程的翻译),模型将不会收敛。

如果您想查看成本方程,可以在 here 找到它。 .

更新

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

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

最佳答案

这可能是 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)

请参阅Tensorflow NaN bug? .

关于machine-learning - 在 tensorflow 中实现 MLP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078027/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com