Skip to content

Instantly share code, notes, and snippets.

@prerakmody
Created January 13, 2022 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prerakmody/25a81846b68cff8d66f3d0a7f124bf45 to your computer and use it in GitHub Desktop.
Save prerakmody/25a81846b68cff8d66f3d0a7f124bf45 to your computer and use it in GitHub Desktop.
Area Under the Curve (AUC) calculation
"""
References
1. Calculating area under the curve (AUC) using Riemann Sum - https://en.wikipedia.org/wiki/Riemann_sum
2. https://scikit-learn.org/stable/modules/generated/sklearn.metrics.auc.html#sklearn.metrics.auc
- it uses np.trapz()
- Code: https://github.com/numpy/numpy/blob/v1.22.0/numpy/lib/function_base.py#L4686-L4797
3. Other methods implemented in TFlow
- https://wikidocs.net/24605
- Note: This method only works right when we provide a list x that has evenly spaced values
"""
import os
import pdb
import sklearn
import sklearn.metrics
import numpy as np
from math import pi
import matplotlib.pyplot as plt
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import tensorflow as tf
# Trapezoidal Method
## Note that dx is fixed in this case so will give incorrect results for when x does not have evenly spaced values
# def integral(y, x):
# dx = (x[-1] - x[0]) / (int(x.shape[0]) - 1)
# print (dx)
# return ((y[0] + y[-1])/2 + tf.reduce_sum(y[1:-1])) * dx
def integral(y, x):
dx = x[1:]-x[:-1]
dy = (y[:-1] + y[1:])/2
return tf.math.reduce_sum(dx*dy)
if 0:
a = tf.constant(0, dtype=tf.float64)
b = tf.constant(pi/2, dtype=tf.float64)
x = tf.linspace(a, b, 2**5+1)
elif 0:
x = tf.constant([0.0, 0.05] + np.arange(0.1,1.0,0.05).tolist() + [1.0])
elif 1:
x = tf.constant(np.arange(0.00001, 0.0001, 0.00001).tolist() + np.arange(0.0001, 0.001, 0.0001).tolist() + np.arange(0.001, 0.01, 0.001).tolist() + np.arange(0.01, 0.1, 0.005).tolist() + np.arange(0.1,1.0,0.05).tolist() + [1.0])
y = tf.sin(x)
result_tflow = integral(y, x)
result_sklearn = sklearn.metrics.auc(x, y)
result_numpy = np.trapz(y, x)
print (' - TFlow : {:.7f}'.format(result_tflow))
print (' - Sklearn: {:.7f}'.format(result_sklearn))
print (' - Numpy : {:.7f}'.format(result_numpy))
plt.plot(x, y)
plt.show(block=False)
pdb.set_trace()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment