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

並且您將獲得穩定的準確度計算。

相關問題