NumPy Backend Extension Points

This page covers the stable NumPy components that turn embeddings into scores, clusters, and evaluation-ready decisions. These components use row-aligned NumPy arrays and serialize independently from PyTorch model checkpoints. Read Hyperion Data Model first when the inputs originate in tables or trial files.

Score backend pipeline

The usual verification sequence is:

  1. fit preprocessing and PLDA on development embeddings and speaker labels;

  2. score enrollment versus test embeddings;

  3. optionally apply cohort-based score normalization; and

  4. fit calibration on separate labelled development trials.

Never use evaluation labels when fitting preprocessing, cohort statistics, or calibration. Keep the fitted transforms, PLDA backend, score normalizer, and calibrator as separate saved artifacts so they can be reproduced or replaced independently.

PLDA and transforms

class hyperion.np.transforms.transform_list.TransformList(transforms: HyperNPModel | List[HyperNPModel], **kwargs: Any)[source]

Class to perform a sequence of transformations.

transforms

list of transformation objects.

Example:

pipeline = TransformList([MVN(), PCA(pca_dim=128)], name="frontend")
__init__(transforms: HyperNPModel | List[HyperNPModel], **kwargs: Any) None[source]

Initializes a transformation pipeline.

Parameters:
  • transforms – Single transform or ordered list of transforms.

  • **kwargs – Additional arguments forwarded to HyperNPModel.

_ensure_unique_transform_names() None[source]

Ensures each child transform has a unique name.

append(t: HyperNPModel) None[source]

Appends a transformation to the list.

Parameters:

t – transformation object.

__call__(x: ndarray) ndarray[source]

Applies the list of transformations to the data.

Parameters:

x – data samples.

Returns:

Transformed data samples.

forward(x: ndarray) ndarray[source]

Applies the list of transformations to the data.

Parameters:

x – data samples.

Returns:

Transformed data samples.

predict(x: ndarray) ndarray[source]

Applies the list of transformations to the data.

Parameters:

x – data samples.

Returns:

Transformed data samples.

update_names() None[source]

Prefixes child transform names with this pipeline name.

get_config() Dict[str, Any][source]

Returns the model configuration dict for the full pipeline.

save_params(f: File) None[source]

Saves all child transform parameters to the same HDF5 file.

Parameters:

f – Output HDF5 file handle.

classmethod load_params(f: File, config: Dict[str, Any]) TransformList[source]

Loads a transformation pipeline from config and file parameters.

Parameters:
  • f – Input HDF5 file handle.

  • config – Pipeline configuration dictionary.

Returns:

Loaded TransformList instance.

static _bootstrap_registry() None

Import common NP subpackages so subclasses register themselves.

static _find_module_for_class_name(class_name: str) str | None

Find module path for a registered class name by scanning NP sources.

Parameters:

class_name – Target class name to locate.

Returns:

Dotted module path if found, otherwise None.

static _load_params_to_dict(f: File, name: str | None, params: Sequence[str], dtypes: type | Mapping[str, Any] | None = None) Dict[str, ndarray | None]

Loads the model parameters from file to a dictionary.

Parameters:
  • f – file handle.

  • name – model identifier or None.

  • params – parameter names.

  • dtypes – dictionary containing the dtypes of the parameters.

Returns:

Dictionary with model parameters.

_save_params_from_dict(f: File, params: Mapping[str, Any], dtypes: type | Mapping[str, Any] | None = None) None

Saves a dictionary of model parameters into the file.

Parameters:
  • f – file handle.

  • params – dictionary of model parameters.

  • dtypes – dictionary indicating the dtypes of the model parameters.

static auto_load(file_path: str | Path, extra_objs: Dict[str, Type[HyperNPModel]] | None = None) HyperNPModel

Auto-load a serialized model based on the saved class_name.

Parameters:
  • file_path – Path to model file.

  • extra_objs – Optional mapping from class name to class object used as a fallback when class is not yet registered.

Returns:

Instantiated model loaded from file_path.

Raises:

Exception – If the class cannot be resolved/imported.

clone() HyperNPModel

Returns a clone of the model.

copy() HyperNPModel

Returns a clone of the model.

fit(x: ndarray, sample_weight: ndarray | None = None, x_val: ndarray | None = None, sample_weight_val: ndarray | None = None) None

Trains the model.

Parameters:
  • x – train data matrix with shape (num_samples, x_dim).

  • sample_weight – weight of each sample in the training loss shape (num_samples,).

  • x_val – validation data matrix with shape (num_val_samples, x_dim).

  • sample_weight_val – weight of each sample in the val. loss.

Raises:

NotImplementedError – If not implemented by a subclass.

fit_generator(x: Any, x_val: Any | None = None) None

Trains the model from a data generator function.

Parameters:
  • x – train data generation function.

  • x_val – validation data generation function.

Raises:

NotImplementedError – If not implemented by a subclass.

init_to_false() None

Sets the model as non initialized.

initialize() None

Initialize model parameters/state.

Subclasses can override this method when they have lazy initialization logic.

property is_init: bool

Returns True if the model has been initialized.

classmethod load(file_path: str | Path) HyperNPModel

Loads the model from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Model object.

classmethod load_config(file_path: str | Path) Dict[str, Any]

Loads the model configuration from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Dictionary containing the model configuration.

static load_config_from_json(json_str: str) Dict[str, Any]

Convert JSON configuration string to dictionary.

registry: ClassVar[Dict[str, Type['HyperNPModel']]] = {'AHC': <class 'hyperion.np.clustering.ahc.AHC'>, 'AdaptSNorm': <class 'hyperion.np.score_norm.adapt_s_norm.AdaptSNorm'>, 'BinaryLogisticRegression': <class 'hyperion.np.classifiers.binary_logistic_regression.BinaryLogisticRegression'>, 'CORAL': <class 'hyperion.np.transforms.coral.CORAL'>, 'CentWhiten': <class 'hyperion.np.transforms.cent_whiten.CentWhiten'>, 'CentWhitenUP': <class 'hyperion.np.transforms.cent_whiten_up.CentWhitenUP'>, 'ExpFamily': <class 'hyperion.np.pdfs.core.exp_family.ExpFamily'>, 'ExpFamilyMixture': <class 'hyperion.np.pdfs.mixtures.exp_family_mixture.ExpFamilyMixture'>, 'FRPLDA': <class 'hyperion.np.pdfs.plda.frplda.FRPLDA'>, 'GMM': <class 'hyperion.np.pdfs.mixtures.gmm.GMM'>, 'GMMDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_diag_cov.GMMDiagCov'>, 'GMMTiedDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_tied_diag_cov.GMMTiedDiagCov'>, 'Gaussianizer': <class 'hyperion.np.transforms.gaussianizer.Gaussianizer'>, 'GreedyFusionBinaryLR': <class 'hyperion.np.classifiers.greedy_fusion.GreedyFusionBinaryLR'>, 'HMM': <class 'hyperion.np.pdfs.hmm.hmm.HMM'>, 'JFATotal': <class 'hyperion.np.pdfs.jfa.jfa_total.JFATotal'>, 'KMeans': <class 'hyperion.np.clustering.kmeans.KMeans'>, 'LDA': <class 'hyperion.np.transforms.lda.LDA'>, 'LNorm': <class 'hyperion.np.transforms.lnorm.LNorm'>, 'LNormUP': <class 'hyperion.np.transforms.lnorm_up.LNormUP'>, 'LinearGBE': <class 'hyperion.np.classifiers.linear_gbe.LinearGBE'>, 'LinearGBEUP': <class 'hyperion.np.classifiers.linear_gbe_up.LinearGBEUP'>, 'LinearSVMC': <class 'hyperion.np.classifiers.linear_svmc.LinearSVMC'>, 'LogisticRegression': <class 'hyperion.np.classifiers.logistic_regression.LogisticRegression'>, 'MVN': <class 'hyperion.np.transforms.mvn.MVN'>, 'NAP': <class 'hyperion.np.transforms.nap.NAP'>, 'NDA': <class 'hyperion.np.transforms.nda.NDA'>, 'NPModel': <class 'hyperion.np.hyper_np_model.NPModel'>, 'NSbSw': <class 'hyperion.np.transforms.sb_sw.NSbSw'>, 'Normal': <class 'hyperion.np.pdfs.core.normal.Normal'>, 'NormalDiagCov': <class 'hyperion.np.pdfs.core.normal_diag_cov.NormalDiagCov'>, 'PCA': <class 'hyperion.np.transforms.pca.PCA'>, 'PDF': <class 'hyperion.np.pdfs.core.pdf.PDF'>, 'PLDA': <class 'hyperion.np.pdfs.plda.plda.PLDA'>, 'PLDABase': <class 'hyperion.np.pdfs.plda.plda_base.PLDABase'>, 'QScoringHomoGBE': <class 'hyperion.np.classifiers.q_scoring_homo_gbe.QScoringHomoGBE'>, 'SNorm': <class 'hyperion.np.score_norm.s_norm.SNorm'>, 'SPLDA': <class 'hyperion.np.pdfs.plda.splda.SPLDA'>, 'SVMC': <class 'hyperion.np.classifiers.svmc.SVMC'>, 'SbSw': <class 'hyperion.np.transforms.sb_sw.SbSw'>, 'ScoreNorm': <class 'hyperion.np.score_norm.score_norm.ScoreNorm'>, 'SklTSNE': <class 'hyperion.np.transforms.skl_tsne.SklTSNE'>, 'SpectralClustering': <class 'hyperion.np.clustering.spectral_clustering.SpectralClustering'>, 'TNorm': <class 'hyperion.np.score_norm.t_norm.TNorm'>, 'TZNorm': <class 'hyperion.np.score_norm.tz_norm.TZNorm'>, 'TransformList': <class 'hyperion.np.transforms.transform_list.TransformList'>, 'ZNorm': <class 'hyperion.np.score_norm.z_norm.ZNorm'>, 'ZTNorm': <class 'hyperion.np.score_norm.zt_norm.ZTNorm'>}
save(file_path: str | Path) None

Saves the model to file.

Parameters:

file_path – filename path.

to_json(**kwargs: Any) str

Return model configuration serialized as JSON.

Parameters:

**kwargs – Extra keyword arguments forwarded to json.dumps().

Returns:

JSON string with model configuration.

class hyperion.np.pdfs.plda.factory.PLDAFactory[source]

Class to create PLDA objects.

Examples

>>> from hyperion.np.pdfs.plda.factory import PLDAFactory, PLDAType
>>> model = PLDAFactory.create(
...     plda_type=PLDAType.SPLDA,
...     y_dim=64,
...     fullcov_W=True,
...     update_mu=True,
... )
static create(plda_type: PLDAType, y_dim: int | None = None, z_dim: int | None = None, fullcov_W: bool = True, update_mu: bool = True, update_V: bool = True, update_U: bool = True, update_B: bool = True, update_W: bool = True, update_D: bool = True, floor_iD: float = 1e-05, prior: FRPLDA | SPLDA | PLDA | str | Path | None = None, r_mu: float = 24.0, r_V: float = 128.0, r_B: float = 256.0, r_W: float | None = None, name: str = 'plda', **kwargs: Any) FRPLDA | SPLDA | PLDA[source]

Instantiates a PLDA model using the given configuration.

Parameters:
  • plda_type – Backend variant to create.

  • y_dim – Speaker-factor dimensionality (used by SPLDA/PLDA).

  • z_dim – Channel-factor dimensionality (used by PLDA).

  • fullcov_W – Whether W is full covariance for FRPLDA/SPLDA.

  • update_mu – Whether mu is updated during EM.

  • update_V – Whether V is updated (if applicable).

  • update_U – Whether U is updated (PLDA only).

  • update_B – Whether B is updated (FRPLDA).

  • update_W – Whether W is updated.

  • update_D – Whether D is updated (PLDA).

  • floor_iD – Minimum inverse variance allowed for D.

  • prior – Optional prior PLDA model for Bayesian adaptation.

  • r_mu – Relevance factor for adapting mu.

  • r_V – Relevance factor for adapting V.

  • r_B – Relevance factor for adapting B.

  • r_W – Relevance factor for adapting W.

  • name – Optional model name.

  • **kwargs – Additional keyword arguments forwarded to the constructor.

Returns:

An initialized PLDA-family instance.

static load_plda(plda_type: PLDAType | str, model_file: str) FRPLDA | SPLDA | PLDA[source]

Loads a serialized PLDA model from disk.

Parameters:
  • plda_type – Type of PLDA stored in model_file.

  • model_file – Path to the serialized model.

Returns:

Loaded PLDA instance.

static filter_args(**kwargs: Any) Dict[str, Any][source]

Filters keyword arguments to those accepted by create().

Parameters:

**kwargs – Keyword arguments passed from higher-level configs.

Returns:

Dictionary containing only parameters accepted by create().

static add_class_args(parser: ArgumentParser, prefix: str | None = None) None[source]

Adds PLDA construction arguments to an ArgumentParser.

Parameters:
  • parser – Target CLI parser.

  • prefix – Optional nested prefix for configuration groups.

static filter_eval_args(**kwargs: Any) Dict[str, Any][source]

Filters keyword arguments to those used during evaluation.

Parameters:

**kwargs – Candidate evaluation parameters.

Returns:

Dictionary containing only valid evaluation argument names.

static add_llr_args(parser: ArgumentParser, prefix: str | None = None) None[source]

Adds LLR scoring arguments to an ArgumentParser.

Parameters:
  • parser – Target CLI parser.

  • prefix – Optional nested prefix for configuration groups.

TransformList preserves the order of preprocessing operations. PLDA training expects one embedding row per class-id row. A score matrix returned by a PLDA backend uses enrollment rows and test columns. Detailed model choices are documented in PLDA Tutorial (NumPy).

Calibration

class hyperion.np.calibration.gauss_calibration.GaussCalibration(mu1: float | None = None, mu2: float | None = None, sigma2: float | None = None, prior: float = 0.5, **kwargs: Any)[source]
Class for supervised Gaussian calibration.

The model assumes that target and non-target score distributions are Gaussians with shared covariance.

mu1

mean of the target score distribution.

mu2

mean of the non-target score distribution.

sigma2

shared variance of the target and non-target score distributions.

prior

prior prob. for target trials.

__init__(mu1: float | None = None, mu2: float | None = None, sigma2: float | None = None, prior: float = 0.5, **kwargs: Any) None[source]

Initialize base model metadata.

Parameters:
  • name – Optional identifier for the model instance. If None, the class name is used.

  • **kwargs – Reserved for subclass compatibility.

is_init() bool[source]
Returns:

True if the model has been initialized.

_compute_scale_bias() None[source]

Computes the scaling and bias of the scores given the Gaussians means and variance.

fit(x: ndarray, y: ndarray, sample_weight: ndarray | None = None) None[source]

Estimates the parameters of the model.

Parameters:
  • x – score numpy tensor (num_scores,).

  • y – trial labels (0,1) numpy tensor (num_scores,).

  • sample_weight – weight of each score in the calculation of the Gaussian parameters (num_scores,).

predict(x: float | ndarray) float | ndarray[source]

Applies the calibration function.

Parameters:

x – score vector (num_scores,)

Returns:

Vector with calibrated scores.

__call__(x: float | ndarray) float | ndarray[source]

Applies the calibration function.

Parameters:

x – score vector (num_scores,)

Returns:

Vector with calibrated scores.

save_params(f: Any) None[source]

Saves model parameters into the file.

Parameters:

f – file handle.

classmethod load_params(f: Any, config: Dict[str, Any]) GaussCalibration[source]

Initializes the model from the configuration and loads the model parameters from file.

Parameters:
  • f – file handle.

  • config – configuration dictionary.

Returns:

Model object.

static _bootstrap_registry() None

Import common NP subpackages so subclasses register themselves.

static _find_module_for_class_name(class_name: str) str | None

Find module path for a registered class name by scanning NP sources.

Parameters:

class_name – Target class name to locate.

Returns:

Dotted module path if found, otherwise None.

static _load_params_to_dict(f: File, name: str | None, params: Sequence[str], dtypes: type | Mapping[str, Any] | None = None) Dict[str, ndarray | None]

Loads the model parameters from file to a dictionary.

Parameters:
  • f – file handle.

  • name – model identifier or None.

  • params – parameter names.

  • dtypes – dictionary containing the dtypes of the parameters.

Returns:

Dictionary with model parameters.

_save_params_from_dict(f: File, params: Mapping[str, Any], dtypes: type | Mapping[str, Any] | None = None) None

Saves a dictionary of model parameters into the file.

Parameters:
  • f – file handle.

  • params – dictionary of model parameters.

  • dtypes – dictionary indicating the dtypes of the model parameters.

static auto_load(file_path: str | Path, extra_objs: Dict[str, Type[HyperNPModel]] | None = None) HyperNPModel

Auto-load a serialized model based on the saved class_name.

Parameters:
  • file_path – Path to model file.

  • extra_objs – Optional mapping from class name to class object used as a fallback when class is not yet registered.

Returns:

Instantiated model loaded from file_path.

Raises:

Exception – If the class cannot be resolved/imported.

clone() HyperNPModel

Returns a clone of the model.

copy() HyperNPModel

Returns a clone of the model.

fit_generator(x: Any, x_val: Any | None = None) None

Trains the model from a data generator function.

Parameters:
  • x – train data generation function.

  • x_val – validation data generation function.

Raises:

NotImplementedError – If not implemented by a subclass.

get_config() Dict[str, Any]

Returns the model configuration dict.

init_to_false() None

Sets the model as non initialized.

initialize() None

Initialize model parameters/state.

Subclasses can override this method when they have lazy initialization logic.

classmethod load(file_path: str | Path) HyperNPModel

Loads the model from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Model object.

classmethod load_config(file_path: str | Path) Dict[str, Any]

Loads the model configuration from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Dictionary containing the model configuration.

static load_config_from_json(json_str: str) Dict[str, Any]

Convert JSON configuration string to dictionary.

