Skip to content

Instantly share code, notes, and snippets.

@rahulbhadani
Forked from larsmans/hellinger.py
Created May 19, 2023 03:31
Show Gist options
  • Save rahulbhadani/94bc60e3102a84f8f3f8b9343379ea21 to your computer and use it in GitHub Desktop.
Save rahulbhadani/94bc60e3102a84f8f3f8b9343379ea21 to your computer and use it in GitHub Desktop.
Hellinger distance for discrete probability distributions in Python
"""
Three ways of computing the Hellinger distance between two discrete
probability distributions using NumPy and SciPy.
"""
import numpy as np
from scipy.linalg import norm
from scipy.spatial.distance import euclidean
_SQRT2 = np.sqrt(2) # sqrt(2) with default precision np.float64
def hellinger1(p, q):
return norm(np.sqrt(p) - np.sqrt(q)) / _SQRT2
def hellinger2(p, q):
return euclidean(np.sqrt(p), np.sqrt(q)) / _SQRT2
def hellinger3(p, q):
return np.sqrt(np.sum((np.sqrt(p) - np.sqrt(q)) ** 2)) / _SQRT2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment