首页 文章

在Tensorflow中使用MNIST上的一个隐藏层训练完全连接的网络

提问于
浏览
0

我刚刚使用Tensorflow进入机器学习,在完成MNIST初学者教程后,我想通过插入一个隐藏层来提高该简单模型的准确性 . 从本质上讲,我决定直接从Micheal Nielsen关于神经网络和深度学习的书的第一章中复制网络架构(参见here) .

尼尔森的代码对我来说很好,但是,我没有使用以下Tensorflow代码获得可比较的结果 . 它应该 - 如果我没有弄错的话 - 完全实现尼尔森建议的模型:

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)


def weight_variable(shape):
    initial = tf.random_normal(shape)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.random_normal(shape)
    return tf.Variable(initial)


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

#hidden layer
W_fc1 = weight_variable([784, 30])
b_fc1 = bias_variable([30])
h_fc1 = tf.sigmoid(tf.matmul(x, W_fc1) + b_fc1)

#output layer
W_fc2 = weight_variable([30, 10])
b_fc2 = bias_variable([10])
y = tf.sigmoid(tf.matmul(h_fc1, W_fc2) + b_fc2)

y_ = tf.placeholder(tf.float32, [None, 10])
loss = tf.reduce_mean(tf.reduce_sum(tf.pow(y_ - y, 2), reduction_indices=[1])) #I also tried simply tf.nn.l2_loss(y_ - y)
train_step = tf.train.GradientDescentOptimizer(3.0).minimize(loss)

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

def get_accuracy():
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    return sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})

for i in range(30):
    batch_xs, batch_ys = mnist.train.next_batch(10)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
    print("Epoch {} accuracy: {:.2f}%".format(i+1, get_accuracy() * 100))

经过30个时期的训练后,我得到了约17%的准确率 . 使用尼尔森的代码,经过一个训练时期后,我获得了91%的准确率 .

显然我错过了一些东西 . 我试图提高准确性,并设法通过更长时间的培训将其提高到约60%,但同一网络应该给出类似的结果,即使它可能使用不同的后端代码 . 我也尝试过使用超参数但没有达到任何可比较的结果 .

你在我的代码中发现了什么缺陷吗?

1 回答

  • 2

    正如suharshs所提到的,看起来你的问题是由对术语时代的误解造成的 . 虽然不是严格的情况,但是一个纪元通常是整个训练数据集的单次迭代 . 如果你再看一下尼尔森的代码,你会看到这反映在SGD方法中 . 单个时期涉及遍历整个training_data,其被分成小批量 . 您的每个时期实际上是一个小批量的大小,只有10个样本 .

相关问题