gmm-divergence 0.0.1a1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.4
2
+ Name: gmm-divergence
3
+ Version: 0.0.1a1
4
+ Summary: Utilities for estimating divergences between Gaussian mixture models.
5
+ Keywords: divergence,gaussian-mixture-model,gmm,kl-divergence,numpy
6
+ Author: David Axelsson
7
+ Author-email: David Axelsson <david.axelsson@liu.se>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Scientific/Engineering
20
+ Classifier: Typing :: Typed
21
+ Requires-Dist: numpy>=2.2.6
22
+ Requires-Dist: typing-extensions>=4.13.2
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+
26
+ # gmm-divergence
27
+
28
+ Utilities for estimating divergences between Gaussian mixture models.
29
+
30
+ This package is under active development. APIs, estimators, and numerical behavior may change between early releases.
31
+
32
+ ## Current Scope
33
+
34
+ The package currently includes:
35
+
36
+ - A typed Gaussian mixture representation
37
+ - Density and log-density evaluation for full and diagonal covariance mixtures
38
+ - Sampling from Gaussian mixtures
39
+ - KL divergence estimators based on Monte Carlo sampling and unscented sigma points
40
+
41
+ ## Installation
42
+
43
+ This project is not yet intended for stable production use. For development, install it from a local checkout:
44
+
45
+ ```bash
46
+ python -m pip install -e .
47
+ ```
@@ -0,0 +1,22 @@
1
+ # gmm-divergence
2
+
3
+ Utilities for estimating divergences between Gaussian mixture models.
4
+
5
+ This package is under active development. APIs, estimators, and numerical behavior may change between early releases.
6
+
7
+ ## Current Scope
8
+
9
+ The package currently includes:
10
+
11
+ - A typed Gaussian mixture representation
12
+ - Density and log-density evaluation for full and diagonal covariance mixtures
13
+ - Sampling from Gaussian mixtures
14
+ - KL divergence estimators based on Monte Carlo sampling and unscented sigma points
15
+
16
+ ## Installation
17
+
18
+ This project is not yet intended for stable production use. For development, install it from a local checkout:
19
+
20
+ ```bash
21
+ python -m pip install -e .
22
+ ```
@@ -0,0 +1,82 @@
1
+ [project]
2
+ name = "gmm-divergence"
3
+ version = "0.0.1a1"
4
+ description = "Utilities for estimating divergences between Gaussian mixture models."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "David Axelsson", email = "david.axelsson@liu.se" }
8
+ ]
9
+ license = "Apache-2.0"
10
+ license-files = ["LICENSE"]
11
+ requires-python = ">=3.10"
12
+ keywords = ["divergence", "gaussian-mixture-model", "gmm", "kl-divergence", "numpy"]
13
+ classifiers = [
14
+ "Development Status :: 2 - Pre-Alpha",
15
+ "Intended Audience :: Science/Research",
16
+ "Operating System :: OS Independent",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Topic :: Scientific/Engineering",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = [
27
+ "numpy>=2.2.6",
28
+ "typing-extensions>=4.13.2",
29
+ ]
30
+
31
+ [dependency-groups]
32
+ build = [
33
+ "build>=1.5.0",
34
+ "twine>=6.2.0",
35
+ ]
36
+ test = [
37
+ "pytest>=8.3.5",
38
+ "pytest-benchmark>=5.2.3",
39
+ ]
40
+
41
+ [build-system]
42
+ requires = ["uv_build>=0.11.16,<0.12.0"]
43
+ build-backend = "uv_build"
44
+
45
+ [tool.ruff]
46
+ line-length = 100
47
+ preview = true
48
+
49
+ [tool.ruff.lint]
50
+ select = ["ALL"]
51
+ ignore = [
52
+ "D203",
53
+ "D213",
54
+ "COM812",
55
+ "PLR2004",
56
+ "DOC201",
57
+ "DOC501",
58
+ "TRY003",
59
+ "D100",
60
+ "PLR0904",
61
+ "TD002",
62
+ "TD003",
63
+ "PLR0913",
64
+ "PLR0917",
65
+ "PLR0914",
66
+ "DOC402",
67
+ "CPY001",
68
+ "D104",
69
+ "TD005",
70
+ "PLC2801",
71
+ "D101",
72
+ ]
73
+ pydocstyle = { convention = "numpy" }
74
+
75
+ [tool.ruff.lint.per-file-ignores]
76
+ "tests/**/*.py" = ["D", "INP001", "S101", "PLC2701"]
77
+
78
+ [tool.ruff.lint.flake8-tidy-imports]
79
+ ban-relative-imports = "all"
80
+
81
+ [tool.pytest.ini_options]
82
+ testpaths = ["tests"]
@@ -0,0 +1,8 @@
1
+ from importlib.metadata import version
2
+
3
+ from gmm_divergence.divergence import kl_divergence
4
+ from gmm_divergence.gmm.model import GaussianMixture
5
+ from gmm_divergence.results import DivergenceResult
6
+
7
+ __all__ = ["DivergenceResult", "GaussianMixture", "kl_divergence"]
8
+ __version__: str = version("gmm-divergence")
@@ -0,0 +1,105 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Literal, overload
4
+
5
+ from gmm_divergence.methods.gaussian_approx import kl_gaussian_approximation
6
+ from gmm_divergence.methods.monte_carlo import kl_monte_carlo
7
+ from gmm_divergence.methods.unscented import kl_unscented
8
+
9
+ if TYPE_CHECKING:
10
+ import numpy as np
11
+ import numpy.typing as npt
12
+
13
+ from gmm_divergence.gmm.model import GaussianMixture, PrecisionT
14
+ from gmm_divergence.results import DivergenceResult
15
+
16
+ KLMethod = Literal["monte_carlo", "unscented", "gaussian_approximation"]
17
+
18
+
19
+ @overload
20
+ def kl_divergence(
21
+ p: GaussianMixture[PrecisionT],
22
+ q: GaussianMixture[PrecisionT],
23
+ /,
24
+ *,
25
+ method: Literal["gaussian_approximation"] = ...,
26
+ approximation: Literal["nearest", "moment_matching"] = "moment_matching",
27
+ ) -> DivergenceResult: ...
28
+
29
+
30
+ @overload
31
+ def kl_divergence(
32
+ p: GaussianMixture[PrecisionT],
33
+ q: GaussianMixture[PrecisionT],
34
+ /,
35
+ *,
36
+ method: Literal["unscented"] = ...,
37
+ ) -> DivergenceResult: ...
38
+
39
+
40
+ @overload
41
+ def kl_divergence(
42
+ p: GaussianMixture[PrecisionT],
43
+ q: GaussianMixture[PrecisionT],
44
+ /,
45
+ *,
46
+ method: Literal["monte_carlo"] = "monte_carlo",
47
+ num_samples: int = 10_000,
48
+ samples: npt.ArrayLike | None = None,
49
+ rng: np.random.Generator | int | None = None,
50
+ ) -> DivergenceResult: ...
51
+
52
+
53
+ def kl_divergence(
54
+ p: GaussianMixture[PrecisionT],
55
+ q: GaussianMixture[PrecisionT],
56
+ /,
57
+ *,
58
+ method: KLMethod = "monte_carlo",
59
+ num_samples: int = 10_000,
60
+ samples: npt.ArrayLike | None = None,
61
+ rng: np.random.Generator | int | None = None,
62
+ approximation: Literal["nearest", "moment_matching"] = "moment_matching",
63
+ ) -> DivergenceResult:
64
+ """Compute KL divergence between two Gaussian mixtures.
65
+
66
+ Parameters
67
+ ----------
68
+ p, q : GaussianMixture
69
+ The two Gaussian mixtures to compare. The KL divergence is computed as
70
+ KL(p || q).
71
+ method : KLMethod
72
+ The method to use for estimating the KL divergence. "monte_carlo" uses
73
+ Monte Carlo sampling, while "unscented" uses unscented sigma points.
74
+ num_samples : int
75
+ The number of samples to use for the Monte Carlo method.
76
+ samples : array-like, optional
77
+ Pre-generated samples from the first mixture `p` to use for the Monte
78
+ Carlo method.
79
+ rng : np.random.Generator, int, or None
80
+ Random number generator or seed for the Monte Carlo method.
81
+
82
+ Returns
83
+ -------
84
+ DivergenceResult
85
+ An object containing the estimated KL divergence and metadata about the
86
+ estimation method. The value for the KL divergence estimate is stored in
87
+ the `value` attribute of the returned object.
88
+ """
89
+ match method:
90
+ case "monte_carlo":
91
+ return kl_monte_carlo(
92
+ p,
93
+ q,
94
+ num_samples=num_samples,
95
+ samples=samples,
96
+ rng=rng,
97
+ )
98
+ case "unscented":
99
+ return kl_unscented(p, q)
100
+ case "gaussian_approximation":
101
+ return kl_gaussian_approximation(
102
+ p,
103
+ q,
104
+ approximation=approximation,
105
+ )
@@ -0,0 +1,19 @@
1
+ from gmm_divergence.gmm.density import (
2
+ gmm_logpdf_diag,
3
+ gmm_logpdf_full,
4
+ gmm_pdf_diag,
5
+ gmm_pdf_full,
6
+ )
7
+ from gmm_divergence.gmm.model import CovarianceType, GaussianMixture, PrecisionT
8
+ from gmm_divergence.gmm.sampling import sample_gmm
9
+
10
+ __all__ = [
11
+ "CovarianceType",
12
+ "GaussianMixture",
13
+ "PrecisionT",
14
+ "gmm_logpdf_diag",
15
+ "gmm_logpdf_full",
16
+ "gmm_pdf_diag",
17
+ "gmm_pdf_full",
18
+ "sample_gmm",
19
+ ]
@@ -0,0 +1,91 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+ if TYPE_CHECKING:
9
+ from gmm_divergence.gmm.model import GaussianMixture, PrecisionT
10
+
11
+
12
+ def _logsumexp(a: npt.NDArray[PrecisionT], axis: int = -1) -> npt.NDArray[PrecisionT]:
13
+ a_max = np.max(a, axis=axis, keepdims=True)
14
+ return np.squeeze(
15
+ a_max + np.log(np.sum(np.exp(a - a_max), axis=axis, keepdims=True)),
16
+ axis=axis,
17
+ )
18
+
19
+
20
+ def gmm_logpdf_full(
21
+ x: npt.ArrayLike,
22
+ gmm: GaussianMixture[PrecisionT],
23
+ ) -> npt.NDArray[PrecisionT]:
24
+ """Evaluate the log-density of a full-covariance Gaussian mixture."""
25
+ if gmm.covariance_type != "full":
26
+ msg = f"Expected full covariance type, got {gmm.covariance_type}"
27
+ raise ValueError(msg)
28
+
29
+ x = np.asarray(x, dtype=gmm.dtype)
30
+ weights = gmm.weights / np.sum(gmm.weights)
31
+
32
+ n_samples, n_features = x.shape
33
+ n_components = weights.shape[0]
34
+
35
+ log_weights = np.log(weights)
36
+ chol = gmm.chol()
37
+ log_probs = np.empty((n_samples, n_components), dtype=gmm.dtype)
38
+ constant = n_features * np.log(2.0 * np.pi)
39
+
40
+ for k in range(n_components):
41
+ diff = x - gmm.means[k]
42
+ y = np.linalg.solve(chol[k], diff.T)
43
+ mahal = np.sum(y * y, axis=0)
44
+ log_det = 2.0 * np.sum(np.log(np.diag(chol[k])))
45
+ log_gaussian = -0.5 * (constant + log_det + mahal)
46
+ log_probs[:, k] = log_weights[k] + log_gaussian
47
+
48
+ return _logsumexp(log_probs, axis=1)
49
+
50
+
51
+ def gmm_pdf_full(
52
+ x: npt.ArrayLike,
53
+ gmm: GaussianMixture[PrecisionT],
54
+ ) -> npt.NDArray[PrecisionT]:
55
+ """Evaluate the density of a full-covariance Gaussian mixture."""
56
+ return np.exp(gmm_logpdf_full(x, gmm))
57
+
58
+
59
+ def gmm_logpdf_diag(
60
+ x: npt.ArrayLike,
61
+ gmm: GaussianMixture[PrecisionT],
62
+ ) -> npt.NDArray[PrecisionT]:
63
+ """Evaluate the log-density of a diagonal-covariance Gaussian mixture."""
64
+ if gmm.covariance_type != "diag":
65
+ msg = f"Expected diagonal covariance type, got {gmm.covariance_type}"
66
+ raise ValueError(msg)
67
+
68
+ x = np.asarray(x, dtype=gmm.dtype)
69
+ weights = gmm.weights / np.sum(gmm.weights)
70
+ means = gmm.means
71
+ variances = gmm.covariances
72
+
73
+ _n_samples, n_features = x.shape
74
+ log_weights = np.log(weights)
75
+
76
+ diff = x[:, None, :] - means[None, :, :]
77
+ mahal = np.sum((diff * diff) / variances[None, :, :], axis=2)
78
+ log_det = np.sum(np.log(variances), axis=1)
79
+ constant = n_features * np.log(2.0 * np.pi)
80
+ log_gaussian = -0.5 * (constant + log_det[None, :] + mahal)
81
+ log_probs = log_weights[None, :] + log_gaussian
82
+
83
+ return _logsumexp(log_probs, axis=1)
84
+
85
+
86
+ def gmm_pdf_diag(
87
+ x: npt.ArrayLike,
88
+ gmm: GaussianMixture[PrecisionT],
89
+ ) -> npt.NDArray[PrecisionT]:
90
+ """Evaluate the density of a diagonal-covariance Gaussian mixture."""
91
+ return np.exp(gmm_logpdf_diag(x, gmm))
@@ -0,0 +1,125 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Generic, Literal, cast
5
+
6
+ import numpy as np
7
+ import numpy.typing as npt
8
+ from typing_extensions import TypeVar
9
+
10
+ from gmm_divergence.gmm.density import gmm_logpdf_diag, gmm_logpdf_full
11
+
12
+ PrecisionT = TypeVar("PrecisionT", np.float32, np.float64, default=np.float64)
13
+
14
+ CovarianceType = Literal["full", "diag"]
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class GaussianMixture(Generic[PrecisionT]):
19
+ weights: npt.NDArray[PrecisionT]
20
+ """Weight array of shape (n_components,)."""
21
+ means: npt.NDArray[PrecisionT]
22
+ """Mean array of shape (n_components, n_features)."""
23
+ covariances: npt.NDArray[PrecisionT]
24
+ """Covariance array shape depends on the covariance type."""
25
+ covariance_type: CovarianceType = "full"
26
+
27
+ _chol: npt.NDArray[PrecisionT] | None = field(default=None, init=False, repr=False)
28
+ """Cached Cholesky factors, shape (n_components, n_features, n_features)."""
29
+
30
+ def __post_init__(self) -> None:
31
+ """Validate the shapes of weights, means, and covariances."""
32
+ if self.weights.ndim != 1:
33
+ msg = "Weights must be a 1D array."
34
+ raise ValueError(msg)
35
+
36
+ if self.means.ndim != 2:
37
+ msg = "Means must be a 2D array."
38
+ raise ValueError(msg)
39
+
40
+ n_components = self.weights.shape[0]
41
+ n_features = self.means.shape[1]
42
+
43
+ if self.weights.shape[0] != self.means.shape[0]:
44
+ msg = "Number of components in weights and means must match."
45
+ raise ValueError(msg)
46
+
47
+ if self.covariance_type == "full":
48
+ expected_shape = (n_components, n_features, n_features)
49
+ if self.covariances.shape != expected_shape:
50
+ msg = (
51
+ "For covariance_type='full', covariances must have shape "
52
+ f"{expected_shape}, got {self.covariances.shape}."
53
+ )
54
+ raise ValueError(msg)
55
+ elif self.covariance_type == "diag":
56
+ expected_shape = (n_components, n_features)
57
+ if self.covariances.shape != expected_shape:
58
+ msg = (
59
+ "For covariance_type='diag', covariances must have shape "
60
+ f"{expected_shape}, got {self.covariances.shape}."
61
+ )
62
+ raise ValueError(msg)
63
+ else:
64
+ msg = f"Unsupported covariance_type: {self.covariance_type!r}."
65
+ raise ValueError(msg)
66
+
67
+ self.weights.setflags(write=False)
68
+ self.means.setflags(write=False)
69
+ self.covariances.setflags(write=False)
70
+
71
+ @classmethod
72
+ def create(
73
+ cls,
74
+ weights: npt.ArrayLike,
75
+ means: npt.ArrayLike,
76
+ covariances: npt.ArrayLike,
77
+ covariance_type: CovarianceType = "full",
78
+ dtype: type[PrecisionT] = np.float64,
79
+ ) -> GaussianMixture[PrecisionT]:
80
+ """Create a Gaussian mixture from array-like parameters."""
81
+ weights = np.asarray(weights, dtype=dtype)
82
+ means = np.asarray(means, dtype=dtype)
83
+ covariances = np.asarray(covariances, dtype=dtype)
84
+ return cls(
85
+ weights=weights,
86
+ means=means,
87
+ covariances=covariances,
88
+ covariance_type=covariance_type,
89
+ )
90
+
91
+ @property
92
+ def dtype(self) -> type[PrecisionT]:
93
+ """Data type of the Gaussian mixture parameters."""
94
+ return self.means.dtype.type
95
+
96
+ @property
97
+ def n_components(self) -> int:
98
+ """Number of components in the Gaussian mixture."""
99
+ return self.weights.shape[0]
100
+
101
+ def logpdf(self, x: npt.ArrayLike) -> npt.NDArray[PrecisionT]:
102
+ """Evaluate the mixture log-density at one or more sample points."""
103
+ x = np.asarray(x, dtype=self.means.dtype)
104
+ if x.ndim == 1:
105
+ x = x[None, :]
106
+ if self.covariance_type == "full":
107
+ return gmm_logpdf_full(x=x, gmm=self)
108
+ if self.covariance_type == "diag":
109
+ return gmm_logpdf_diag(x=x, gmm=self)
110
+ msg = f"Unsupported covariance type: {self.covariance_type}"
111
+ raise ValueError(msg)
112
+
113
+ def pdf(self, x: npt.ArrayLike) -> npt.NDArray[PrecisionT]:
114
+ """Evaluate the mixture density at one or more sample points."""
115
+ return np.exp(self.logpdf(x))
116
+
117
+ def chol(self) -> npt.NDArray[PrecisionT]:
118
+ """Compute or retrieve the cached Cholesky factors of the covariance matrices."""
119
+ if self.covariance_type != "full":
120
+ msg = "Cholesky factors are only defined for full covariance type."
121
+ raise ValueError(msg)
122
+
123
+ if self._chol is None:
124
+ object.__setattr__(self, "_chol", np.linalg.cholesky(self.covariances))
125
+ return cast("npt.NDArray[PrecisionT]", self._chol)
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+ if TYPE_CHECKING:
9
+ from gmm_divergence.gmm.model import GaussianMixture, PrecisionT
10
+
11
+
12
+ def sample_gmm(
13
+ gmm: GaussianMixture[PrecisionT],
14
+ /,
15
+ n_samples: int,
16
+ *,
17
+ rng: np.random.Generator | int | None = None,
18
+ ) -> npt.NDArray[PrecisionT]:
19
+ """Draw samples from a Gaussian mixture."""
20
+ rng = np.random.default_rng(rng)
21
+ weights = gmm.weights / np.sum(gmm.weights)
22
+
23
+ component_ids = rng.choice(
24
+ gmm.n_components,
25
+ size=n_samples,
26
+ p=weights,
27
+ )
28
+
29
+ if gmm.covariance_type == "diag":
30
+ stds = np.sqrt(gmm.covariances[component_ids])
31
+ eps = rng.standard_normal(size=gmm.means[component_ids].shape)
32
+ samples = gmm.means[component_ids] + eps * stds
33
+ elif gmm.covariance_type == "full":
34
+ chol = gmm.chol()
35
+ eps = rng.standard_normal(size=gmm.means[component_ids].shape)
36
+ samples = gmm.means[component_ids] + np.einsum(
37
+ "nij,nj->ni",
38
+ chol[component_ids],
39
+ eps,
40
+ )
41
+ else:
42
+ msg = f"Unsupported covariance type: {gmm.covariance_type}"
43
+ raise ValueError(msg)
44
+
45
+ return samples.astype(gmm.means.dtype, copy=False)
@@ -0,0 +1,4 @@
1
+ from gmm_divergence.methods.monte_carlo import kl_monte_carlo
2
+ from gmm_divergence.methods.unscented import kl_unscented
3
+
4
+ __all__ = ["kl_monte_carlo", "kl_unscented"]
@@ -0,0 +1,95 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Literal
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+ from gmm_divergence.results import DivergenceResult
9
+
10
+ if TYPE_CHECKING:
11
+ from gmm_divergence.gmm.model import GaussianMixture, PrecisionT
12
+
13
+ Approximation = Literal["nearest", "moment_matching"]
14
+
15
+
16
+ def kl_gaussian_approximation(
17
+ p: GaussianMixture[PrecisionT],
18
+ q: GaussianMixture[PrecisionT],
19
+ /,
20
+ approximation: Approximation = "moment_matching",
21
+ ) -> DivergenceResult:
22
+ """Estimate KL divergence by approximating each mixture with a single Gaussian."""
23
+ if approximation == "moment_matching":
24
+ mean_p, cov_p = _moment_matching_approximation(p)
25
+ mean_q, cov_q = _moment_matching_approximation(q)
26
+ return DivergenceResult(
27
+ value=_kl_single_gaussian(mean_p, cov_p, mean_q, cov_q),
28
+ method="moment_matching",
29
+ )
30
+ if approximation == "nearest":
31
+ return DivergenceResult(
32
+ value=_nearest_component_approximation(p, q), method="nearest_component"
33
+ )
34
+ msg = f"Unsupported approximation method: {approximation}"
35
+ raise ValueError(msg)
36
+
37
+
38
+ def _moment_matching_approximation(
39
+ gmm: GaussianMixture[PrecisionT],
40
+ ) -> tuple[npt.NDArray[PrecisionT], npt.NDArray[PrecisionT]]:
41
+ """Compute mean and covariance of the Gaussian approximation."""
42
+ weights = gmm.weights / np.sum(gmm.weights)
43
+ mean = np.sum(weights[:, None] * gmm.means, axis=0)
44
+ if gmm.covariance_type == "diag":
45
+ cov = np.sum(
46
+ weights[:, None] * (gmm.covariances + (gmm.means - mean) * (gmm.means - mean).T),
47
+ axis=0,
48
+ )
49
+ elif gmm.covariance_type == "full":
50
+ cov = np.sum(
51
+ weights[:, None, None]
52
+ * (gmm.covariances + (gmm.means - mean)[:, :, None] * (gmm.means - mean)[:, None, :]),
53
+ axis=0,
54
+ )
55
+ else:
56
+ msg = f"Unsupported covariance type: {gmm.covariance_type}"
57
+ raise ValueError(msg)
58
+ return mean, cov
59
+
60
+
61
+ def _nearest_component_approximation(
62
+ p: GaussianMixture[PrecisionT], q: GaussianMixture[PrecisionT], /
63
+ ) -> float:
64
+ """Find the component of q closest to p in KL divergence."""
65
+ min_kl = np.inf
66
+ for a in range(q.n_components):
67
+ for b in range(p.n_components):
68
+ kl = _kl_single_gaussian(
69
+ mean_p=p.means[b],
70
+ cov_p=p.covariances[b]
71
+ if p.covariance_type == "full"
72
+ else np.diag(p.covariances[b]),
73
+ mean_q=q.means[a],
74
+ cov_q=q.covariances[a]
75
+ if q.covariance_type == "full"
76
+ else np.diag(q.covariances[a]),
77
+ )
78
+ min_kl = min(min_kl, kl)
79
+ return min_kl
80
+
81
+
82
+ def _kl_single_gaussian(
83
+ mean_p: npt.NDArray[PrecisionT],
84
+ cov_p: npt.NDArray[PrecisionT],
85
+ mean_q: npt.NDArray[PrecisionT],
86
+ cov_q: npt.NDArray[PrecisionT],
87
+ ) -> float:
88
+ """Compute KL divergence between two Gaussians."""
89
+ dim = mean_p.shape[0]
90
+ inv_cov_q = np.linalg.inv(cov_q)
91
+ trace_term = np.trace(inv_cov_q @ cov_p)
92
+ mean_diff = mean_q - mean_p
93
+ quadratic_term = mean_diff.T @ inv_cov_q @ mean_diff
94
+ log_det_ratio = np.log(np.linalg.det(cov_q) / np.linalg.det(cov_p))
95
+ return 0.5 * (trace_term + quadratic_term - dim + log_det_ratio)
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+ from gmm_divergence.gmm.sampling import sample_gmm
9
+ from gmm_divergence.results import DivergenceResult
10
+
11
+ if TYPE_CHECKING:
12
+ from gmm_divergence.gmm.model import GaussianMixture, PrecisionT
13
+
14
+
15
+ def kl_monte_carlo(
16
+ p: GaussianMixture[PrecisionT],
17
+ q: GaussianMixture[PrecisionT],
18
+ /,
19
+ *,
20
+ num_samples: int = 10_000,
21
+ samples: npt.ArrayLike | None = None,
22
+ rng: np.random.Generator | int | None = None,
23
+ ) -> DivergenceResult:
24
+ """Estimate KL divergence with samples from the first mixture."""
25
+ samples = _resolve_samples(p, num_samples, samples, rng)
26
+ return DivergenceResult(
27
+ value=float(np.mean(p.logpdf(samples) - q.logpdf(samples))),
28
+ method="monte_carlo",
29
+ num_samples=num_samples,
30
+ )
31
+
32
+
33
+ def _resolve_samples(
34
+ gmm: GaussianMixture[PrecisionT],
35
+ num_samples: int,
36
+ samples: npt.ArrayLike | None,
37
+ rng: np.random.Generator | int | None = None,
38
+ ) -> npt.NDArray[PrecisionT]:
39
+ if samples is not None:
40
+ samples = np.asarray(samples, dtype=gmm.dtype)
41
+ if samples.ndim != 2 or samples.shape[1] != gmm.means.shape[1]:
42
+ msg = f"Expected samples of shape (n_samples, n_features), got {samples.shape}"
43
+ raise ValueError(msg)
44
+ return samples
45
+ return sample_gmm(gmm, n_samples=num_samples, rng=rng)
@@ -0,0 +1,48 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+ from gmm_divergence.results import DivergenceResult
9
+
10
+ if TYPE_CHECKING:
11
+ from gmm_divergence.gmm.model import GaussianMixture, PrecisionT
12
+
13
+
14
+ def kl_unscented(
15
+ p: GaussianMixture[PrecisionT],
16
+ q: GaussianMixture[PrecisionT],
17
+ /,
18
+ ) -> DivergenceResult:
19
+ """Estimate KL divergence with unscented sigma points."""
20
+ sigma_points = _sigma_points(p)
21
+ n_components, n_sigma, dim = sigma_points.shape
22
+ flat_points = sigma_points.reshape(-1, dim)
23
+ log_p = p.logpdf(flat_points).reshape(n_components, n_sigma)
24
+ log_q = q.logpdf(flat_points).reshape(n_components, n_sigma)
25
+ log_ratio = log_p - log_q
26
+ # log_ratio[a, k] = log(f(x_{a,k}) / g(x_{a,k}))
27
+ value = np.sum(p.weights[:, None] * log_ratio) / n_sigma
28
+ return DivergenceResult(
29
+ value=float(value), method="unscented", num_samples=n_components * n_sigma
30
+ )
31
+
32
+
33
+ def _sigma_points(gmm: GaussianMixture[PrecisionT], /) -> npt.NDArray[PrecisionT]:
34
+ """Compute sigma points for each component of GMM."""
35
+ means = gmm.means
36
+ covariances = gmm.covariances
37
+ n_components, dim = means.shape
38
+ eigenvalues, eigenvectors = np.linalg.eigh(covariances)
39
+ eigenvalues = np.maximum(eigenvalues, 0)
40
+ scales = np.sqrt(dim * eigenvalues) # (K, d)
41
+ offsets = eigenvectors * scales[:, None, :] # (K, d, d)
42
+ sigma_points = np.empty(
43
+ (n_components, 2 * dim, dim),
44
+ dtype=gmm.dtype,
45
+ )
46
+ sigma_points[:, :dim, :] = means[:, None, :] + offsets.transpose(0, 2, 1)
47
+ sigma_points[:, dim:, :] = means[:, None, :] - offsets.transpose(0, 2, 1)
48
+ return sigma_points
File without changes
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass(frozen=True, slots=True)
7
+ class DivergenceResult:
8
+ value: float
9
+ method: str | None = None
10
+ num_samples: int | None = None