Classification
sleepecg.evaluate(stages_true, stages_pred, stages_mode, show_undefined=False)
Evaluate the performance of a sleep stage classifier.
Prints overall accuracy, Cohen's kappa, confusion matrix, per-class precision, recall, and F1 score.
Parameters:
-
stages_true
(ndarray
) –The annotated (ground truth) sleep stages as a 2D array of shape
(n_records, n_samples)
containing integer class labels, or a 3D array of shape(n_records, n_samples, n_classes)
containing one-hot encoded class labels. -
stages_pred
(ndarray
) –The predicted sleep stages as a 2D array of shape
(n_records, n_samples)
containing integer class labels, or a 3D array of shape(n_records, n_samples, n_classes)
containing one-hot encoded class labels. -
stages_mode
(str
) –Identifier of the grouping mode. Can be any of
'wake-sleep'
,'wake-rem-nrem'
,'wake-rem-light-n3'
,'wake-rem-n1-n2-n3'
. -
show_undefined
(bool
) –If
True
, includeSleepStage.UNDEFINED
(i.e0
) in the confusion matrix output. This can be helpful during debugging. By defaultFalse
.
Returns:
Source code in sleepecg/classification.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
|
sleepecg.list_classifiers(classifiers_dir=None)
List available classifiers.
Parameters:
-
classifiers_dir
(str | Path
) –Directory in which to look for classifiers. If
None
(default), the value is taken from the configuration. If'SleepECG'
,site-packages/sleepecg/classifiers
is used.
See Also
load_classifier : Load classifiers.
Source code in sleepecg/classification.py
sleepecg.load_classifier(name, classifiers_dir=None, silence_tf_messages=True)
Load a SleepClassifier
from disk.
This functions reads .zip
files saved by save_classifier()
. Pass 'SleepECG'
as the
second argument to load a classifier bundled with SleepECG.
Parameters:
-
name
(str
) –The identifier of the classifier to load.
-
classifiers_dir
(str | Path
) –Directory in which to look for
<name>.zip
. IfNone
(default), the value is taken from the configuration. If'SleepECG'
, load classifiers fromsite-packages/sleepecg/classifiers
. -
silence_tf_messages
(bool
) –Whether or not to silence messages from TensorFlow when loading a model. By default
True
.
Returns:
-
SleepClassifier
–Contains the model and metadata required for feature extraction and preprocessing. Can be passed to
stage()
.
See Also
list_classifiers : Show information about available classifiers.
Source code in sleepecg/classification.py
sleepecg.prepare_data_keras(features, stages, stages_mode, mask_value=-1)
Mask and pad data and calculate sample weights for a Keras model.
The following steps are performed:
- Merge sleep stages in
stages
according tostage_mode
. - Set features corresponding to
SleepStage.UNDEFINED
tomask_value
. - Replace
np.nan
andnp.inf
infeatures
withmask_value
. - Pad to a common length, where
mask_value
is used forfeatures
andSleepStage.UNDEFINED
(i.e0
) is used for stages. - One-hot encode stages.
- Calculate sample weights with class weights taken as
n_samples / (n_classes * np.bincount(y))
.
Parameters:
-
features
(list[ndarray]
) –Each 2D array in this list is a feature matrix of shape
(n_samples, n_features)
corresponding to a single record as returned byextract_features()
. -
stages
(list[ndarray]
) –Each 1D array in this list contains the sleep stages of a single record as returned by
extract_features()
. -
stages_mode
(str
) –Identifier of the grouping mode. Can be any of
'wake-sleep'
,'wake-rem-nrem'
,'wake-rem-light-n3'
,'wake-rem-n1-n2-n3'
. -
mask_value
(int
) –Value used to pad features and replace
np.nan
andnp.inf
, by default-1
. Remember to pass the same value tolayers.Masking
in your model.
Returns:
-
features_padded
(ndarray
) –A 3D array of shape
(n_records, max_n_samples, n_features)
, wheren_records
is the length offeatures
/stages
andmax_n_samples
is the maximum number of rows of all feature matrices infeatures
. -
stages_padded_onehot
(ndarray
) –A 3D array of shape
(n_records, max_n_samples, n_classes+1)
, wheren_classes
is the number of classes remaining after merging sleep stages (excludingSleepStage.UNDEFINED
). -
sample_weight
(ndarray
) –A 2D array of shape
(n_records, max_n_samples)
.
Source code in sleepecg/classification.py
sleepecg.print_class_balance(stages, stages_mode=None)
Print the number of samples and percentages of each class in stages
.
Parameters:
-
stages
(ndarray
) –A 2D array of shape
(n_records, n_samples)
containing integer class labels or a 3D array of shape(n_records, n_samples, n_classes)
containing one-hot encoded class labels. -
stages_mode
(str
) –Identifier of the grouping mode. Can be any of
'wake-sleep'
,'wake-rem-nrem'
,'wake-rem-light-n3'
,'wake-rem-n1-n2-n3'
. IfNone
(default), no class labels are printed.
Source code in sleepecg/classification.py
sleepecg.save_classifier(name, model, stages_mode, feature_extraction_params, mask_value=None, classifiers_dir=None)
Save a trained classifier to disk.
The model
itself and a .yml
file containing classifier metadata are stored as
<name>.zip
in classifiers_dir
. Model serialization is performed as suggested by the
respective package documentation. Currently only Keras models are supported.
Parameters:
-
name
(str
) –An identifier which is used as the filename.
-
model
(Any
) –The classification model, should have
fit()
andpredict()
methods. -
stages_mode
(str
) –Identifier of the grouping mode. Can be any of
'wake-sleep'
,'wake-rem-nrem'
,'wake-rem-light-n3'
, or'wake-rem-n1-n2-n3'
. -
feature_extraction_params
(dict[str, Any]
) –The parameters passed to
extract_features()
, as a dictionary mapping string parameter names to values. Should not includerecords
andn_jobs
. -
mask_value
(int
) –Only required for Keras models, as passed to
prepare_data_keras()
andkeras.layers.Masking
, by defaultNone
. -
classifiers_dir
(str | Path
) –Directory in which the
.zip
file is stored. IfNone
(default), the value is taken from the configuration.
See Also
load_classifier : Load classifiers saved with this function.
Source code in sleepecg/classification.py
sleepecg.stage(clf, record, return_mode='int')
Predict sleep stages for a single record.
Feature extraction and preprocessing are performed according to the information stored
in clf
.
Parameters:
-
clf
(SleepClassifier
) –A classifier object as loaded with
load_classifier()
. -
record
(SleepRecord
) –A single record (i.e. night).
-
return_mode
(str
) –If
'int'
, return the predicted sleep stages as a 1D array of integers. If'prob'
, return a 2D array of probabilities. If'str'
, return a 1D array of strings.
Returns:
-
ndarray
–Array of sleep stages. Depending on
return_mode
, this takes different forms.
Warnings
Note that the returned labels depend on clf.stages_mode
, so they do not necessarily
follow the stage-to-integer mapping defined in SleepStage
. See
classification for details.
Source code in sleepecg/classification.py
sleepecg.SleepClassifier
dataclass
Store a sleep classifier model and metadata.
Attributes:
-
model
(_Model
) –The classification model, should have
fit
andpredict
methods. -
stages_mode
(str
) –Identifier of the grouping mode. Can be any of
'wake-sleep'
,'wake-rem-nrem'
,'wake-rem-light-n3'
, or'wake-rem-n1-n2-n3'
. -
feature_extraction_params
(dict[str, Any]
) –The parameters passed to
extract_features()
, as a dictionary mapping string parameter names to values. Does not includerecords
andn_jobs
. -
model_type
(str
) –A string identifying the model type, e.g.
'keras'
or'sklearn'
. This is used bystage()
to determine how to perform sleep stage predictions. -
mask_value
((int, optional)
) –Only required for models of type
'keras'
, as passed toprepare_data_keras()
andkeras.layers.Masking
, by defaultNone
. -
source_file
((Path, optional)
) –The file from which the classifier was loaded using
load_classifier()
, by defaultNone
.