我使用CNN训练了MNIST
模型,但是当我在训练后用测试数据检查模型的准确性时,我发现我的准确性会提高。这是代码。
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
这让我很困惑,有人可以告诉我出了什么问题吗? 感谢您的耐心等待!
最佳答案
tf.metrics.accuracy
并不像你想象的那么微不足道。看一下它的文档:
The
accuracy
function creates two local variables,total
and
count
that are used to compute the frequency with whichpredictions
matcheslabels
. This frequency is ultimately returned asaccuracy
: an idempotent operation that simply dividestotal
bycount
.Internally, an
is_correct
operation computes aTensor
with elements 1.0 where the corresponding elements ofpredictions
andlabels
match and 0.0 otherwise. Thenupdate_op
incrementstotal
with the reduced sum of the product ofweights
andis_correct
, and it incrementscount
with the reduced sum ofweights
.For estimation of the metric over a stream of data, the function creates an
update_op
operation that updates these variables and returns theaccuracy
....
Returns:
- accuracy: A
Tensor
representing the accuracy, the value oftotal
divided bycount
.- update_op: An operation that increments the
total
andcount
variables appropriately and whose value matchesaccuracy
.
请注意,它返回一个元组,并且您获取第二项,即update_op
。连续调用 update_op
被视为数据流,这不是您想要做的(因为训练期间的每个评估都会影响 future 的评估)。事实上,这个运行指标是 pretty counter-intuitive .
您的解决方案是使用简单的精度计算。将此行更改为:
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(tf_y, axis=1), tf.argmax(output, axis=1)), tf.float32))
您将获得稳定的准确度计算。
关于machine-learning - TensorFlow:多次评估测试集但得到不同的精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45127327/