NumPy Backend API
hyperion.np provides the statistical backend used after embedding
extraction: preprocessing transforms, PLDA, calibration, score normalization,
and array-level metrics. These components operate on NumPy arrays and serialize
their state independently of PyTorch checkpoints.
Model serialization
- class hyperion.np.HyperNPModel(name: str | None = None, **kwargs: Any)[source]
Base class for machine learning models based on numpy.
- name
optional identifier for the model.
- registry: ClassVar[Dict[str, Type[HyperNPModel]]] = {'CORAL': <class 'hyperion.np.transforms.coral.CORAL'>, 'CentWhiten': <class 'hyperion.np.transforms.cent_whiten.CentWhiten'>, 'CentWhitenUP': <class 'hyperion.np.transforms.cent_whiten_up.CentWhitenUP'>, 'Gaussianizer': <class 'hyperion.np.transforms.gaussianizer.Gaussianizer'>, 'LDA': <class 'hyperion.np.transforms.lda.LDA'>, 'LNorm': <class 'hyperion.np.transforms.lnorm.LNorm'>, 'LNormUP': <class 'hyperion.np.transforms.lnorm_up.LNormUP'>, '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'>, 'PCA': <class 'hyperion.np.transforms.pca.PCA'>, 'SbSw': <class 'hyperion.np.transforms.sb_sw.SbSw'>, 'SklTSNE': <class 'hyperion.np.transforms.skl_tsne.SklTSNE'>, 'TransformList': <class 'hyperion.np.transforms.transform_list.TransformList'>}
- __init__(name: str | None = None, **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.
- copy() HyperNPModel[source]
Returns a clone of the model.
- clone() HyperNPModel[source]
Returns a clone of the model.
- property is_init: bool
Returns True if the model has been initialized.
- init_to_false() None[source]
Sets the model as non initialized.
- initialize() None[source]
Initialize model parameters/state.
Subclasses can override this method when they have lazy initialization logic.
- fit(x: ndarray, sample_weight: ndarray | None = None, x_val: ndarray | None = None, sample_weight_val: ndarray | None = None) None[source]
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[source]
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.
- save(file_path: str | Path) None[source]
Saves the model to file.
- Parameters:
file_path – filename path.
- save_params(f: File) None[source]
Saves model parameters into the file.
- Parameters:
f – file handle.
- _save_params_from_dict(f: File, params: Mapping[str, Any], dtypes: type | Mapping[str, Any] | None = None) None[source]
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.
- classmethod load_config(file_path: str | Path) Dict[str, Any][source]
Loads the model configuration from file.
- Parameters:
file_path – path to the file where the model is stored.
- Returns:
Dictionary containing the model configuration.
- classmethod load(file_path: str | Path) HyperNPModel[source]
Loads the model from file.
- Parameters:
file_path – path to the file where the model is stored.
- Returns:
Model object.
- classmethod load_params(f: File, config: Dict[str, Any]) HyperNPModel[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 _load_params_to_dict(f: File, name: str | None, params: Sequence[str], dtypes: type | Mapping[str, Any] | None = None) Dict[str, ndarray | None][source]
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.
- get_config() Dict[str, Any][source]
Returns the model configuration dict.
- to_json(**kwargs: Any) str[source]
Return model configuration serialized as JSON.
- Parameters:
**kwargs – Extra keyword arguments forwarded to
json.dumps().- Returns:
JSON string with model configuration.
- static load_config_from_json(json_str: str) Dict[str, Any][source]
Convert JSON configuration string to dictionary.
- static _bootstrap_registry() None[source]
Import common NP subpackages so subclasses register themselves.
- static _find_module_for_class_name(class_name: str) str | None[source]
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 auto_load(file_path: str | Path, extra_objs: Dict[str, Type[HyperNPModel]] | None = None) HyperNPModel[source]
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.
HyperNPModel subclasses register by class name and persist configuration
plus parameters in HDF5-style files. Use auto_load() when callers should
restore the recorded concrete model class. See
Save and Load Models and Backends for deployment guidance.
Transforms and preprocessing
- class hyperion.np.transforms.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
TransformListinstance.
- 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']]] = {'CORAL': <class 'hyperion.np.transforms.coral.CORAL'>, 'CentWhiten': <class 'hyperion.np.transforms.cent_whiten.CentWhiten'>, 'CentWhitenUP': <class 'hyperion.np.transforms.cent_whiten_up.CentWhitenUP'>, 'Gaussianizer': <class 'hyperion.np.transforms.gaussianizer.Gaussianizer'>, 'LDA': <class 'hyperion.np.transforms.lda.LDA'>, 'LNorm': <class 'hyperion.np.transforms.lnorm.LNorm'>, 'LNormUP': <class 'hyperion.np.transforms.lnorm_up.LNormUP'>, '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'>, 'PCA': <class 'hyperion.np.transforms.pca.PCA'>, 'SbSw': <class 'hyperion.np.transforms.sb_sw.SbSw'>, 'SklTSNE': <class 'hyperion.np.transforms.skl_tsne.SklTSNE'>, 'TransformList': <class 'hyperion.np.transforms.transform_list.TransformList'>}
- 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.
Use TransformList to preserve the ordered preprocessing chain used for a
backend. Fit transforms on development data only, then load and apply the same
chain to enrollment, test, and cohort embeddings. The principal transforms are
centering/whitening, length normalization, PCA, LDA, and CORAL.
Transforms Tutorial (NumPy) provides worked transform examples.
Extract, Score, and Evaluate X-Vectors shows transform use with PLDA.
PLDA and scoring backends
- 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
Wis full covariance for FRPLDA/SPLDA.update_mu – Whether
muis updated during EM.update_V – Whether
Vis updated (if applicable).update_U – Whether
Uis updated (PLDA only).update_B – Whether
Bis updated (FRPLDA).update_W – Whether
Wis updated.update_D – Whether
Dis 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.
PLDA backends consume matrices shaped (num_embeddings, embedding_dim) and
speaker/class ids aligned with rows during training. Scoring returns a matrix
whose rows correspond to enrollment models and columns to test segments.
PLDA Tutorial (NumPy) covers SPLDA, FRPLDA, full PLDA, and N-vs-M scoring.
Use
hyperion-train-pldaandhyperion-eval-plda-backendfor the file/table workflow.
Calibration and score normalization
Calibration turns raw scores into application-specific calibrated scores using development keys. Score normalization uses background cohorts. Both must be fit without evaluation labels to avoid contaminating metrics.
- class hyperion.np.classifiers.binary_logistic_regression.BinaryLogisticRegression(A: ndarray | None = None, b: ndarray | None = None, penalty: str = 'l2', lambda_reg: float = 1e-05, use_bias: bool = True, bias_scaling: float = 1, prior: float = 0.5, random_state: Any = None, solver: str = 'lbfgs', max_iter: int = 100, dual: bool = False, tol: float = 0.0001, verbose: int = 0, warm_start: bool = True, lr_seed: int = 1024, **kwargs: Any)[source]
Binary logistic regression.
This is a wrapper that add functionalities to sklearn logistic regression. Contrary to sklearn, this class produces well-calibrated likelihood ratios. Thus, this is suitable for score calibration.
- Loss function:
For training samples
(x_n, t_n)with binary labelt_n in {0, 1}, the optimized objective is:L(a, b) = sum_n w_n * CE(t_n, p_n) + lambda_reg * R(a)where:
CE(t_n, p_n) = -t_n * log(p_n) - (1 - t_n) * log(1 - p_n)w_n = s_n * (pi_{t_n} / N_{t_n})y_n = a^T x_n + bz_n = y_n + log(pi_1 / pi_0)p_n = 1 / (1 + exp(-z_n))where
s_nis optionalsample_weight(or1if not provided),pi_1 = prior,pi_0 = 1 - prior, andN_kis the number of training samples in classk.R(a)is either||a||_2^2(forpenalty='l2') or||a||_1(forpenalty='l1'), depending on the selected solver/penalty.
- \* ``A``
Scale coefficients with shape
(num_features, 1).
- \* ``b``
Bias vector with shape
(1,).
- \* ``penalty``
"l1"or"l2"regularization. Thenewton-cg,sag, andlbfgssolvers support only L2;liblinearandsagaalso support L1.
- \* ``lambda_reg``
Positive regularization strength.
- \* ``use_bias``
Whether to add an intercept to the decision function.
- \* ``bias_scaling``
Synthetic-feature scale used by
liblinearwhenuse_biasis enabled. Increasing it reduces regularization on the intercept weight.
- \* ``prior``
Prior probability of the positive class.
- \* ``random_state``
Optional random generator used by
sagandliblinear.
- \* ``solver``
Optimization solver.
liblinearis generally suitable for small data sets, whilesagandsagasuit larger data sets whose features have comparable scales.
- \* ``max_iter``, ``dual``, ``tol``, ``verbose``, ``warm_start``
Solver convergence and reuse controls passed to the underlying estimator.
- \* ``lr_seed``
Random seed used by Hyperion’s optimizer wrapper.
Example
>>> import numpy as np >>> from hyperion.np.classifiers.binary_logistic_regression import ( ... BinaryLogisticRegression, ... ) >>> x = np.array([[0.1, 1.2], [1.0, -0.2], [0.3, 0.4], [1.2, 0.1]]) >>> y = np.array([0, 1, 0, 1], dtype=np.int64) >>> blr = BinaryLogisticRegression(prior=0.5, solver="lbfgs") >>> blr.fit(x, y) >>> llr = blr.predict(x, eval_type="logit") >>> post = blr.predict(x, eval_type="post")
- __init__(A: ndarray | None = None, b: ndarray | None = None, penalty: str = 'l2', lambda_reg: float = 1e-05, use_bias: bool = True, bias_scaling: float = 1, prior: float = 0.5, random_state: Any = None, solver: str = 'lbfgs', max_iter: int = 100, dual: bool = False, tol: float = 0.0001, verbose: int = 0, warm_start: bool = True, lr_seed: int = 1024, **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.
- property prior: float
Prior probability for a positive sample.
- get_config() Dict[str, Any][source]
Gets configuration hyperparams. :returns: Dictionary with config hyperparams.
- predict(x: ndarray, eval_type: str = 'logit') ndarray[source]
Evaluates the logistic regression.
It provides well calibrated likelihood ratios or posteriors.
- Parameters:
x – input features (num_samples, feat_dim), it can be (num_samples,) if feat_dim=1.
eval_type – evaluation method: logit (log-likelihood ratio), log-post (log-posteriors), post (posteriors)
- Returns:
Output scores (num_samples,)
- __call__(x: ndarray, eval_type: str = 'logit') ndarray[source]
Evaluates the logistic regression.
- Parameters:
x – input features (num_samples, feat_dim), it can be (num_samples,) if feat_dim=1.
eval_type – evaluation method: logit (log-likelihood ratio), log-post (log-posteriors), post (posteriors)
- Returns:
Output scores (num_samples,)
- static filter_class_args(**kwargs: Any) Dict[str, Any][source]
Extracts the hyperparams of the class from a dictionary.
- Returns:
Hyperparameter dictionary to initialize the class.
- static add_class_args(parser: ArgumentParser, prefix: str | None = None) None[source]
It adds the arguments corresponding to the class to jsonargparse. :param parser: jsonargparse object :param prefix: argument prefix.
- static add_argparse_args(parser: ArgumentParser, prefix: str | None = None) None
It adds the arguments corresponding to the class to jsonargparse. :param parser: jsonargparse object :param prefix: argument prefix.
- property A: ndarray
- 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 add_argparse_eval_args(parser: ArgumentParser, prefix: str | None = None) None
It adds the arguments needed to evaluate the class to jsonargparse. :param parser: jsonargparse object :param prefix: argument prefix.
- static add_argparse_train_args(parser: ArgumentParser, prefix: str | None = None) None
It adds the arguments corresponding to the class to jsonargparse. :param parser: jsonargparse object :param prefix: argument prefix.
- static add_eval_args(parser: ArgumentParser, prefix: str | None = None) None
It adds the arguments needed to evaluate the class to jsonargparse. :param parser: jsonargparse object :param prefix: argument prefix.
- 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.
- property b: ndarray
- clone() HyperNPModel
Returns a clone of the model.
- copy() HyperNPModel
Returns a clone of the model.
- static filter_eval_args(**kwargs: Any) Dict[str, Any]
Extracts the evaluation time hyperparams of the class from a dictionary.
- Returns:
Hyperparameters to evaluate the class.
- static filter_train_args(**kwargs: Any) Dict[str, Any]
Extracts the hyperparams of the class from a dictionary.
- Returns:
Hyperparameter dictionary to initialize the class.
- fit(x: ndarray, class_ids: ndarray, sample_weight: ndarray | None = None) None
Estimates the parameters of the model.
- Parameters:
x – input features (num_samples, feat_dim), it can be (num_samples,) if feat_dim=1.
class_ids – class integer [0, num_classes-1] identifier (num_samples,)
sample_weight – weight of each sample in the estimation (num_samples,)
- 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: Any, config: Dict[str, Any]) LogisticRegression
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'>, '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'>, 'SPLDA': <class 'hyperion.np.pdfs.plda.splda.SPLDA'>, 'SVMC': <class 'hyperion.np.classifiers.svmc.SVMC'>, 'SbSw': <class 'hyperion.np.transforms.sb_sw.SbSw'>, 'SklTSNE': <class 'hyperion.np.transforms.skl_tsne.SklTSNE'>, 'SpectralClustering': <class 'hyperion.np.clustering.spectral_clustering.SpectralClustering'>, 'TransformList': <class 'hyperion.np.transforms.transform_list.TransformList'>}
- save(file_path: str | Path) None
Saves the model to file.
- Parameters:
file_path – filename path.
- save_params(f: Any) 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
nbestsamples.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'>, '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.
See Extract, Score, and Evaluate X-Vectors for calibration and adaptive S-Norm placement in a verification pipeline.
Other stable areas
The NumPy stack also includes speech augmentation, features, classifiers, clustering, diarization, and metric utilities. Their public use should be guided by the corresponding task documentation rather than by importing every implementation module directly.
The contract-level reference for calibration, cohort score normalization, clustering, diarization, and augmentation is NumPy Backend Extension Points.