Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class wise precision and recall for multi class classification in Tensorflow?

Is there a way to get per class precision or recall when doing multiclass classification using tensor flow.

For example, If I have y_true and y_pred from each batch, is there a functional way to get precision or recall per class if I have more than 2 classes.

like image 787
prateek agrawal Avatar asked Aug 10 '17 03:08

prateek agrawal


People also ask

How do you calculate precision and recall for multiclass classification?

In an imbalanced classification problem with more than two classes, precision is calculated as the sum of true positives across all classes divided by the sum of true positives and false positives across all classes.

Can we calculate precision and recall for multi-class problems?

We can also use Precision and Recall for multi-class problems. A confusion matrix can be constructed to represent the results of a 3-class model. Precision and Recall are calculated for Class 2 and Class 3 in the same way. For data with more than 3 classes, the metrics are calculated using the same methodology.

How do you find the accuracy of a multi-class classification?

Accuracy is one of the most popular metrics in multi-class classification and it is directly computed from the confusion matrix. The formula of the Accuracy considers the sum of True Positive and True Negative elements at the numerator and the sum of all the entries of the confusion matrix at the denominator.


1 Answers

Here's a solution that is working for me for a problem with n=6 classes. If you have many more classes this solution is probably slow and you should use some sort of mapping instead of a loop.

Assume you have one hot encoded class labels in rows of tensor labels and logits (or posteriors) in tensor labels. Then, if n is the number of classes, try this:

y_true = tf.argmax(labels, 1)
y_pred = tf.argmax(logits, 1)

recall = [0] * n
update_op_rec = [[]] * n

for k in range(n):
    recall[k], update_op_rec[k] = tf.metrics.recall(
        labels=tf.equal(y_true, k),
        predictions=tf.equal(y_pred, k)
    )

Note that inside tf.metrics.recall, the variables labels and predictions are set to boolean vectors like in the 2 variable case, which allows the use of the function.

like image 181
Avi Avatar answered Sep 19 '22 08:09

Avi