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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With