Created
May 2, 2018 21:15
-
-
Save tokestermw/09b22481f56a3f1d4c58b76b96601301 to your computer and use it in GitHub Desktop.
Calculate a percentage from the confusion matrix in TensorFlow.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tensorflow as tf | |
from tensorflow.python.ops.metrics_impl import _streaming_confusion_matrix | |
# almost the same as | |
def confusion_matrix(labels, predictions, num_classes, weights=None): | |
total_cm, update_op = _streaming_confusion_matrix( | |
labels, predictions, num_classes, weights=weights) | |
def get_percentage(cm): | |
row_sums = tf.reduce_sum(tf.to_float(cm), axis=1) | |
# If the value of the denominator is 0, set it to 1 to avoid | |
# zero division. | |
denominator = tf.where( | |
tf.greater(row_sums, 0), row_sums, | |
tf.ones_like(row_sums)) | |
return tf.div(tf.to_float(cm), tf.reshape(denominator, (-1, 1))) | |
percent_cm = get_percentage(total_cm) | |
return percent_cm, update_op |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment