1

我已经使用CNN训练了MNIST的模型,但是当我在训练后用测试数据检查模型的准确性时,我发现我的准确性会提高。这是代码。TensorFlow:多次评估测试集,但得到不同的准确性

BATCH_SIZE = 50 
LR = 0.001    # learning rate 
mnist = input_data.read_data_sets('./mnist', one_hot=True) # they has been normalized to range (0,1) 
test_x = mnist.test.images[:2000] 
test_y = mnist.test.labels[:2000] 

def new_cnn(imageinput, inputshape): 
    weights = tf.Variable(tf.truncated_normal(inputshape, stddev = 0.1),name = 'weights') 
    biases = tf.Variable(tf.constant(0.05, shape = [inputshape[3]]),name = 'biases') 
    layer = tf.nn.conv2d(imageinput, weights, strides = [1, 1, 1, 1], padding = 'SAME') 
    layer = tf.nn.relu(layer) 
    return weights, layer 

tf_x = tf.placeholder(tf.float32, [None, 28 * 28]) 
image = tf.reshape(tf_x, [-1, 28, 28, 1])    # (batch, height, width, channel) 
tf_y = tf.placeholder(tf.int32, [None, 10])   # input y 

# CNN 
weights1, layer1 = new_cnn(image, [5, 5, 1, 32]) 
pool1 = tf.layers.max_pooling2d(
    layer1, 
    pool_size=2, 
    strides=2, 
)   # -> (14, 14, 32) 
weight2, layer2 = new_cnn(pool1, [5, 5, 32, 64]) # -> (14, 14, 64) 
pool2 = tf.layers.max_pooling2d(layer2, 2, 2) # -> (7, 7, 64) 
flat = tf.reshape(pool2, [-1, 7 * 7 * 64])   # -> (7*7*64,) 
hide = tf.layers.dense(flat, 1024, name = 'hide')    # hidden layer 
output = tf.layers.dense(hide, 10, name = 'output') 
loss = tf.losses.softmax_cross_entropy(onehot_labels=tf_y, logits=output)   # compute cost 
accuracy = tf.metrics.accuracy(labels=tf.argmax(tf_y, axis=1), predictions=tf.argmax(output, axis=1),)[1] 
train_op = tf.train.AdamOptimizer(LR).minimize(loss) 



sess = tf.Session() 
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) # the local var is for accuracy 
sess.run(init_op)  # initialize var in graph 
saver = tf.train.Saver() 
for step in range(101): 
    b_x, b_y = mnist.train.next_batch(BATCH_SIZE) 
    _, loss_ = sess.run([train_op, loss], {tf_x: b_x, tf_y: b_y}) 
    if step % 50 == 0: 
     print(loss_) 
     accuracy_, loss2 = sess.run([accuracy, loss], {tf_x: test_x, tf_y: test_y }) 
     print('Step:', step, '| test accuracy: %f' % accuracy_) 

为了简化问题,我只使用了100次训练迭代。测试集的最终准确度大约为0.655000

但是当我运行下面的代码:

for i in range(5): 
    accuracy2 = sess.run(accuracy, {tf_x: test_x, tf_y: test_y }) 
    print(sess.run(weight2[1,:,0,0])) # To show that the model parameters won't update 
    print(accuracy2) 

输出是

[-0.06928255 -0.13498515 0.01266837 0.05656774 0.09438231] 
0.725875 
[-0.06928255 -0.13498515 0.01266837 0.05656774 0.09438231] 
0.7684 
[-0.06928255 -0.13498515 0.01266837 0.05656774 0.09438231] 
0.79675 
[-0.06928255 -0.13498515 0.01266837 0.05656774 0.09438231] 
0.817 
[-0.06928255 -0.13498515 0.01266837 0.05656774 0.09438231] 
0.832187 

这使我困惑,有人可以告诉我,什么是错的? 感谢您的耐心等待!

+0

[每个推理的相同预测](https://stackoverflow.com/questions/44952929/same-prediction-for-each-inference) – user1735003

+0

请包括完整的代码。例如wgat你使用keep_prob? – lejlot

+0

@lejlot抱歉,我删除了冗余部分。 – DennngP

回答

0

tf.metrics.accuracy并不像您想象的那么微不足道。在它的文档看看:

accuracy函数创建一个用于计算频率两个局部变量,total
countpredictions比赛labels。该频率最终为 ,返回为accuracy:幂等性操作,简单地将 total除以count

在内部,is_correct操作计算一个Tensor与 元件1.0其中predictionslabels匹配和0.0的相应的元件,否则。然后update_op增量 totalweightsis_correct产品的降低的总和,它与 weights减小的总和增量count

在过去的数据流的度量的估计,该函数 创建update_op操作,更新这些变量和 返回accuracy

...

返回:

  • 准确度:Tensor代表准确,total值由count分 。
  • update_op:适当增加totalcount变量 并且其值匹配accuracy的操作。

注意,它返回一个元组和你采取的第二项,即update_op。连续调用update_op被视为数据流,这不是您打算做的事情(因为培训期间中的每个评估都会影响将来的评估)。实际上,这个运行指标是pretty counter-intuitive

您的解决方案是使用普通的简单精度计算。将此行更改为:

accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(tf_y, axis=1), tf.argmax(output, axis=1)), tf.float32)) 

并且您将获得稳定的准确度计算。

相关问题