how is jsd calucalted
- User
how is jsd calucalted
- Assistant
The Jensen–Shannon Divergence (JSD) is a symmetric, smoothed version of the Kullback–Leibler (KL) divergence that measures how different two probability distributions are. Here’s how it’s calculated step-by-step:
-
Start with two probability distributions Let’s say you have: P=(p1,p2,…,pn)P = (p_1, p_2, \dots, p_n)P=(p1,p2,…,pn) Q=(q1,q2,…,qn)Q = (q_1, q_2, \dots, q_n)Q=(q1,q2,…,qn) Both must sum to 1 (valid probability distributions) and have the same support.
-
Compute the average distribution M=12(P+Q)M = \frac{1}{2}(P + Q)M=21(P+Q) So: mi=pi+qi2m_i = \frac{p_i + q_i}{2}mi=2pi+qi
-
Compute KL divergence from each distribution to MMM KL divergence is: KL(P∥M)=∑ipilog2pimiKL(P \parallel M) = \sum_i p_i \log_2 \frac{p_i}{m_i}KL(P∥M)=i∑pilog2mipi KL(Q∥M)=∑iqilog2qimiKL(Q \parallel M) = \sum_i q_i \log_2 \frac{q_i}{m_i}KL(Q∥M)=i∑qilog2miqi We usually take log base 2 for interpretability (result in bits), but natural log (base eee) is also common.
-
- User
how is it here: def jsd(P, Q, eps=1e-12): # Normalize to probabilities (L1 norm) _P = P / torch.norm(P, p=1, dim=-1, keepdim=True) _Q = Q / torch.norm(Q, p=1, dim=-1, keepdim=True)
# Mean distribution _M = 0.5 * (_P + _Q) # Clamp to avoid log(0) _P = torch.clamp(_P, eps, 1.0) _Q = torch.clamp(_Q, eps, 1.0) _M = torch.clamp(_M, eps, 1.0) # Compute JSD using KL Divergence jsd = 0.5 * (torch.sum(_P * torch.log(_P / _M), dim=-1) + torch.sum(_Q * torch.log(_Q / _M), dim=-1)) return jsd - Assistant
Got it — in your code, they’re implementing the exact math I explained, but in PyTorch and with a few practical adjustments for numerical stability. Let’s walk through it line by line:
- Normalization pythonCopyEdit_P = P / torch.norm(P, p=1, dim=-1, keepdim=True) _Q = Q / torch.norm(Q, p=1, dim=-1, keepdim=True)
torch.norm(..., p=1, ...) computes the L1 norm (sum of absolute values) along the last dimension.
This ensures that _P and _Q are probability distributions (sum to 1).
This is important because KL divergence and JSD require probabilities.
- User
so for a neural netweork who will it look
- Assistant
If you drop this jsd() function into a neural network pipeline, it’s going to be applied to the network’s outputs (or some intermediate feature representation turned into probabilities). Let me show you how it might look in practice for a network:
Example: Neural Network + JSD Let’s say you have:
Original input xxx
Reconstructed input x^\hat{x}x^ from an autoencoder
You pass both through the same classifier network to get probability distributions:
- User
is this correct for jsd threhold calculation: def compute_jsd_threshold(detector_model, classifier_model, dataloader, device='cpu', temperature=2.0): detector_model.eval() classifier_model.eval()
# Store all JSD values per class jsd_per_class = defaultdict(list) total_jsd = 0.0 total_samples = 0 with torch.no_grad(): for x, labels in dataloader: x = x.to(device) labels = labels.to(device) # Original logits & probabilities logits_x = classifier_model(x) probs_x = softmax_with_temperature(logits_x, T=temperature) # Reconstructed input x_recon = detector_model(x) logits_recon = classifier_model(x_recon) probs_recon = softmax_with_temperature(logits_recon, T=temperature) # JSD for the batch (vector) batch_jsd = jsd(probs_x, probs_recon) # shape: (B,) total_jsd += batch_jsd.sum().item() total_samples += x.size(0) # Append each sample's JSD into its class list for lbl, val in zip(labels.cpu().tolist(), batch_jsd.cpu().tolist()): jsd_per_class[lbl].append(val) avg_jsd = total_jsd / total_samples # Compute average per class avg_jsd_per_class = {cls: sum(vals)/len(vals) for cls, vals in jsd_per_class.items()} print("Overall Avg JSD:", avg_jsd) print("Per-Class Avg JSD:") for cls, val in avg_jsd_per_class.items(): print(f" Class {cls}: {val:.6f}") return avg_jsd - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.