gpt4 book ai didi

python - TensorFlow Precision/Recall/F1 分数和混淆矩阵

转载 作者:IT老高 更新时间:2023-10-28 22:01:37 27 4
gpt4 key购买 nike

我想知道是否有一种方法可以像这样从 scikit learn 包中实现不同的分数功能:

from sklearn.metrics import confusion_matrix
confusion_matrix(y_true, y_pred)

进入 tensorflow 模型以获得不同的分数。

with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
init = tf.initialize_all_variables()
sess.run(init)
for epoch in xrange(1):
avg_cost = 0.
total_batch = len(train_arrays) / batch_size
for batch in range(total_batch):
train_step.run(feed_dict = {x: train_arrays, y: train_labels})
avg_cost += sess.run(cost, feed_dict={x: train_arrays, y: train_labels})/total_batch
if epoch % display_step == 0:
print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)

print "Optimization Finished!"
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print "Accuracy:", batch, accuracy.eval({x: test_arrays, y: test_labels})

我是否必须再次运行 session 才能获得预测?

最佳答案

您实际上并不需要 sklearn 来计算精度/召回率/f1 分数。通过查看公式,您可以轻松地以 TF 方式表达它们:

enter image description here

现在,如果您将 actualpredicted 值作为 0/1 的向量,您可以使用 tf.count_nonzero 计算 TP、TN、FP、FN :

TP = tf.count_nonzero(predicted * actual)
TN = tf.count_nonzero((predicted - 1) * (actual - 1))
FP = tf.count_nonzero(predicted * (actual - 1))
FN = tf.count_nonzero((predicted - 1) * actual)

现在您的指标很容易计算:

precision = TP / (TP + FP)
recall = TP / (TP + FN)
f1 = 2 * precision * recall / (precision + recall)

关于python - TensorFlow Precision/Recall/F1 分数和混淆矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35365007/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com