registry: ClassVar[Dict[str, Type['HyperNPModel']]] = {'AHC': <class 'hyperion.np.clustering.ahc.AHC'>, 'AdaptSNorm': <class 'hyperion.np.score_norm.adapt_s_norm.AdaptSNorm'>, 'BinaryLogisticRegression': <class 'hyperion.np.classifiers.binary_logistic_regression.BinaryLogisticRegression'>, 'CORAL': <class 'hyperion.np.transforms.coral.CORAL'>, 'CentWhiten': <class 'hyperion.np.transforms.cent_whiten.CentWhiten'>, 'CentWhitenUP': <class 'hyperion.np.transforms.cent_whiten_up.CentWhitenUP'>, 'ExpFamily': <class 'hyperion.np.pdfs.core.exp_family.ExpFamily'>, 'ExpFamilyMixture': <class 'hyperion.np.pdfs.mixtures.exp_family_mixture.ExpFamilyMixture'>, 'FRPLDA': <class 'hyperion.np.pdfs.plda.frplda.FRPLDA'>, 'GMM': <class 'hyperion.np.pdfs.mixtures.gmm.GMM'>, 'GMMDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_diag_cov.GMMDiagCov'>, 'GMMTiedDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_tied_diag_cov.GMMTiedDiagCov'>, 'GaussCalibration': <class 'hyperion.np.calibration.gauss_calibration.GaussCalibration'>, 'Gaussianizer': <class 'hyperion.np.transforms.gaussianizer.Gaussianizer'>, 'GreedyFusionBinaryLR': <class 'hyperion.np.classifiers.greedy_fusion.GreedyFusionBinaryLR'>, 'HMM': <class 'hyperion.np.pdfs.hmm.hmm.HMM'>, 'JFATotal': <class 'hyperion.np.pdfs.jfa.jfa_total.JFATotal'>, 'KMeans': <class 'hyperion.np.clustering.kmeans.KMeans'>, 'LDA': <class 'hyperion.np.transforms.lda.LDA'>, 'LNorm': <class 'hyperion.np.transforms.lnorm.LNorm'>, 'LNormUP': <class 'hyperion.np.transforms.lnorm_up.LNormUP'>, 'LinearGBE': <class 'hyperion.np.classifiers.linear_gbe.LinearGBE'>, 'LinearGBEUP': <class 'hyperion.np.classifiers.linear_gbe_up.LinearGBEUP'>, 'LinearSVMC': <class 'hyperion.np.classifiers.linear_svmc.LinearSVMC'>, 'LogisticRegression': <class 'hyperion.np.classifiers.logistic_regression.LogisticRegression'>, 'MVN': <class 'hyperion.np.transforms.mvn.MVN'>, 'NAP': <class 'hyperion.np.transforms.nap.NAP'>, 'NDA': <class 'hyperion.np.transforms.nda.NDA'>, 'NPModel': <class 'hyperion.np.hyper_np_model.NPModel'>, 'NSbSw': <class 'hyperion.np.transforms.sb_sw.NSbSw'>, 'Normal': <class 'hyperion.np.pdfs.core.normal.Normal'>, 'NormalDiagCov': <class 'hyperion.np.pdfs.core.normal_diag_cov.NormalDiagCov'>, 'PCA': <class 'hyperion.np.transforms.pca.PCA'>, 'PDF': <class 'hyperion.np.pdfs.core.pdf.PDF'>, 'PLDA': <class 'hyperion.np.pdfs.plda.plda.PLDA'>, 'PLDABase': <class 'hyperion.np.pdfs.plda.plda_base.PLDABase'>, 'QScoringHomoGBE': <class 'hyperion.np.classifiers.q_scoring_homo_gbe.QScoringHomoGBE'>, 'SNorm': <class 'hyperion.np.score_norm.s_norm.SNorm'>, 'SPLDA': <class 'hyperion.np.pdfs.plda.splda.SPLDA'>, 'SVMC': <class 'hyperion.np.classifiers.svmc.SVMC'>, 'SbSw': <class 'hyperion.np.transforms.sb_sw.SbSw'>, 'ScoreNorm': <class 'hyperion.np.score_norm.score_norm.ScoreNorm'>, 'SklTSNE': <class 'hyperion.np.transforms.skl_tsne.SklTSNE'>, 'SpectralClustering': <class 'hyperion.np.clustering.spectral_clustering.SpectralClustering'>, 'TNorm': <class 'hyperion.np.score_norm.t_norm.TNorm'>, 'TZNorm': <class 'hyperion.np.score_norm.tz_norm.TZNorm'>, 'TransformList': <class 'hyperion.np.transforms.transform_list.TransformList'>, 'ZNorm': <class 'hyperion.np.score_norm.z_norm.ZNorm'>, 'ZTNorm': <class 'hyperion.np.score_norm.zt_norm.ZTNorm'>}
save(file_path: str | Path) None

Saves the model to file.

Parameters:

file_path – filename path.

to_json(**kwargs: Any) str

Return model configuration serialized as JSON.

Parameters:

**kwargs – Extra keyword arguments forwarded to json.dumps().

Returns:

JSON string with model configuration.

GaussCalibration learns an affine score mapping from one-dimensional development scores and binary labels (target is 1, non-target is 0). It requires both classes and a non-zero shared variance. For discriminative calibration, use BinaryLogisticRegression from NumPy Backend API.

Score normalization

class hyperion.np.score_norm.score_norm.ScoreNorm(norm_var: bool = True, std_floor: float = 1e-05, **kwargs: Any)[source]

Base class for score normalization

std_floor

floor for standard deviations.

__init__(norm_var: bool = True, std_floor: float = 1e-05, **kwargs: Any) None[source]

Initialize base model metadata.

Parameters:
  • name – Optional identifier for the model instance. If None, the class name is used.

  • **kwargs – Reserved for subclass compatibility.

forward(**kwargs: Any) Any[source]

Overloads predict function.

__call__(*args: Any, **kwargs: Any) Any[source]

Overloads predict function.

get_config() Dict[str, Any][source]

Returns the model configuration dict.

static _bootstrap_registry() None

Import common NP subpackages so subclasses register themselves.

static _find_module_for_class_name(class_name: str) str | None

Find module path for a registered class name by scanning NP sources.

Parameters:

class_name – Target class name to locate.

Returns:

Dotted module path if found, otherwise None.

static _load_params_to_dict(f: File, name: str | None, params: Sequence[str], dtypes: type | Mapping[str, Any] | None = None) Dict[str, ndarray | None]

Loads the model parameters from file to a dictionary.

Parameters:
  • f – file handle.

  • name – model identifier or None.

  • params – parameter names.

  • dtypes – dictionary containing the dtypes of the parameters.

Returns:

Dictionary with model parameters.

_save_params_from_dict(f: File, params: Mapping[str, Any], dtypes: type | Mapping[str, Any] | None = None) None

Saves a dictionary of model parameters into the file.

Parameters:
  • f – file handle.

  • params – dictionary of model parameters.

  • dtypes – dictionary indicating the dtypes of the model parameters.

static auto_load(file_path: str | Path, extra_objs: Dict[str, Type[HyperNPModel]] | None = None) HyperNPModel

Auto-load a serialized model based on the saved class_name.

Parameters:
  • file_path – Path to model file.

  • extra_objs – Optional mapping from class name to class object used as a fallback when class is not yet registered.

Returns:

Instantiated model loaded from file_path.

Raises:

Exception – If the class cannot be resolved/imported.

clone() HyperNPModel

Returns a clone of the model.

copy() HyperNPModel

Returns a clone of the model.

fit(x: ndarray, sample_weight: ndarray | None = None, x_val: ndarray | None = None, sample_weight_val: ndarray | None = None) None

Trains the model.

Parameters:
  • x – train data matrix with shape (num_samples, x_dim).

  • sample_weight – weight of each sample in the training loss shape (num_samples,).

  • x_val – validation data matrix with shape (num_val_samples, x_dim).

  • sample_weight_val – weight of each sample in the val. loss.

Raises:

NotImplementedError – If not implemented by a subclass.

fit_generator(x: Any, x_val: Any | None = None) None

Trains the model from a data generator function.

Parameters:
  • x – train data generation function.

  • x_val – validation data generation function.

Raises:

NotImplementedError – If not implemented by a subclass.

init_to_false() None

Sets the model as non initialized.

initialize() None

Initialize model parameters/state.

Subclasses can override this method when they have lazy initialization logic.

property is_init: bool

Returns True if the model has been initialized.

classmethod load(file_path: str | Path) HyperNPModel

Loads the model from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Model object.

classmethod load_config(file_path: str | Path) Dict[str, Any]

Loads the model configuration from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Dictionary containing the model configuration.

static load_config_from_json(json_str: str) Dict[str, Any]

Convert JSON configuration string to dictionary.

classmethod load_params(f: File, config: Dict[str, Any]) HyperNPModel

Initializes the model from the configuration and loads the model parameters from file.

Parameters:
  • f – file handle.

  • config – configuration dictionary.

Returns:

Model object.

registry: ClassVar[Dict[str, Type['HyperNPModel']]] = {'AHC': <class 'hyperion.np.clustering.ahc.AHC'>, 'AdaptSNorm': <class 'hyperion.np.score_norm.adapt_s_norm.AdaptSNorm'>, 'BinaryLogisticRegression': <class 'hyperion.np.classifiers.binary_logistic_regression.BinaryLogisticRegression'>, 'CORAL': <class 'hyperion.np.transforms.coral.CORAL'>, 'CentWhiten': <class 'hyperion.np.transforms.cent_whiten.CentWhiten'>, 'CentWhitenUP': <class 'hyperion.np.transforms.cent_whiten_up.CentWhitenUP'>, 'ExpFamily': <class 'hyperion.np.pdfs.core.exp_family.ExpFamily'>, 'ExpFamilyMixture': <class 'hyperion.np.pdfs.mixtures.exp_family_mixture.ExpFamilyMixture'>, 'FRPLDA': <class 'hyperion.np.pdfs.plda.frplda.FRPLDA'>, 'GMM': <class 'hyperion.np.pdfs.mixtures.gmm.GMM'>, 'GMMDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_diag_cov.GMMDiagCov'>, 'GMMTiedDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_tied_diag_cov.GMMTiedDiagCov'>, 'GaussCalibration': <class 'hyperion.np.calibration.gauss_calibration.GaussCalibration'>, 'Gaussianizer': <class 'hyperion.np.transforms.gaussianizer.Gaussianizer'>, 'GreedyFusionBinaryLR': <class 'hyperion.np.classifiers.greedy_fusion.GreedyFusionBinaryLR'>, 'HMM': <class 'hyperion.np.pdfs.hmm.hmm.HMM'>, 'JFATotal': <class 'hyperion.np.pdfs.jfa.jfa_total.JFATotal'>, 'KMeans': <class 'hyperion.np.clustering.kmeans.KMeans'>, 'LDA': <class 'hyperion.np.transforms.lda.LDA'>, 'LNorm': <class 'hyperion.np.transforms.lnorm.LNorm'>, 'LNormUP': <class 'hyperion.np.transforms.lnorm_up.LNormUP'>, 'LinearGBE': <class 'hyperion.np.classifiers.linear_gbe.LinearGBE'>, 'LinearGBEUP': <class 'hyperion.np.classifiers.linear_gbe_up.LinearGBEUP'>, 'LinearSVMC': <class 'hyperion.np.classifiers.linear_svmc.LinearSVMC'>, 'LogisticRegression': <class 'hyperion.np.classifiers.logistic_regression.LogisticRegression'>, 'MVN': <class 'hyperion.np.transforms.mvn.MVN'>, 'NAP': <class 'hyperion.np.transforms.nap.NAP'>, 'NDA': <class 'hyperion.np.transforms.nda.NDA'>, 'NPModel': <class 'hyperion.np.hyper_np_model.NPModel'>, 'NSbSw': <class 'hyperion.np.transforms.sb_sw.NSbSw'>, 'Normal': <class 'hyperion.np.pdfs.core.normal.Normal'>, 'NormalDiagCov': <class 'hyperion.np.pdfs.core.normal_diag_cov.NormalDiagCov'>, 'PCA': <class 'hyperion.np.transforms.pca.PCA'>, 'PDF': <class 'hyperion.np.pdfs.core.pdf.PDF'>, 'PLDA': <class 'hyperion.np.pdfs.plda.plda.PLDA'>, 'PLDABase': <class 'hyperion.np.pdfs.plda.plda_base.PLDABase'>, 'QScoringHomoGBE': <class 'hyperion.np.classifiers.q_scoring_homo_gbe.QScoringHomoGBE'>, 'SNorm': <class 'hyperion.np.score_norm.s_norm.SNorm'>, 'SPLDA': <class 'hyperion.np.pdfs.plda.splda.SPLDA'>, 'SVMC': <class 'hyperion.np.classifiers.svmc.SVMC'>, 'SbSw': <class 'hyperion.np.transforms.sb_sw.SbSw'>, 'ScoreNorm': <class 'hyperion.np.score_norm.score_norm.ScoreNorm'>, 'SklTSNE': <class 'hyperion.np.transforms.skl_tsne.SklTSNE'>, 'SpectralClustering': <class 'hyperion.np.clustering.spectral_clustering.SpectralClustering'>, 'TNorm': <class 'hyperion.np.score_norm.t_norm.TNorm'>, 'TZNorm': <class 'hyperion.np.score_norm.tz_norm.TZNorm'>, 'TransformList': <class 'hyperion.np.transforms.transform_list.TransformList'>, 'ZNorm': <class 'hyperion.np.score_norm.z_norm.ZNorm'>, 'ZTNorm': <class 'hyperion.np.score_norm.zt_norm.ZTNorm'>}
save(file_path: str | Path) None

Saves the model to file.

Parameters:

file_path – filename path.

save_params(f: File) None

Saves model parameters into the file.

Parameters:

f – file handle.

to_json(**kwargs: Any) str

Return model configuration serialized as JSON.

Parameters:

**kwargs – Extra keyword arguments forwarded to json.dumps().

Returns:

JSON string with model configuration.

class hyperion.np.score_norm.adapt_s_norm.AdaptSNorm(nbest: int = 100, nbest_discard: int = 0, nbest_sel_method: str = 'highest-other-side', **kwargs: Any)[source]

Class for adaptive S-Norm.

\* ``nbest``

Number of cohort samples selected to compute each trial’s statistics.

\* ``nbest_discard``

Number of highest-scoring trials discarded before selection; this can avoid selecting actual target trials.

\* ``std_floor``

Lower bound used for standard deviations inherited from ScoreNorm.

Example:

import numpy as np
from hyperion.np.score_norm import AdaptSNorm

n_enr, n_test, n_coh = 3, 5, 50
scores = np.random.randn(n_enr, n_test)
scores_coh_test = np.random.randn(n_coh, n_test)
scores_enr_coh = np.random.randn(n_enr, n_coh)

as_norm = AdaptSNorm(
    norm_var=True,
    std_floor=1e-5,
    nbest=20,
    nbest_discard=2,
    nbest_sel_method="highest-other-side",
)
scores_as = as_norm.predict(scores, scores_coh_test, scores_enr_coh)
__init__(nbest: int = 100, nbest_discard: int = 0, nbest_sel_method: str = 'highest-other-side', **kwargs: Any) None[source]

Initializes adaptive S-Norm configuration.

Parameters:
  • nbest – Number of cohort elements used for trial-dependent statistics.

  • nbest_discard – Number of top cohort scores discarded before selecting the nbest samples.

  • nbest_sel_method – Cohort selection strategy. Supported values are "highest-other-side" and "highest-same-side".

  • kwargs – Parameters forwarded to ScoreNorm.

get_config() Dict[str, Any][source]

Returns the model configuration dict.

__call__(scores: ndarray, scores_coh_test: ndarray, scores_enr_coh: ndarray, mask_coh_test: ndarray | None = None, mask_enr_coh: ndarray | None = None, return_stats: bool = False) ndarray | Tuple[ndarray, ndarray, ndarray | float, ndarray, ndarray | float][source]

Alias for predict().

Parameters:
  • scores – Score matrix enroll vs. test.

  • scores_coh_test – Score matrix cohort vs. test.

  • scores_enr_coh – Score matrix enroll vs. cohort.

  • mask_coh_test – Optional boolean mask for scores_coh_test.

  • mask_enr_coh – Optional boolean mask for scores_enr_coh.

  • return_stats – If True, also returns normalization statistics.

Returns:

Normalized scores, or normalized scores with statistics.

predict(scores: ndarray, scores_coh_test: ndarray, scores_enr_coh: ndarray, mask_coh_test: ndarray | None = None, mask_enr_coh: ndarray | None = None, return_stats: bool = False) ndarray | Tuple[ndarray, ndarray, ndarray | float, ndarray, ndarray | float][source]

Normalizes the scores.

Parameters:
  • scores – score matrix enroll vs. test.

  • scores_coh_test – score matrix cohort vs. test.

  • scores_enr_coh – score matrix enroll vs cohort.

  • mask_coh_test – binary matrix to mask out target trials from cohort vs test matrix.

  • mask_enr_coh – binary matrix to mask out target trials from enroll vs. cohort matrix.

_norm_highest_other_side0(scores: ndarray, scores_coh_test: ndarray, scores_enr_coh: ndarray, mask_coh_test: ndarray | None, mask_enr_coh: ndarray | None, return_stats: bool, nbest: int) ndarray | Tuple[ndarray, ndarray, ndarray | float, ndarray, ndarray | float][source]

Slow reference implementation for “highest-other-side” selection.

Parameters:
  • scores – Score matrix enroll vs. test.

  • scores_coh_test – Score matrix cohort vs. test.

  • scores_enr_coh – Score matrix enroll vs. cohort.

  • mask_coh_test – Optional boolean mask for scores_coh_test.

  • mask_enr_coh – Optional boolean mask for scores_enr_coh.

  • return_stats – If True, also returns normalization statistics.

  • nbest – Number of selected cohort samples per trial.

Returns:

Normalized scores, or normalized scores with statistics.

_norm_highest_other_side(scores: ndarray, scores_coh_test: ndarray, scores_enr_coh: ndarray, mask_coh_test: ndarray | None, mask_enr_coh: ndarray | None, return_stats: bool, nbest: int) ndarray | Tuple[ndarray, ndarray, ndarray | float, ndarray, ndarray | float][source]

Vectorized implementation for “highest-other-side” selection.

Parameters:
  • scores – Score matrix enroll vs. test.

  • scores_coh_test – Score matrix cohort vs. test.

  • scores_enr_coh – Score matrix enroll vs. cohort.

  • mask_coh_test – Optional boolean mask for scores_coh_test.

  • mask_enr_coh – Optional boolean mask for scores_enr_coh.

  • return_stats – If True, also returns normalization statistics.

  • nbest – Number of selected cohort samples per trial.

Returns:

Normalized scores, or normalized scores with statistics.

_norm_highest_same_side0(scores: ndarray, scores_coh_test: ndarray, scores_enr_coh: ndarray, mask_coh_test: ndarray | None, mask_enr_coh: ndarray | None, return_stats: bool, nbest: int) ndarray | Tuple[ndarray, ndarray, ndarray | float, ndarray, ndarray | float][source]

Slow reference implementation for “highest-same-side” selection.

Parameters:
  • scores – Score matrix enroll vs. test.

  • scores_coh_test – Score matrix cohort vs. test.

  • scores_enr_coh – Score matrix enroll vs. cohort.

  • mask_coh_test – Optional boolean mask for scores_coh_test.

  • mask_enr_coh – Optional boolean mask for scores_enr_coh.

  • return_stats – If True, also returns normalization statistics.

  • nbest – Number of selected cohort samples per trial.

Returns:

Normalized scores, or normalized scores with statistics.

_norm_highest_same_side(scores: ndarray, scores_coh_test: ndarray, scores_enr_coh: ndarray, mask_coh_test: ndarray | None, mask_enr_coh: ndarray | None, return_stats: bool, nbest: int) ndarray | Tuple[ndarray, ndarray, ndarray | float, ndarray, ndarray | float][source]

Vectorized implementation for “highest-same-side” selection.

Parameters:
  • scores – Score matrix enroll vs. test.

  • scores_coh_test – Score matrix cohort vs. test.

  • scores_enr_coh – Score matrix enroll vs. cohort.

  • mask_coh_test – Optional boolean mask for scores_coh_test.

  • mask_enr_coh – Optional boolean mask for scores_enr_coh.

  • return_stats – If True, also returns normalization statistics.

  • nbest – Number of selected cohort samples per trial.

Returns:

Normalized scores, or normalized scores with statistics.

static _bootstrap_registry() None

Import common NP subpackages so subclasses register themselves.

static _find_module_for_class_name(class_name: str) str | None

Find module path for a registered class name by scanning NP sources.

Parameters:

class_name – Target class name to locate.

Returns:

Dotted module path if found, otherwise None.

static _load_params_to_dict(f: File, name: str | None, params: Sequence[str], dtypes: type | Mapping[str, Any] | None = None) Dict[str, ndarray | None]

Loads the model parameters from file to a dictionary.

Parameters:
  • f – file handle.

  • name – model identifier or None.

  • params – parameter names.

  • dtypes – dictionary containing the dtypes of the parameters.

Returns:

Dictionary with model parameters.

_save_params_from_dict(f: File, params: Mapping[str, Any], dtypes: type | Mapping[str, Any] | None = None) None

Saves a dictionary of model parameters into the file.

Parameters:
  • f – file handle.

  • params – dictionary of model parameters.

  • dtypes – dictionary indicating the dtypes of the model parameters.

static auto_load(file_path: str | Path, extra_objs: Dict[str, Type[HyperNPModel]] | None = None) HyperNPModel

Auto-load a serialized model based on the saved class_name.

Parameters:
  • file_path – Path to model file.

  • extra_objs – Optional mapping from class name to class object used as a fallback when class is not yet registered.

Returns:

Instantiated model loaded from file_path.

Raises:

Exception – If the class cannot be resolved/imported.

clone() HyperNPModel

Returns a clone of the model.

copy() HyperNPModel

Returns a clone of the model.

fit(x: ndarray, sample_weight: ndarray | None = None, x_val: ndarray | None = None, sample_weight_val: ndarray | None = None) None

Trains the model.

Parameters:
  • x – train data matrix with shape (num_samples, x_dim).

  • sample_weight – weight of each sample in the training loss shape (num_samples,).

  • x_val – validation data matrix with shape (num_val_samples, x_dim).

  • sample_weight_val – weight of each sample in the val. loss.

Raises:

NotImplementedError – If not implemented by a subclass.

fit_generator(x: Any, x_val: Any | None = None) None

Trains the model from a data generator function.

Parameters:
  • x – train data generation function.

  • x_val – validation data generation function.

Raises:

NotImplementedError – If not implemented by a subclass.

forward(**kwargs: Any) Any

Overloads predict function.

init_to_false() None

Sets the model as non initialized.

initialize() None

Initialize model parameters/state.

Subclasses can override this method when they have lazy initialization logic.

property is_init: bool

Returns True if the model has been initialized.

classmethod load(file_path: str | Path) HyperNPModel

Loads the model from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Model object.

classmethod load_config(file_path: str | Path) Dict[str, Any]

Loads the model configuration from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Dictionary containing the model configuration.

static load_config_from_json(json_str: str) Dict[str, Any]

Convert JSON configuration string to dictionary.

classmethod load_params(f: File, config: Dict[str, Any]) HyperNPModel

Initializes the model from the configuration and loads the model parameters from file.

Parameters:
  • f – file handle.

  • config – configuration dictionary.

Returns:

Model object.

registry: ClassVar[Dict[str, Type['HyperNPModel']]] = {'AHC': <class 'hyperion.np.clustering.ahc.AHC'>, 'AdaptSNorm': <class 'hyperion.np.score_norm.adapt_s_norm.AdaptSNorm'>, 'BinaryLogisticRegression': <class 'hyperion.np.classifiers.binary_logistic_regression.BinaryLogisticRegression'>, 'CORAL': <class 'hyperion.np.transforms.coral.CORAL'>, 'CentWhiten': <class 'hyperion.np.transforms.cent_whiten.CentWhiten'>, 'CentWhitenUP': <class 'hyperion.np.transforms.cent_whiten_up.CentWhitenUP'>, 'ExpFamily': <class 'hyperion.np.pdfs.core.exp_family.ExpFamily'>, 'ExpFamilyMixture': <class 'hyperion.np.pdfs.mixtures.exp_family_mixture.ExpFamilyMixture'>, 'FRPLDA': <class 'hyperion.np.pdfs.plda.frplda.FRPLDA'>, 'GMM': <class 'hyperion.np.pdfs.mixtures.gmm.GMM'>, 'GMMDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_diag_cov.GMMDiagCov'>, 'GMMTiedDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_tied_diag_cov.GMMTiedDiagCov'>, 'GaussCalibration': <class 'hyperion.np.calibration.gauss_calibration.GaussCalibration'>, 'Gaussianizer': <class 'hyperion.np.transforms.gaussianizer.Gaussianizer'>, 'GreedyFusionBinaryLR': <class 'hyperion.np.classifiers.greedy_fusion.GreedyFusionBinaryLR'>, 'HMM': <class 'hyperion.np.pdfs.hmm.hmm.HMM'>, 'JFATotal': <class 'hyperion.np.pdfs.jfa.jfa_total.JFATotal'>, 'KMeans': <class 'hyperion.np.clustering.kmeans.KMeans'>, 'LDA': <class 'hyperion.np.transforms.lda.LDA'>, 'LNorm': <class 'hyperion.np.transforms.lnorm.LNorm'>, 'LNormUP': <class 'hyperion.np.transforms.lnorm_up.LNormUP'>, 'LinearGBE': <class 'hyperion.np.classifiers.linear_gbe.LinearGBE'>, 'LinearGBEUP': <class 'hyperion.np.classifiers.linear_gbe_up.LinearGBEUP'>, 'LinearSVMC': <class 'hyperion.np.classifiers.linear_svmc.LinearSVMC'>, 'LogisticRegression': <class 'hyperion.np.classifiers.logistic_regression.LogisticRegression'>, 'MVN': <class 'hyperion.np.transforms.mvn.MVN'>, 'NAP': <class 'hyperion.np.transforms.nap.NAP'>, 'NDA': <class 'hyperion.np.transforms.nda.NDA'>, 'NPModel': <class 'hyperion.np.hyper_np_model.NPModel'>, 'NSbSw': <class 'hyperion.np.transforms.sb_sw.NSbSw'>, 'Normal': <class 'hyperion.np.pdfs.core.normal.Normal'>, 'NormalDiagCov': <class 'hyperion.np.pdfs.core.normal_diag_cov.NormalDiagCov'>, 'PCA': <class 'hyperion.np.transforms.pca.PCA'>, 'PDF': <class 'hyperion.np.pdfs.core.pdf.PDF'>, 'PLDA': <class 'hyperion.np.pdfs.plda.plda.PLDA'>, 'PLDABase': <class 'hyperion.np.pdfs.plda.plda_base.PLDABase'>, 'QScoringHomoGBE': <class 'hyperion.np.classifiers.q_scoring_homo_gbe.QScoringHomoGBE'>, 'SNorm': <class 'hyperion.np.score_norm.s_norm.SNorm'>, 'SPLDA': <class 'hyperion.np.pdfs.plda.splda.SPLDA'>, 'SVMC': <class 'hyperion.np.classifiers.svmc.SVMC'>, 'SbSw': <class 'hyperion.np.transforms.sb_sw.SbSw'>, 'ScoreNorm': <class 'hyperion.np.score_norm.score_norm.ScoreNorm'>, 'SklTSNE': <class 'hyperion.np.transforms.skl_tsne.SklTSNE'>, 'SpectralClustering': <class 'hyperion.np.clustering.spectral_clustering.SpectralClustering'>, 'TNorm': <class 'hyperion.np.score_norm.t_norm.TNorm'>, 'TZNorm': <class 'hyperion.np.score_norm.tz_norm.TZNorm'>, 'TransformList': <class 'hyperion.np.transforms.transform_list.TransformList'>, 'ZNorm': <class 'hyperion.np.score_norm.z_norm.ZNorm'>, 'ZTNorm': <class 'hyperion.np.score_norm.zt_norm.ZTNorm'>}
save(file_path: str | Path) None

Saves the model to file.

Parameters:

file_path – filename path.

save_params(f: File) None

Saves model parameters into the file.

Parameters:

f – file handle.

to_json(**kwargs: Any) str

Return model configuration serialized as JSON.

Parameters:

**kwargs – Extra keyword arguments forwarded to json.dumps().

Returns:

JSON string with model configuration.

Score normalization is a cohort operation, not a classifier. Adaptive S-Norm accepts three matrices: enrollment-versus-test scores, cohort-versus-test scores, and enrollment-versus-cohort scores. Cohort dimensions must agree with the corresponding rows or columns. Mask unavailable cohort trials instead of silently changing matrix alignment.

Clustering and diarization

class hyperion.np.clustering.ahc.AHC(method: str = 'average', metric: str = 'llr', **kwargs: Any)[source]

Agglomerative Hierarchical Clustering class.

method

linkage method to calculate the distance between a new agglomerated cluster and the rest of clusters. This can be [“average”, “single”, “complete”, “weighted”, “centroid”, “median”, “ward”]. See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html

metric

indicates the type of metric used to calculate the input scores. It can be: “llr” (log-likelihood ratios), “prob” (probabilities), “distance”: (distance metric).

Example

>>> import numpy as np
>>> from hyperion.np.clustering.ahc import AHC
>>> x = np.array([
...     [0.0, 0.9, 0.2, 0.1],
...     [0.9, 0.0, 0.3, 0.2],
...     [0.2, 0.3, 0.0, 0.8],
...     [0.1, 0.2, 0.8, 0.0],
... ], dtype=np.float32)
>>> ahc = AHC(method="average", metric="llr")
>>> ahc.fit(x)
>>> clusters_thr = ahc.get_flat_clusters(t=0.5, criterion="threshold")
>>> clusters_k2 = ahc.get_flat_clusters(t=2, criterion="num_clusters")
__init__(method: str = 'average', metric: str = 'llr', **kwargs: Any) None[source]

Initialize base model metadata.

Parameters:
  • name – Optional identifier for the model instance. If None, the class name is used.

  • **kwargs – Reserved for subclass compatibility.

get_config() Dict[str, Any][source]

Returns the model configuration dict.

fit(x: ndarray, mask: ndarray | None = None) None[source]
Performs the clustering.

It stores the AHC tree in the Z property of the object.

Parameters:
  • x – input score matrix (num_samples, num_samples). It will use the upper triangular matrix only.

  • mask – boolean mask where False in position i,j means that nodes i and j should not be merged.

get_flat_clusters(t: int | float, criterion: str = 'threshold') ndarray[source]

Computes the flat clusters from the AHC tree.

Parameters:
  • t – threshold or number of clusters

  • criterion"threshold" selects scores above the threshold for LLR/probability inputs (or distances below it). "num_clusters" selects the requested number of clusters.

Returns:

Cluster assignments for x as a NumPy integer vector (num_samples,).

get_flat_clusters_from_num_clusters(num_clusters: int) ndarray[source]

Computes the flat clusters from the AHC tree using num_clusters criterion”

get_flat_clusters_from_thr(thr: float) ndarray[source]

Computes the flat clusters from the AHC tree using threshold criterion”

compute_flat_clusters() None[source]

Computes the flat clusters for all possible number of clusters

Returns:

numpy matrix (num_samples, num_samples) where row i contains the clusters assignments for the case of choosing num_samples - i clusters.

evaluate_homogeneity_completeness_tradeoff(true_labels: ndarray) Tuple[ndarray, ndarray][source]
Evaluates the curve homogeneity versus completeness where

Homogeneity: each cluster contains only members of a single class. (cluster purity) Completeness: all members of a given class are assigned to the same cluster. (class purity)

Parameters:

true_labels – true cluster labels

Returns:

homogeneity vector (num_samples,) completeness vector (num_samples,)

static _bootstrap_registry() None

Import common NP subpackages so subclasses register themselves.

static _find_module_for_class_name(class_name: str) str | None

Find module path for a registered class name by scanning NP sources.

Parameters:

class_name – Target class name to locate.

Returns:

Dotted module path if found, otherwise None.

static _load_params_to_dict(f: File, name: str | None, params: Sequence[str], dtypes: type | Mapping[str, Any] | None = None) Dict[str, ndarray | None]

Loads the model parameters from file to a dictionary.

Parameters:
  • f – file handle.

  • name – model identifier or None.

  • params – parameter names.

  • dtypes – dictionary containing the dtypes of the parameters.

Returns:

Dictionary with model parameters.

_save_params_from_dict(f: File, params: Mapping[str, Any], dtypes: type | Mapping[str, Any] | None = None) None

Saves a dictionary of model parameters into the file.

Parameters:
  • f – file handle.

  • params – dictionary of model parameters.

  • dtypes – dictionary indicating the dtypes of the model parameters.

static auto_load(file_path: str | Path, extra_objs: Dict[str, Type[HyperNPModel]] | None = None) HyperNPModel

Auto-load a serialized model based on the saved class_name.

Parameters:
  • file_path – Path to model file.

  • extra_objs – Optional mapping from class name to class object used as a fallback when class is not yet registered.

Returns:

Instantiated model loaded from file_path.

Raises:

Exception – If the class cannot be resolved/imported.

clone() HyperNPModel

Returns a clone of the model.

copy() HyperNPModel

Returns a clone of the model.

fit_generator(x: Any, x_val: Any | None = None) None

Trains the model from a data generator function.

Parameters:
  • x – train data generation function.

  • x_val – validation data generation function.

Raises:

NotImplementedError – If not implemented by a subclass.

init_to_false() None

Sets the model as non initialized.

initialize() None

Initialize model parameters/state.

Subclasses can override this method when they have lazy initialization logic.

property is_init: bool

Returns True if the model has been initialized.

classmethod load(file_path: str | Path) HyperNPModel

Loads the model from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Model object.

classmethod load_config(file_path: str | Path) Dict[str, Any]

Loads the model configuration from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Dictionary containing the model configuration.

static load_config_from_json(json_str: str) Dict[str, Any]

Convert JSON configuration string to dictionary.

classmethod load_params(f: File, config: Dict[str, Any]) HyperNPModel

Initializes the model from the configuration and loads the model parameters from file.

Parameters:
  • f – file handle.

  • config – configuration dictionary.

Returns:

Model object.

registry: ClassVar[Dict[str, Type['HyperNPModel']]] = {'AHC': <class 'hyperion.np.clustering.ahc.AHC'>, 'AdaptSNorm': <class 'hyperion.np.score_norm.adapt_s_norm.AdaptSNorm'>, 'BinaryLogisticRegression': <class 'hyperion.np.classifiers.binary_logistic_regression.BinaryLogisticRegression'>, 'CORAL': <class 'hyperion.np.transforms.coral.CORAL'>, 'CentWhiten': <class 'hyperion.np.transforms.cent_whiten.CentWhiten'>, 'CentWhitenUP': <class 'hyperion.np.transforms.cent_whiten_up.CentWhitenUP'>, 'ExpFamily': <class 'hyperion.np.pdfs.core.exp_family.ExpFamily'>, 'ExpFamilyMixture': <class 'hyperion.np.pdfs.mixtures.exp_family_mixture.ExpFamilyMixture'>, 'FRPLDA': <class 'hyperion.np.pdfs.plda.frplda.FRPLDA'>, 'GMM': <class 'hyperion.np.pdfs.mixtures.gmm.GMM'>, 'GMMDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_diag_cov.GMMDiagCov'>, 'GMMTiedDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_tied_diag_cov.GMMTiedDiagCov'>, 'GaussCalibration': <class 'hyperion.np.calibration.gauss_calibration.GaussCalibration'>, 'Gaussianizer': <class 'hyperion.np.transforms.gaussianizer.Gaussianizer'>, 'GreedyFusionBinaryLR': <class 'hyperion.np.classifiers.greedy_fusion.GreedyFusionBinaryLR'>, 'HMM': <class 'hyperion.np.pdfs.hmm.hmm.HMM'>, 'JFATotal': <class 'hyperion.np.pdfs.jfa.jfa_total.JFATotal'>, 'KMeans': <class 'hyperion.np.clustering.kmeans.KMeans'>, 'LDA': <class 'hyperion.np.transforms.lda.LDA'>, 'LNorm': <class 'hyperion.np.transforms.lnorm.LNorm'>, 'LNormUP': <class 'hyperion.np.transforms.lnorm_up.LNormUP'>, 'LinearGBE': <class 'hyperion.np.classifiers.linear_gbe.LinearGBE'>, 'LinearGBEUP': <class 'hyperion.np.classifiers.linear_gbe_up.LinearGBEUP'>, 'LinearSVMC': <class 'hyperion.np.classifiers.linear_svmc.LinearSVMC'>, 'LogisticRegression': <class 'hyperion.np.classifiers.logistic_regression.LogisticRegression'>, 'MVN': <class 'hyperion.np.transforms.mvn.MVN'>, 'NAP': <class 'hyperion.np.transforms.nap.NAP'>, 'NDA': <class 'hyperion.np.transforms.nda.NDA'>, 'NPModel': <class 'hyperion.np.hyper_np_model.NPModel'>, 'NSbSw': <class 'hyperion.np.transforms.sb_sw.NSbSw'>, 'Normal': <class 'hyperion.np.pdfs.core.normal.Normal'>, 'NormalDiagCov': <class 'hyperion.np.pdfs.core.normal_diag_cov.NormalDiagCov'>, 'PCA': <class 'hyperion.np.transforms.pca.PCA'>, 'PDF': <class 'hyperion.np.pdfs.core.pdf.PDF'>, 'PLDA': <class 'hyperion.np.pdfs.plda.plda.PLDA'>, 'PLDABase': <class 'hyperion.np.pdfs.plda.plda_base.PLDABase'>, 'QScoringHomoGBE': <class 'hyperion.np.classifiers.q_scoring_homo_gbe.QScoringHomoGBE'>, 'SNorm': <class 'hyperion.np.score_norm.s_norm.SNorm'>, 'SPLDA': <class 'hyperion.np.pdfs.plda.splda.SPLDA'>, 'SVMC': <class 'hyperion.np.classifiers.svmc.SVMC'>, 'SbSw': <class 'hyperion.np.transforms.sb_sw.SbSw'>, 'ScoreNorm': <class 'hyperion.np.score_norm.score_norm.ScoreNorm'>, 'SklTSNE': <class 'hyperion.np.transforms.skl_tsne.SklTSNE'>, 'SpectralClustering': <class 'hyperion.np.clustering.spectral_clustering.SpectralClustering'>, 'TNorm': <class 'hyperion.np.score_norm.t_norm.TNorm'>, 'TZNorm': <class 'hyperion.np.score_norm.tz_norm.TZNorm'>, 'TransformList': <class 'hyperion.np.transforms.transform_list.TransformList'>, 'ZNorm': <class 'hyperion.np.score_norm.z_norm.ZNorm'>, 'ZTNorm': <class 'hyperion.np.score_norm.zt_norm.ZTNorm'>}
save(file_path: str | Path) None

Saves the model to file.

Parameters:

file_path – filename path.

save_params(f: File) None

Saves model parameters into the file.

Parameters:

f – file handle.

to_json(**kwargs: Any) str

Return model configuration serialized as JSON.

Parameters:

**kwargs – Extra keyword arguments forwarded to json.dumps().

Returns:

JSON string with model configuration.

class hyperion.np.clustering.spectral_clustering.SpectralClustering(laplacian: LaplacianType | str = LaplacianType.norm_sym, num_clusters: int | None = None, max_num_clusters: int | None = None, criterion: SpectralClusteringNumClassCriterion | str = SpectralClusteringNumClassCriterion.max_eigengap, thr_eigengap: float = 0.001, kmeans_epochs: int = 100, kmeans_init_method: KMeansInitMethod | str = KMeansInitMethod.max_dist, num_workers: int = 1, **kwargs: Any)[source]

Spectral Clustering class.

laplacian

Type of graph Laplacian used to compute the spectral embedding.

num_clusters

Fixed number of output clusters. If None, the number of clusters is estimated from eigenvalue statistics.

max_num_clusters

Maximum number of clusters/eigenvectors considered while estimating the number of clusters.

criterion

Criterion used to infer the number of clusters.

thr_eigengap

Threshold used by threshold-based criteria.

kmeans_epochs

Maximum number of epochs used by k-means in embedding space.

kmeans_init_method

Initialization method for k-means seeds.

num_workers

Number of worker threads used by k-means.

Example

>>> import numpy as np
>>> from hyperion.np.clustering.spectral_clustering import SpectralClustering
>>> x = np.array([
...     [0.0, 0.9, 0.1, 0.0],
...     [0.9, 0.0, 0.2, 0.1],
...     [0.1, 0.2, 0.0, 0.8],
...     [0.0, 0.1, 0.8, 0.0],
... ], dtype=np.float32)
>>> sc = SpectralClustering(num_clusters=2, laplacian="norm_sym")
>>> y, num_clusters, eigengap_stats = sc.fit(x)
__init__(laplacian: LaplacianType | str = LaplacianType.norm_sym, num_clusters: int | None = None, max_num_clusters: int | None = None, criterion: SpectralClusteringNumClassCriterion | str = SpectralClusteringNumClassCriterion.max_eigengap, thr_eigengap: float = 0.001, kmeans_epochs: int = 100, kmeans_init_method: KMeansInitMethod | str = KMeansInitMethod.max_dist, num_workers: int = 1, **kwargs: Any) None[source]

Initializes a SpectralClustering model.

Parameters:
  • laplacian – Graph Laplacian type.

  • num_clusters – Fixed number of clusters, or None to estimate.

  • max_num_clusters – Maximum number of clusters considered during automatic selection.

  • criterion – Criterion used to estimate number of clusters.

  • thr_eigengap – Threshold for threshold-based criteria.

  • kmeans_epochs – Number of k-means epochs in embedding space.

  • kmeans_init_method – K-means initialization method.

  • num_workers – Number of threads for k-means.

  • **kwargs – Extra arguments forwarded to HyperNPModel.

get_config() Dict[str, Any][source]

Returns the model configuration dict.

spectral_embedding(x: ndarray) Tuple[ndarray, ndarray][source]

Computes graph spectral embedding.

Parameters:

x – Affinity/similarity matrix with shape (num_nodes, num_nodes).

Returns:

Eigenvalues associated with the selected embedding vectors. eig_vecs: Eigenvectors with shape (num_nodes, num_eigenvectors).

Return type:

eig_vals

spectral_embedding_0(x: ndarray) Tuple[ndarray, ndarray][source]

Computes dense spectral embedding using scipy.linalg.eigh.

Parameters:

x – Dense affinity/similarity matrix with shape (num_nodes, num_nodes).

Returns:

Eigenvalues associated with the selected embedding vectors. eig_vecs: Eigenvectors with shape (num_nodes, num_eigenvectors).

Return type:

eig_vals

compute_eigengap(eig_vals: ndarray) Dict[str, Any][source]

Computes eigengap statistics used for cluster-count prediction.

Parameters:

eig_vals – Sorted eigenvalues (excluding the trivial first one).

Returns:

Dictionary with eigenvalue/eigengap derived statistics.

predict_num_clusters(eigengap_stats: Dict[str, Any] | None) int[source]

Predicts number of clusters from eigengap statistics.

Parameters:

eigengap_stats – Output of compute_eigengap(), or None when self.num_clusters is fixed.

Returns:

Predicted (or fixed) number of clusters.

normalize_eigvecs(eig_vecs: ndarray) ndarray[source]

Applies row-normalization to eigenvectors when required.

Parameters:

eig_vecs – Spectral embedding vectors.

Returns:

Normalized (or unchanged) embedding vectors.

do_kmeans(x: ndarray, num_clusters: int | None = None) ndarray[source]

Runs k-means on spectral embeddings.

Parameters:
  • x – Spectral embeddings with shape (num_samples, emb_dim).

  • num_clusters – Number of clusters. If None, uses x.shape[1] + 1.

Returns:

Cluster assignments with shape (num_samples,).

fit(x: ndarray) Tuple[ndarray, int, Dict[str, Any] | None][source]

Performs spectral clustering.

Parameters:

x – Affinity/similarity matrix with shape (num_nodes, num_nodes).

Returns:

Tuple containing cluster assignments, the selected number of clusters, and optional eigengap statistics.

plot_eigengap_stats(eigengap_stats: Dict[str, Any], num_clusters: int, fig_file: str | Path | None = None) None[source]

Plots eigengap statistics.

Parameters:
  • eigengap_stats – Dictionary returned by compute_eigengap().

  • num_clusters – Selected number of clusters.

  • fig_file – Optional output path to save figure.

Returns:

None.

static add_class_args(parser: ArgumentParser, prefix: str | None = None) None[source]

Adds class arguments to a jsonargparse parser.

Parameters:
  • parser – jsonargparse parser instance.

  • prefix – argument prefix.

Returns:

None.

static _bootstrap_registry() None

Import common NP subpackages so subclasses register themselves.

static _find_module_for_class_name(class_name: str) str | None

Find module path for a registered class name by scanning NP sources.

Parameters:

class_name – Target class name to locate.

Returns:

Dotted module path if found, otherwise None.

static _load_params_to_dict(f: File, name: str | None, params: Sequence[str], dtypes: type | Mapping[str, Any] | None = None) Dict[str, ndarray | None]

Loads the model parameters from file to a dictionary.

Parameters:
  • f – file handle.

  • name – model identifier or None.

  • params – parameter names.

  • dtypes – dictionary containing the dtypes of the parameters.

Returns:

Dictionary with model parameters.

_save_params_from_dict(f: File, params: Mapping[str, Any], dtypes: type | Mapping[str, Any] | None = None) None

Saves a dictionary of model parameters into the file.

Parameters:
  • f – file handle.

  • params – dictionary of model parameters.

  • dtypes – dictionary indicating the dtypes of the model parameters.

static auto_load(file_path: str | Path, extra_objs: Dict[str, Type[HyperNPModel]] | None = None) HyperNPModel

Auto-load a serialized model based on the saved class_name.

Parameters:
  • file_path – Path to model file.

  • extra_objs – Optional mapping from class name to class object used as a fallback when class is not yet registered.

Returns:

Instantiated model loaded from file_path.

Raises:

Exception – If the class cannot be resolved/imported.

clone() HyperNPModel

Returns a clone of the model.

copy() HyperNPModel

Returns a clone of the model.

fit_generator(x: Any, x_val: Any | None = None) None

Trains the model from a data generator function.

Parameters:
  • x – train data generation function.

  • x_val – validation data generation function.

Raises:

NotImplementedError – If not implemented by a subclass.

init_to_false() None

Sets the model as non initialized.

initialize() None

Initialize model parameters/state.

Subclasses can override this method when they have lazy initialization logic.

property is_init: bool

Returns True if the model has been initialized.

classmethod load(file_path: str | Path) HyperNPModel

Loads the model from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Model object.

classmethod load_config(file_path: str | Path) Dict[str, Any]

Loads the model configuration from file.

Parameters:

file_path – path to the file where the model is stored.

Returns:

Dictionary containing the model configuration.

static load_config_from_json(json_str: str) Dict[str, Any]

Convert JSON configuration string to dictionary.

classmethod load_params(f: File, config: Dict[str, Any]) HyperNPModel

Initializes the model from the configuration and loads the model parameters from file.

Parameters:
  • f – file handle.

  • config – configuration dictionary.

Returns:

Model object.

registry: ClassVar[Dict[str, Type['HyperNPModel']]] = {'AHC': <class 'hyperion.np.clustering.ahc.AHC'>, 'AdaptSNorm': <class 'hyperion.np.score_norm.adapt_s_norm.AdaptSNorm'>, 'BinaryLogisticRegression': <class 'hyperion.np.classifiers.binary_logistic_regression.BinaryLogisticRegression'>, 'CORAL': <class 'hyperion.np.transforms.coral.CORAL'>, 'CentWhiten': <class 'hyperion.np.transforms.cent_whiten.CentWhiten'>, 'CentWhitenUP': <class 'hyperion.np.transforms.cent_whiten_up.CentWhitenUP'>, 'ExpFamily': <class 'hyperion.np.pdfs.core.exp_family.ExpFamily'>, 'ExpFamilyMixture': <class 'hyperion.np.pdfs.mixtures.exp_family_mixture.ExpFamilyMixture'>, 'FRPLDA': <class 'hyperion.np.pdfs.plda.frplda.FRPLDA'>, 'GMM': <class 'hyperion.np.pdfs.mixtures.gmm.GMM'>, 'GMMDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_diag_cov.GMMDiagCov'>, 'GMMTiedDiagCov': <class 'hyperion.np.pdfs.mixtures.gmm_tied_diag_cov.GMMTiedDiagCov'>, 'GaussCalibration': <class 'hyperion.np.calibration.gauss_calibration.GaussCalibration'>, 'Gaussianizer': <class 'hyperion.np.transforms.gaussianizer.Gaussianizer'>, 'GreedyFusionBinaryLR': <class 'hyperion.np.classifiers.greedy_fusion.GreedyFusionBinaryLR'>, 'HMM': <class 'hyperion.np.pdfs.hmm.hmm.HMM'>, 'JFATotal': <class 'hyperion.np.pdfs.jfa.jfa_total.JFATotal'>, 'KMeans': <class 'hyperion.np.clustering.kmeans.KMeans'>, 'LDA': <class 'hyperion.np.transforms.lda.LDA'>, 'LNorm': <class 'hyperion.np.transforms.lnorm.LNorm'>, 'LNormUP': <class 'hyperion.np.transforms.lnorm_up.LNormUP'>, 'LinearGBE': <class 'hyperion.np.classifiers.linear_gbe.LinearGBE'>, 'LinearGBEUP': <class 'hyperion.np.classifiers.linear_gbe_up.LinearGBEUP'>, 'LinearSVMC': <class 'hyperion.np.classifiers.linear_svmc.LinearSVMC'>, 'LogisticRegression': <class 'hyperion.np.classifiers.logistic_regression.LogisticRegression'>, 'MVN': <class 'hyperion.np.transforms.mvn.MVN'>, 'NAP': <class 'hyperion.np.transforms.nap.NAP'>, 'NDA': <class 'hyperion.np.transforms.nda.NDA'>, 'NPModel': <class 'hyperion.np.hyper_np_model.NPModel'>, 'NSbSw': <class 'hyperion.np.transforms.sb_sw.NSbSw'>, 'Normal': <class 'hyperion.np.pdfs.core.normal.Normal'>, 'NormalDiagCov': <class 'hyperion.np.pdfs.core.normal_diag_cov.NormalDiagCov'>, 'PCA': <class 'hyperion.np.transforms.pca.PCA'>, 'PDF': <class 'hyperion.np.pdfs.core.pdf.PDF'>, 'PLDA': <class 'hyperion.np.pdfs.plda.plda.PLDA'>, 'PLDABase': <class 'hyperion.np.pdfs.plda.plda_base.PLDABase'>, 'QScoringHomoGBE': <class 'hyperion.np.classifiers.q_scoring_homo_gbe.QScoringHomoGBE'>, 'SNorm': <class 'hyperion.np.score_norm.s_norm.SNorm'>, 'SPLDA': <class 'hyperion.np.pdfs.plda.splda.SPLDA'>, 'SVMC': <class 'hyperion.np.classifiers.svmc.SVMC'>, 'SbSw': <class 'hyperion.np.transforms.sb_sw.SbSw'>, 'ScoreNorm': <class 'hyperion.np.score_norm.score_norm.ScoreNorm'>, 'SklTSNE': <class 'hyperion.np.transforms.skl_tsne.SklTSNE'>, 'SpectralClustering': <class 'hyperion.np.clustering.spectral_clustering.SpectralClustering'>, 'TNorm': <class 'hyperion.np.score_norm.t_norm.TNorm'>, 'TZNorm': <class 'hyperion.np.score_norm.tz_norm.TZNorm'>, 'TransformList': <class 'hyperion.np.transforms.transform_list.TransformList'>, 'ZNorm': <class 'hyperion.np.score_norm.z_norm.ZNorm'>, 'ZTNorm': <class 'hyperion.np.score_norm.zt_norm.ZTNorm'>}
save(file_path: str | Path) None

Saves the model to file.

Parameters:

file_path – filename path.

save_params(f: File) None

Saves model parameters into the file.

Parameters:

f – file handle.

to_json(**kwargs: Any) str

Return model configuration serialized as JSON.

Parameters:

**kwargs – Extra keyword arguments forwarded to json.dumps().

Returns:

JSON string with model configuration.

AHC accepts a square pairwise score or distance matrix; set metric to match the matrix semantics. Its threshold direction differs for LLR/probability scores and distances, so save the configured metric with the backend. SpectralClustering accepts an affinity-style square matrix and can either use a fixed cluster count or estimate it from eigengap statistics.

class hyperion.np.diarization.diar_ahc_plda.DiarAHCPLDA(plda_model: Any | None = None, preproc: Any | None = None, calibrator: Any | None = None, threshold: float = 0.0, max_clusters: int | None = None, pca_var_r: float = 1.0, do_unsup_cal: bool = False, use_bic: bool = False)[source]

Performs diarization with agglomerative hierarchical clustering (AHC).

Pipeline:
  1. Optional feature pre-processing (e.g., LDA + length norm).

  2. Optional PCA fit on current utterance and projection of features (and PLDA parameters when PLDA is used).

  3. Pairwise scoring with PLDA (or cosine scoring if PLDA is not provided).

  4. Optional score calibration (external calibrator and/or unsupervised GMM).

  5. AHC and optional post-merge of temporal intervals per speaker.

plda_model

Pre-trained PLDA-like model. If None, cosine scoring is used.

preproc

Optional callable transform applied to x before scoring.

calibrator

Optional external score calibrator applied element-wise to the score matrix.

threshold

Stopping threshold for AHC flat clustering.

max_clusters

Optional upper bound on number of output clusters.

pca_var_r

Variance ratio preserved by PCA in (0, 1]. If pca_var_r=1, PCA is skipped.

do_unsup_cal

If True, runs unsupervised 2-Gaussian score calibration.

use_bic

If True (and unsupervised calibration is enabled), uses BIC to detect one-Gaussian cases and return a single cluster.

Example

>>> import numpy as np
>>> from hyperion.np.diarization.diar_ahc_plda import DiarAHCPLDA
>>> x = np.random.randn(100, 256).astype(np.float32)
>>> t_start = np.arange(100, dtype=np.float32) * 0.01
>>> t_end = t_start + 0.01
>>> diar = DiarAHCPLDA(threshold=0.0, pca_var_r=1.0, do_unsup_cal=False)
>>> cluster_ids, t_start_out, t_end_out = diar(x, t_start=t_start, t_end=t_end)
__init__(plda_model: Any | None = None, preproc: Any | None = None, calibrator: Any | None = None, threshold: float = 0.0, max_clusters: int | None = None, pca_var_r: float = 1.0, do_unsup_cal: bool = False, use_bic: bool = False) None[source]

Initializes a diarization backend based on AHC over PLDA scores.

Parameters:
  • plda_model – Pre-trained PLDA-like model. If None, cosine scoring is used.

  • preproc – Optional preprocessing transform/callable applied to features.

  • calibrator – Optional external score calibrator.

  • threshold – AHC threshold used to cut the dendrogram.

  • max_clusters – Optional upper bound on number of output clusters.

  • pca_var_r – PCA kept-variance ratio in (0, 1]. 1 disables PCA.

  • do_unsup_cal – Enables unsupervised GMM score calibration.

  • use_bic – Uses BIC decision from unsupervised calibration to force a single-cluster output when supported by the data.

static _plot_score_hist(scores: ndarray, output_file: str | Path, thr: float | None = None, gmm: Any | None = None) None[source]

Plots score histogram and optional calibration model density.

Parameters:
  • scores – Pairwise score matrix (N, N).

  • output_file – Output plot path.

  • thr – Optional decision threshold to draw as vertical line.

  • gmm – Optional fitted GMM object for plotting model density.

Returns:

None.

static _unsup_gmm_calibration(scores: ndarray) Tuple[ndarray, float, Any][source]

Performs unsupervised score calibration using a 2-component GMM.

Parameters:

scores – Pairwise score matrix (N, N).

Returns:

Calibrated scores with same shape as input. bic: BIC-based evidence for 2-comp vs 1-comp model. gmm_2c: Trained 2-component GMM used for calibration.

Return type:

scores_cal

_merge_intervals(cluster_ids: ndarray, t_start: ndarray, t_end: ndarray) Tuple[ndarray, ndarray, ndarray][source]

Merges overlapping/adjacent intervals per speaker cluster.

Parameters:
  • cluster_ids – Cluster assignments (num_segments,).

  • t_start – Segment start times (num_segments,).

  • t_end – Segment end times (num_segments,).

Returns:

Reindexed cluster labels sorted by start time. new_t_start: Merged segment start times. new_t_end: Merged segment end times.

Return type:

new_cluster_ids

__call__(x: ndarray, t_start: ndarray | None = None, t_end: ndarray | None = None, hist_file: str | Path | None = None) Tuple[ndarray, ndarray | None, ndarray | None][source]

Performs diarization clustering.

Parameters:
  • x – Input feature matrix (num_segments, feat_dim).

  • t_start – Optional segment start times.

  • t_end – Optional segment end times.

  • hist_file – Optional path to save score histogram plot.

Returns:

Tuple containing cluster assignments and optional segment start/end times.

static filter_args(**kwargs: Any) Dict[str, Any][source]

Filters diarization args from arguments dictionary.

Parameters:

kwargs – Arguments dictionary.

Returns:

Dictionary with diarization options.

static add_class_args(parser: ArgumentParser, prefix: str | None = None) None[source]

Adds diarization options to parser.

Parameters:
  • parser – Arguments parser.

  • prefix – Options prefix.

Returns:

None.

static add_argparse_args(parser: ArgumentParser, prefix: str | None = None) None

Adds diarization options to parser.

Parameters:
  • parser – Arguments parser.

  • prefix – Options prefix.

Returns:

None.

DiarAHCPLDA combines optional preprocessing, PLDA or cosine scoring, optional calibration, and AHC. Its input rows are speech segments; optional start/end arrays must remain aligned with those rows. The returned cluster ids describe speakers for those segments, not global speaker identities.

Speech augmentation

class hyperion.np.augment.speech_augment.SpeechAugment(speed_aug: SpeedAugment | None = None, reverb_aug: ReverbAugment | None = None, noise_aug: NoiseAugment | None = None, codec_aug: CodecAugment | None = None, transcodec_aug: CodecAugment | None = None)[source]

Applies a configurable chain of speech augmentations.

speed_aug

Optional speed augmenter.

reverb_aug

Optional reverb augmenter.

noise_aug

Optional additive noise augmenter.

codec_aug

Optional codec augmenter.

transcodec_aug

Optional second codec augmenter applied after codec_aug.

__init__(speed_aug: SpeedAugment | None = None, reverb_aug: ReverbAugment | None = None, noise_aug: NoiseAugment | None = None, codec_aug: CodecAugment | None = None, transcodec_aug: CodecAugment | None = None) None[source]

Initializes a speech augmentation pipeline.

Parameters:
  • speed_aug – Optional speed augmenter.

  • reverb_aug – Optional reverb augmenter.

  • noise_aug – Optional additive noise augmenter.

  • codec_aug – Optional codec augmenter.

  • transcodec_aug – Optional second codec augmenter applied conditionally.

Returns:

None.

classmethod create(cfg: str | Dict[str, Any], random_seed: int = 112358, rng: Generator | None = None) SpeechAugment[source]

Creates a SpeechAugment object from options dictionary or YAML file.

Parameters:
  • cfg – YAML file path or dictionary with augmentation options.

  • random_seed – Seed passed to sub-augmenters when they create RNGs.

  • rng – Optional pre-created random generator.

Returns:

Configured speech augmenter instance.

property max_reverb_context: int

Returns the maximum reverb context required by the pipeline.

Parameters:

None.

Returns:

Maximum left context in samples required by reverb augmentation.

reseed(seed: int | SeedSequence) None[source]

Reseeds all stochastic sub-augmenters with independent child streams.

forward(x: ndarray, sample_freq: float | None = None, enable_tel_codecs: bool = True, enable_media_codecs: bool = True, enable_transcodec: bool = True) Tuple[ndarray, Dict[str, Any]][source]

Adds speed augment, noise and reverberation to signal, speed multiplier, noise type, SNR, room type and RIRs are chosen randomly.

Parameters:
  • x – Clean speech signal.

  • sample_freq – Sampling rate in Hz used by codec-based augmenters.

  • enable_tel_codecs – Enables telephony codecs in codec_aug.

  • enable_media_codecs – Enables media codecs in codec_aug.

  • enable_transcodec – Enables second-stage codec augmentation.

Returns:

Augmented signal. Dictionary containing augmentation metadata for each enabled stage.

__call__(x: ndarray, sample_freq: float | None = None, enable_tel_codecs: bool = True, enable_media_codecs: bool = True, enable_transcodec: bool = True) Tuple[ndarray, Dict[str, Any]][source]

Runs the augmentation pipeline using callable-style syntax.

Parameters:
  • x – Clean speech signal.

  • sample_freq – Sampling rate in Hz used by codec-based augmenters.

  • enable_tel_codecs – Enables telephony codecs in codec_aug.

  • enable_media_codecs – Enables media codecs in codec_aug.

  • enable_transcodec – Enables second-stage codec augmentation.

Returns:

Augmented signal. Dictionary containing augmentation metadata for each enabled stage.

SpeechAugment composes speed, reverberation, noise, and codec effects for a one-dimensional waveform. Give it an explicit random seed or generator for reproducible experiments, and record the returned augmentation metadata with the experiment configuration. The complete configuration schema and CSV manifest examples are in Speech Augmentation Tutorial.

See also