Monday, 20 January 2020

Keras Accuracy Functions Test

Source Code:
%tensorflow_version 2.x
%reset -f

#Libs
import tensorflow as tf;

#PROGRAMME ENTRY POINT==========================================================
a  = tf.metrics.Accuracy();
ba = tf.metrics.BinaryAccuracy();
ca = tf.metrics.CategoricalAccuracy();

#Y is expected, U is output
#Accuracy (use with Heaviside or integer outputs)
Y = tf.constant([[0],[1],[1],[0  ]], tf.float32);
U = tf.constant([[0],[1],[1],[0.1]], tf.float32);
print("Accuracy:",a(Y,U)); #Perfectly equal only, 0.1 is NOT 0

#BinaryAccuracy (use with single Sigmoid output)
Y = tf.constant([[0],[1],[1],[0  ]], tf.float32);
U = tf.constant([[0],[1],[1],[0.1]], tf.float32); 
print("BinaryAccuracy:",ba(Y,U)); #Threshold 0.5, 0.1 is still 0

#CategoricalAccuracy (use with multi-prob Softmax output)
Y = tf.constant([[0,1,0],[001  ]], tf.float32);
U = tf.constant([[0,1,0],[000.1]], tf.float32); 
#Considered as:           0, 0, 1 
#2 zeros prefix 0.1, so 0.1 is still max prob and considered as 1, means correct
print("CategoricalAccuracy:",ca(Y,U));

Y = tf.constant([[0,1,0],[00,   1  ]], tf.float32);
U = tf.constant([[0,1,0],[00.30.1]], tf.float32); 
#Considered as:           0, 1,   0
#0.2 is max prob and considered as 1, so the second sample is partially wrong
#0.1 is considered as 0 coz 0.1 < 0.3/2
print("CategoricalAccuracy:",ca(Y,U));
#EOF

Result:
Accuracy: tf.Tensor(0.75, shape=(), dtype=float32)
BinaryAccuracy: tf.Tensor(1.0, shape=(), dtype=float32)
CategoricalAccuracy: tf.Tensor(1.0, shape=(), dtype=float32)
CategoricalAccuracy: tf.Tensor(0.75, shape=(), dtype=float32)

No comments:

Post a Comment