Comparison.score.jensen_shannon_divergence
Comparison.score.jensen_shannon_divergence ¶
jensen_shannon_divergence(
alpha: float = 1,
base: float = 2,
weight_ref: float = 0.5,
weight_cmp: float = 0.5,
reference_score: float | Literal["mean"] | Expr = 0,
) -> Comparison
Calculates the Jensen-Shannon divergence (JSD) between the reference and comparison corpora.
The JSD is a symmetric, bounded measure of how two corpora differ. It is computed by averaging the Kullback-Leibler divergence of each corpus against a synthetic mixture corpus representing the combination of both corpora. This implementation generalizes the JSD through an order parameter \(\alpha\). When \(\alpha < 1\), more weight is given to rare tokens; when \(\alpha > 1\), more weight is given to common tokens.
Example
When the reference_score is 0 and \(\alpha = 1\), the contribution \(\delta_\tau\) of a
token \(\tau\) is:
where \(p_\tau^{(R)}\) and \(p_\tau^{(C)}\) are the normalized frequencies of token \(\tau\) in \(R\) and \(C\) respectively, the reference and comparison corpora, and \(p_\tau^{(M)} = \pi_R \, p_\tau^{(R)} + \pi_C \, p_\tau^{(C)}\) with weights \(\pi_R\) and \(\pi_C\) such that \(\pi_R + \pi_C = 1\). For \(\alpha = 1\), each token's contribution is always non-negative.
When the reference_score is 0 and \(\alpha \neq 1\), the contribution of the token is:
where \(\Phi^{(\text{ref})}\) is the user-provided reference score, and
Reference
For more details, see the following paper:
Gallagher, R. J., Frank, M. R., Mitchell, L., Schwartz, A. J., Reagan, A. J., Danforth, C. M., & Dodds, P. S. (2021). Generalized word shift graphs: a method for visualizing and explaining pairwise comparisons between texts. EPJ Data Science, 10(1), 4.
See Also
| Score | Description |
|---|---|
Comparison.score.kullback_leibler_divergence |
Scores corpora using an asymmetric entropy-based divergence |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
float
|
Order of the generalized entropy. \(\alpha = 1\) recovers the standard JSD. Larger values place more weight on common tokens, and smaller values place more weight on rare tokens |
1
|
|
float
|
Base of the logarithms used to calculate the JSD when \(\alpha = 1\). Ignored otherwise |
2
|
|
float
|
Mixture weight \(\pi_R\) for the reference corpus |
0.5
|
|
float
|
Mixture weight \(\pi_C\) for the comparison corpus |
0.5
|
|
float | Literal['mean'] | Expr
|
Baseline against which per-token contributions are interpreted. Defaults to 0. If
|
0
|
Returns:
| Type | Description |
|---|---|
Comparison
|
A new |