Home > Software design >  How to use tensorflow metrics Accuracy for multiclass?
How to use tensorflow metrics Accuracy for multiclass?

Time:12-10

My goal is to understand how tensorflow calculate accuracy.

The problem is, the expected output is 2/3. Because there are 3 rows, 2 rows correctly predict the label.

y_true = np.array([
    [0,1,0,0], # 1st row
    [1,0,0,0], # nth row
    [0,1,0,0],
])

The actual output is 0.8333334.

The code

import tensorflow as tf
import numpy as np
m = tf.keras.metrics.Accuracy()
y_true = np.array([
    [0,1,0,0], # 1st row
    [1,0,0,0], # nth row
    [0,1,0,0],
])
y_pred = np.array([
    [0,1,0,0],
    [1,0,0,0],
    [1,0,0,0],
])
m.update_state(y_true, 
               y_pred)
m.result().numpy()

CodePudding user response:

There are total 12 elements out of which 10 are correct - 10/12 = 0.8333

What you want is,

m.update_state(tf.argmax(y_true, axis=-1), 
               tf.argmax(y_pred, axis=-1))
#results in 2/3
  • Related