tf.metrics.accuracy用于计算模型输出的准确率
tf.metrics.accuracy(
labels,
predictions,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
return accuracy, update_op
参数:
labels 标签的真实值
predictions 标签的预测值
weights 每个值的权重
metrics_collections accuracy的集合
updates_collections update_op的集合
输出:
accuracy 上一个batch的准确率
update_op 加上本次训练数据后的准确率
例子:
import numpy as np
import pandas as pd
import tensorflow as tf
x = tf.placeholder(tf.float64, [5])
y = tf.placeholder(tf.int32, [5])
acc, acc_op = tf.metrics.accuracy(labels=y, predictions=tf.greater_equal(x,0.5))
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
v = sess.run([acc, acc_op], feed_dict={x: [0.1, 0.5, 0.4, 0.2, 0.6],
y: [1, 0, 0, 0, 1]}) #3/5
print(v)
v = sess.run([acc, acc_op], feed_dict={x: [0.1, 0.6, 0.6, 0.6, 0.3],
y: [1, 0, 0, 0, 1]}) #3/10
print(v)
v = sess.run([acc, acc_op], feed_dict={x: [0.1, 0.6, 0.6, 0.6, 0.3],
y: [1, 0, 0, 0, 1]}) #3/15
print(v)
v = sess.run([acc, acc_op], feed_dict={x: [0.1, 0.6, 0.6, 0.6, 0.3],
y: [1, 0, 0, 0, 1]}) #3/20
print(v)
sess.close()
'''
[0.0, 0.6]
[0.6, 0.3]
[0.3, 0.2]
[0.2, 0.15]
'''
如果有weights,分母为所有weights之和,分子为正确标签的weights之和
x = tf.placeholder(tf.float64, [5])
y = tf.placeholder(tf.int32, [5])
z = tf.placeholder(tf.float64, [5])
acc, acc_op = tf.metrics.accuracy(labels=y, predictions=tf.greater_equal(x,0.5), weights = z)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
v = sess.run([acc, acc_op], feed_dict={x:[0.1, 0.1, 0.1, 0.1, 0.1],
y:[0, 0, 0, 0, 0],
z:[1., 1., 1., 1., 0.]}) #4/4
print(v)
v = sess.run([acc, acc_op], feed_dict={x:[0.1, 0.1, 0.1, 0.1, 0.6],
y:[0, 0, 0, 0, 0],
z:[1., 1., 1., 1., 3.]}) #8/11
print(v)
sess.close()
'''
[0.0, 1.0]
[1.0, 0.72727275]
'''