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

标签 python machine-learning scikit-learn tensorflow

我想知道是否有一种方法可以像这样从 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/

相关文章:

java - 我应该如何实现 SSL?

python - 类型错误 : '_IncompatibleKeys' object is not callable

python - Keras fit_generator() 与扩展序列的生成器返回的样本数多于总数

python - 如何并排连接数据框的多个移位行?

python - 多输出线性回归模型的访问权重/系数

python - 上采样不平衡数据集的小类

python - RSS feedparser 到 MySQL 数据库未填充

Python 更新函数内的值并重用它

python - 打印功能使多处理程序失败

algorithm - 用于预测体育节目结束时间的最佳算法