Clustering Gaussian Mixture#
gaussian_mixture
#
| CLASS | DESCRIPTION |
|---|---|
GaussianMixture |
Gaussian Mixture Model clustering using Expectation-Maximization algorithm. |
| FUNCTION | DESCRIPTION |
|---|---|
gaussian_mixture |
Perform Gaussian Mixture Model clustering (functional interface). |
Classes#
GaussianMixture(n_states: int, covariance_type: Literal['diag', 'spherical', 'full', 'tied'] = 'diag', init: Literal['random', 'k-means++'] = 'random', n_init: int = 1, n_iter: int = 100, eps: float = torch.finfo(torch.float32).eps, tol: float = 0.001, device: torch.device | str | None = None, dtype: torch.dtype = torch.float32)
#
Bases: Estimator
Gaussian Mixture Model clustering using Expectation-Maximization algorithm.
A Gaussian Mixture Model represents data as a combination of multiple Gaussian distributions. This implementation uses the Expectation-Maximization (EM) algorithm to iteratively estimate the parameters of each Gaussian component.
The fit method accepts sample weights to handle class imbalance,
importance sampling, or uncertainty weighting. Weights are incorporated
into both the E-step (responsibilities) and M-step (parameter updates):
- Responsibilities weighted by sample weights
- Component means computed as weighted averages
- Covariances computed with weighted samples
- Mixture weights normalized based on effective sample counts
Weights are automatically normalized to sum to n_samples. Zero or negative weights raise an error.
| PARAMETER | DESCRIPTION |
|---|---|
n_states
|
Number of Gaussian components (states) to form. Must be at least 1.
TYPE:
|
covariance_type
|
Type of covariance.
TYPE:
|
init
|
Initialization strategy for component parameters.
TYPE:
|
n_init
|
Number of EM initializations to perform. Best result is kept.
TYPE:
|
n_iter
|
Maximum number of EM iterations per initialization.
TYPE:
|
eps
|
Regularization term added to diagonal of covariance matrices to ensure numerical stability.
TYPE:
|
tol
|
Convergence tolerance. EM stops when log-likelihood improvement is below this threshold.
TYPE:
|
device
|
Device to run computations on. If None, automatically selects CUDA if available, otherwise CPU.
TYPE:
|
dtype
|
Data type to use for computations.
TYPE:
|
Properties
means : torch.Tensor Mean parameters for each mixture component of shape (n_states, in_features).
covariances : torch.Tensor
Covariance parameters for each component. Shape depends on covariance_type:
- "diag": (n_states, in_features)
- "spherical": (n_states, 1)
- "full": (n_states, in_features, in_features)
- "tied": (in_features, in_features)
weights : torch.Tensor Mixing weights for each component of shape (n_states,).
labels : torch.Tensor Component labels for each training sample.
lower_bound : float Log-likelihood lower bound achieved by the model.
converged : bool Whether the EM algorithm converged for the best fit.
Examples:
Basic Gaussian mixture modeling:
>>> from spectre.utils.compute import deterministic
>>> deterministic(42)
>>> gmm = GaussianMixture(n_states=3, covariance_type="diag")
>>> X = torch.randn(100, 2)
>>> labels = gmm.fit_predict(X)
>>> labels.shape
torch.Size([100])
Accessing fitted parameters:
>>> gmm.fit(X)
>>> print(f"Component means: {gmm.means_.shape}")
>>> print(f"Component weights: {gmm.weights_}")
Using spherical covariances:
>>> gmm = GaussianMixture(n_states=2, covariance_type="spherical", n_init=5)
>>> labels = gmm.fit_predict(X)
Evaluating clustering quality:
Soft clustering probabilities:
>>> gmm = GaussianMixture(n_states=2, covariance_type="diag")
>>> gmm.fit(X)
>>> probabilities = gmm.predict_proba(X) # Returns: (n_samples, n_states)
>>> # Get samples with high uncertainty
>>> max_probs = probabilities.max(dim=1)[0]
>>> uncertain = X[max_probs < 0.7]
Weighted samples for class imbalance or importance weighting:
>>> # Emphasize certain samples during fitting
>>> weights = torch.ones(100)
>>> weights[:50] = 2.0 # Double weight for first half
>>> gmm = GaussianMixture(n_states=2, covariance_type="diag")
>>> gmm.fit(X, weights=weights)
>>> # Component weights will reflect the sample weighting
>>> print(gmm.weights_) # Biased toward states containing weighted samples
| METHOD | DESCRIPTION |
|---|---|
fit |
Fit Gaussian Mixture Model to input data. |
predict |
Predict component labels for input data. |
fit_predict |
Fit Gaussian Mixture Model and predict component labels. |
predict_proba |
Predict component membership probabilities for input data. |
score |
Return the silhouette score of the clustering. |
get_results |
Get all fitted parameters as a dictionary. |
| ATTRIBUTE | DESCRIPTION |
|---|---|
means |
Component means.
TYPE:
|
covariances |
Component covariances.
TYPE:
|
mixing_weights |
Component mixing weights.
TYPE:
|
labels |
Training sample labels.
TYPE:
|
lower_bound |
Log-likelihood lower bound.
TYPE:
|
converged |
Whether EM algorithm converged.
TYPE:
|
Source code in spectre/clustering/gaussian_mixture.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
Attributes#
means: torch.Tensor
property
#
Component means.
covariances: torch.Tensor
property
#
Component covariances.
mixing_weights: torch.Tensor
property
#
Component mixing weights.
labels: torch.Tensor
property
#
Training sample labels.
lower_bound: float
property
#
Log-likelihood lower bound.
converged: bool
property
#
Whether EM algorithm converged.
Functions#
fit(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> GaussianMixture
#
Fit Gaussian Mixture Model to input data.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Training data of shape (n_samples, in_features).
TYPE:
|
weights
|
Sample weights of shape (n_samples,). If provided, samples are weighted during EM parameter estimation. Weights are normalized to sum to n_samples.
TYPE:
|
target
|
Target values for supervised learning. Not supported.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
GaussianMixture
|
Return self. |
Source code in spectre/clustering/gaussian_mixture.py
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
predict(X: torch.Tensor) -> torch.Tensor
#
Predict component labels for input data.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data of shape (n_samples, in_features).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Predicted component labels of shape (n_samples, ). |
Source code in spectre/clustering/gaussian_mixture.py
fit_predict(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> torch.Tensor
#
Fit Gaussian Mixture Model and predict component labels.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Training data of shape (n_samples, in_features).
TYPE:
|
weights
|
Sample weights of shape (n_samples, ).
TYPE:
|
target
|
Target values for supervised learning. Currently not supported.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Predicted component labels of shape (n_samples, ). |
Source code in spectre/clustering/gaussian_mixture.py
predict_proba(X: torch.Tensor) -> torch.Tensor
#
Predict component membership probabilities for input data.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data of shape (n_samples, in_features).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Component membership probabilities of shape (n_samples, n_states). |
Source code in spectre/clustering/gaussian_mixture.py
score(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> torch.Tensor
#
Return the silhouette score of the clustering.
Score is between -1 and 1. Higher values indicate better clustering
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Data to score.
TYPE:
|
weights
|
Sample weights. Currently ignored for silhouette score computation.
TYPE:
|
target
|
Target values. Ignored for clustering (compatibility).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Silhouette score. |
Source code in spectre/clustering/gaussian_mixture.py
get_results() -> dict[str, torch.Tensor | float | bool]
#
Get all fitted parameters as a dictionary.
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary containing computed results. |
Source code in spectre/clustering/gaussian_mixture.py
Functions#
gaussian_mixture(X: torch.Tensor, weights: torch.Tensor | None = None, *, n_states: int, covariance_type: Literal['diag', 'spherical', 'full', 'tied'] = 'diag', init: Literal['random', 'k-means++'] = 'random', n_init: int = 1, n_iter: int = 100, eps: float = torch.finfo(torch.float32).eps, tol: float = 0.001, device: torch.device | str | None = None, dtype: torch.dtype = torch.float32) -> dict[str, torch.Tensor | float | bool]
#
Perform Gaussian Mixture Model clustering (functional interface).
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data of shape (n_samples, in_features).
TYPE:
|
weights
|
Sample weights.
TYPE:
|
n_states
|
Number of Gaussian components.
TYPE:
|
covariance_type
|
Type of covariance parameters. See
TYPE:
|
init
|
Initialization strategy.
TYPE:
|
n_init
|
Number of random initializations.
TYPE:
|
n_iter
|
Maximum EM iterations.
TYPE:
|
eps
|
Covariance regularization.
TYPE:
|
tol
|
Convergence tolerance.
TYPE:
|
device
|
Device on which to perform computations.
TYPE:
|
dtype
|
Data type for computations.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor | float | bool]
|
Clustering results. |