Jensen Shannon Divergence¶
- It is a symmetric divergence that quantifies between 2 probability distributions $P$ and $Q$. $$\begin{equation*}D_{JS}=\frac{D_{KL}\left(P||\frac{P+Q}{2}\right)+D_{KL}\left(Q||\frac{P+Q}{2}\right)}{2}\end{equation*}$$
- It is based on KL diergence.
Example¶
Let's suppose we're given the same dataset as to how many people like apple pie, orange pie and chocolate pie in 2 separate years.
| Year | Apple Pie | Orange Pie | Chocolate Pie |
|---|---|---|---|
| 2024 | 120 | 80 | 200 |
| 2025 | 150 | 65 | 220 |
Let's see if we can measure how much the data has changed from the year 2024 to 2025.
Loading and visualizing the data¶
In [1]:
import matplotlib.pyplot as plt
import numpy as np
# Example data
data_2024 = [120, 80, 200]
data_2025 = [150, 65, 220]
labels = ['Apple pie', 'Orange Pie', 'Chocolate Pie']
# Set the positions for the bars
x = np.arange(len(labels)) # Indices for x-axis (0, 1, 2, 3)
width = 0.35 # Width of each bar (adjust to control closeness)
# Create the figure and axis
fig, ax = plt.subplots()
# Plot the bars
ax.bar(x - width/2, data_2024, width, label = '2024', color = '#1f77b4')
ax.bar(x + width/2, data_2025, width, label = '2025', color = '#ff7f0e')
# Customize the plot
ax.set_xlabel('Categories')
ax.set_ylabel('Values')
ax.set_title('Data Chart 2024-2025')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
# Display the plot
plt.tight_layout()
plt.show()
Implementing KL divergence¶
In [2]:
import numpy as np
from typing import List
# Normalize the arrays to create probability distributions
def normalize_array(arr: List[float], epsilon_: float = 1e-10) -> List[float]:
arr_sum = np.sum(arr)
if arr_sum == 0:
raise ValueError("Array sum is zero, cannot normalize.")
# Add small epsilon to avoid division by zero
return (np.array(arr) + epsilon_) / (arr_sum + epsilon_ * len(arr))
# Compute KL divergence
def kl_divergence(p: List[float], q: List[float], epsilon_: float = 1e-10, normalize: bool = False) -> float:
normalized_p = (normalize_array(p, epsilon_ = epsilon_) if normalize else np.array(p))
normalized_q = (normalize_array(q, epsilon_ = epsilon_) if normalize else np.array(q))
# TODO: values less than epsilon are set to epsilon and values greater than 1 are set to 1
if normalize:
normalized_p = np.clip(normalized_p, epsilon_, 1)
normalized_q = np.clip(normalized_q, epsilon_, 1)
return np.sum(normalized_p * np.log10(normalized_p / normalized_q))
Implementing JS Divergence¶
In [3]:
from scipy.stats import entropy
def js_divergence(p: List[float], q: List[float], epsilon_: float = 1e-10, normalize: bool = False) -> float:
n, m = len(p), len(q)
if not n == m:
raise ValueError("Dimension of probability distributions must be same")
normalized_p = (normalize_array(p, epsilon_ = epsilon_) if normalize else np.array(p))
normalized_q = (normalize_array(q, epsilon_ = epsilon_) if normalize else np.array(q))
normalized_average = [(normalized_p[i] + normalized_q[i]) / 2.0 for i in range(n)]
d_pa = kl_divergence(normalized_p, normalized_average, epsilon_ = epsilon_, normalize = False)
d_qa = kl_divergence(normalized_q, normalized_average, epsilon_ = epsilon_, normalize = False)
return (d_pa + d_qa) / 2.0
Driver code¶
In [4]:
js_divergence(data_2024, data_2025, epsilon_ = 0.0, normalize = True)
Out[4]:
0.0011397527244117276
Verify using scipy¶
Note: The scipy implementation uses the formula
$$\begin{equation*}D_{JS}=\sqrt{\frac{D_{KL}\left(P||\frac{P+Q}{2}\right)+D_{KL}\left(Q||\frac{P+Q}{2}\right)}{2}}\end{equation*}$$
In [5]:
import numpy as np
from scipy.spatial.distance import jensenshannon
p = np.array(data_2024) / sum(data_2024)
q = np.array(data_2025) / sum(data_2025)
jsd = jensenshannon(p, q, base = 10)
In [6]:
jsd ** 2
Out[6]:
0.0011397527244117267