记录一下分别用:tf.equal();tf.nn.in_top_k();tf.metrics.accuracy() 计算分类准确率accuracy的过程。
* 要求参数x和y有相同的类型
import tensorflow as tf
batch_size = 8
class_num = 10 # 类别数量
# 定义一个logits为神经网络预测的标签结果,shape:(batch_size,)
logits = tf.constant([0, 5, 9, 1, 7, 1, 0, 1])
# 定义一个labels为真实样本号,这里设为全1,shape:(batch_size,)
labels = tf.ones((batch_size,), dtype=tf.int32)
# 使用tf.equal()计算分类准确率,返回的是bool类型的Tensor来判断对应位的值是否相等
correct_prediction = tf.equal(logits, labels)
# 将bool值转为float类型(即0或1)再求均值即为准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
print(logits.eval())
print(labels.eval())
print(correct_prediction.eval())
print("accuracy:{}".format(accuracy.eval()))
打印结果为:
[0 5 9 1 7 1 0 1]
[1 1 1 1 1 1 1 1]
[False False False True False True False True]
accuracy:0.375
* 要求参数'predictions'为float32类型,且shape为(batch_size, class_num)
* 要求参数'targets'为int32或int64类型,且shape为(batch_size,)
import tensorflow as tf
batch_size = 8
class_num = 10 # 类别数量
# 定义一个logits为神经网络预测的标签结果,shape:(batch_size, class_num)
logits = tf.constant([0, 5, 9, 1, 7, 1, 0, 1])
# 通过one_hot函数将(batch_size, )转为(batch_size, class_num)
logits = tf.one_hot(indices=tf.cast(logits, tf.int32), depth=class_num)
# 定义一个labels为真实样本号,这里设为全1,shape:(batch_size,)
labels = tf.ones((batch_size, ), dtype=tf.int32)
# 使用tf.nn.in_top_k()计算分类准确率,当参数k=1时等价于tf.equal()
# 返回的是bool类型的Tensor来判断对应位的值是否相等
correct_prediction = tf.nn.in_top_k(logits, labels, 1)
# 将bool值转为float类型(即0或1)再求均值即为准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
print(logits.eval())
print(labels.eval())
print(correct_prediction.eval())
print("accuracy:{}".format(accuracy.eval()))
打印结果为:
[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]]
[1 1 1 1 1 1 1 1]
[False False False True False True False True]
accuracy:0.375
* 要求参数labels要和参数predictions的shape相同
import tensorflow as tf
batch_size = 8
class_num = 10 # 类别数量
# 定义一个logits为神经网络预测的标签结果,shape:(batch_size, )
logits = tf.constant([0, 5, 9, 1, 7, 1, 0, 1])
# 定义一个labels为真实样本号,这里设为全1,shape:(batch_size, )
labels = tf.ones((batch_size, ), dtype=tf.int32)
# 使用tf.metrics.accuracy()计算分类准确率,返回的第一个值即为分类准确率
acc, acc_op = tf.metrics.accuracy(logits, labels)
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
print(logits.eval())
print(labels.eval())
print("accuracy:{}".format(acc_op.eval()))
打印结果为:
[0 5 9 1 7 1 0 1]
[1 1 1 1 1 1 1 1]
accuracy:0.375