Creates a dataset from continuous data by loading continuous data and splitting it in segments according to set parameters.
window (float, optional) – Window size in seconds. Defaults to 2.
overlap (float, optional) – Overlap between windows (0-1). Defaults to 0.
offset (int, optional) – Offset in seconds. Defaults to 10.
sfreq (float, optional) – Sampling frequency. Defaults to 500.
n_subjects (int, optional) – Number of subjects. Defaults to None (all subjects).
scaling (str, optional) – The scaling method. available options are “zscore” and “minmax”. By default, minmax.
n_samples (int, optional) – Number of samples per subject. Defaults to None.
split_sizes(tuple or int), optional – A tuple of (train_size, valid_size, test_size) for splits or a float <= 1, in which case the valid sizes and test sizes are deduced to be as half or the remaining.
sensortype (str, optional) – Sensor type. Defaults to None.
lso (bool, optional) – Leave subjects out. Defaults to False.
random_state (int, optional) – Random state for reproducibility. Defaults to 0.
Window size in seconds.
int
Overlap between windows.
float
Offset in seconds.
int
Sampling frequency.
int
Number of subjects.
int
Number of samples per subject.
int
Data.
torch.Tensor
targets.
torch.Tensor
Groups.
list
Subject list.
list
Loads a subject’s data with windowing and overlap.
alias of EpochedDataset
Creates a dataset for epoch-based M/EEG data.
sfreq (int, optional) – The sampling frequency, by default 500.
n_subjects (int, optional) – The number of subjects. Default value is None, which means all subjects are processed.
scaling (str, optional) – The scaling method. available options are “zscore” and “minmax”. By default, minmax.
n_samples (int, optional) – The number of samples to include, by default None.
sensortype (str, optional) – The type of sensor to use, by default None.
lso (bool, optional) – Leave subjects out. If False, within-subject splitting is used, by default False.
random_state (int, optional) – The random state for reproducibility, by default 0.
The sampling frequency.
int
The number of subjects.
int
The number of samples for each subject.
int
The data.
torch.Tensor
The targets.
torch.Tensor
The groups.
list
The subject list.
list
The path to the data.
str
Wrapper for the load_from_path method.
*args (tuple) – Positional arguments to pass to load_from_path.
**kwargs (dict) – Keyword arguments to pass to load_from_path.
Loads data from the data_path.
data_path (str, optional) – Path to the data. Defaults to self.data_path if None.
csv_path (str, optional) – Path to the CSV file. Defaults to “participants_info.csv” in data_path.
one_sub (str, optional) – Subject ID or “random” to select a random subject.
verbose (int, optional) – Logging verbosity level (0-2).
target_col (str, optional) – Column name for targets in the CSV file.
Loads the subject list from a CSV file.
data_path (str) – Path to the folder containing the dataset.
csv_path (str, optional) – Path to the CSV file. Defaults to “participants_info.csv” in the data_path.
DataFrame containing participant information.
pd.DataFrame
Sets the data, targets, and groups for the dataset, with optional random subject selection.
data (torch.Tensor or np.ndarray) – The dataset containing all subjects’ data.
targets (torch.Tensor or np.ndarray) – The target labels corresponding to the data.
groups (torch.Tensor or np.ndarray) – The group labels indicating the subject for each sample.
target_labels (list, optional) – The unique target labels. If None, they will be inferred from the targets.
Splits data into training, validation, and test sets.
train_size (float) – Train set size (%).
valid_size (float) – Validation set size (%).
test_size (float, optional) – Test set size (%). Defaults to None.
Indices for the splits.
tuple
Returns a Torch dataset instance of the torch Dataset class for the given index.
Creates an infinite data loader.
dataset (torch.utils.data.Dataset) – The dataset to be loaded.
batch_size (int) – The size of the batches to be loaded.
num_workers (int, optional) – The number of workers to use for loading the data, by default 0.
pin_memory (bool, optional) – If True, the data loader will copy tensors into CUDA pinned memory before returning them. This can make data transfer faster, but requires more memory.
weights (torch.Tensor, optional) – A 1D tensor assigning a weight to each sample in the dataset. If not provided, all samples are assumed to have the same weight.
An infinite data loader.
alias of ContinuousDataset
Bases: CustomNet
Defines the forward pass through the network.
Args: x (torch.Tensor): Input tensor.
Returns: torch.Tensor: Output tensor.
Bases: Module
Base class for custom neural networks.
input_size (tuple) – Input shape of the network.
n_outputs (int) – Number of output neurons.
Input shape of the network.
tuple
Number of output neurons.
int
Defines the forward pass through the network.
Computes the output shape of a sequence of layers.
Defines the feature extraction part of the network (must be implemented).
Defines the classification part of the network (must be implemented).
Defines the forward pass through the network.
Args: x (torch.Tensor): Input tensor.
Returns: torch.Tensor: Output tensor.
Computes the output size of a sequence of layers.
Args: layers (nn.Sequential): Sequence of layers.
Returns: int: Output size of the sequence.
Bases: CustomNet
EEGNet architecture implementation.
input_size (tuple) – Input shape (S, C, T) where S is the number of sensors.
n_outputs (int) – Number of output classes.
filter_size (int, optional) – Filter size. Defaults to 64.
n_filters (int, optional) – Number of filters. Defaults to 16.
dropout (float, optional) – Dropout rate. Defaults to 0.5.
dropout_option (str, optional) – Dropout type (“SpatialDropout2D” or “Dropout”). Defaults to “Dropout”.
depthwise_multiplier (int, optional) – Depthwise multiplier. Defaults to 2.
Feature extraction layers.
nn.Sequential
Classification layers.
nn.Sequential
Bases: CustomNet
Bases: CustomNet
FullNet architecture implementation.
input_size (tuple) – Input shape (S, C, T) where S is the number of sensors.
n_outputs (int) – Number of output classes.
hlayers (int, optional) – Number of hidden layers. Defaults to 2.
filter_size (int, optional) – Filter size. Defaults to 7.
nchan (int, optional) – Number of channels. Defaults to 5.
n_linear (int, optional) – Number of neurons in the first linear layer. Defaults to 150.
dropout (float, optional) – Dropout rate. Defaults to 0.25.
batchnorm (bool, optional) – Whether to use batch normalization. Defaults to False.
maxpool (int, optional) – Max pooling size. Defaults to 0.
Bases: CustomNet
LF-CNN architecture implementation.
Spatial demixing followed by depthwise (per-component) temporal convolution and pooling. Each latent component has its own temporal filter, making the model more interpretable than VAR-CNN. For details see [1].
input_size (tuple) – Input shape (S, C, T) where S is the number of sensor types, C the number of channels and T the number of time samples.
n_outputs (int) – Number of output classes.
n_latent (int, optional) – Number of latent components after spatial demixing. Defaults to 32.
filter_length (int, optional) – Length of temporal convolution kernels. Defaults to 7.
pooling (int, optional) – Temporal pooling factor. Defaults to 2.
stride (int, optional) – Temporal pooling stride. Defaults to 2.
pool_type (str, optional) – Pooling type (‘max’ or ‘avg’). Defaults to ‘max’.
dropout (float, optional) – Dropout rate. Defaults to 0.5.
nonlin (nn.Module, optional) – Activation function class. Defaults to nn.ReLU.
References
signals. Neuroimage. (2019) May 4;197:425-434
Bases: CustomNet
MEEGNet architecture implementation.
input_size (tuple) – Input shape (S, C, T) where S is the number of sensors.
n_outputs (int) – Number of output classes.
n_linear (int, optional) – Number of neurons in the first linear layer. Defaults to 2000.
dropout (float, optional) – Dropout rate. Defaults to 0.5.
Bases: CustomNet
Multi-Layer Perceptron (MLP) implementation.
input_size (tuple) – Input shape.
n_outputs (int) – Number of output neurons.
hparams (dict) –
mlp_width (int): Number of neurons in each hidden layer.
mlp_depth (int): Number of hidden layers.
mlp_dropout (float): Dropout rate.
Bases: object
Load model from file.
Train the model on the provided dataset.
dataset – Dataset to train on.
batch_size (int, optional) – Batch size for training. Defaults to 128.
patience (int, optional) – Patience for early stopping. Defaults to 10.
max_epoch (int, optional) – Maximum number of epochs to train. Defaults to None.
model_path (str, optional) – Path to save the model. Defaults to None.
num_workers (int, optional) – Number of workers for data loading. Defaults to 4.
continue_training (bool, optional) – Wether to pick up training from last checkpoint. By default False. Use when training stopped abbruptly because of an error, or to re-train or fine-tune the model.
verbose (int, optional) – The verbosity level. By default 3. Values under 3 will display less detailed progress during training. Values under 2 will not display any update on performance epoch per epoch during training.
Notes
This method trains the model using the provided dataset and hyperparameters. It uses early stopping based on the validation loss and saves the model periodically.
Bases: object
Bases: CustomNet
VGG16 architecture implementation.
input_size (tuple) – Input shape (C, H, W) or (S, C, T) for M/EEG data. With S the number of sensors, C the number of channels and T the number of time samples
n_outputs (int) – Number of output classes.
Bases: CustomNet
VanPutNet architecture implementation.
input_size (tuple) – Input shape (C, H, W) or (S, C, T) for M/EEG data.
n_output (int) – Number of output classes.
dropout (float, optional) – Dropout rate. Defaults to 0.25.
Bases: CustomNet
VAR-CNN architecture implementation.
Spatial demixing followed by VAR temporal convolution and pooling. For details see [1].
input_size (tuple) – Input shape (S, C, T) where S is the number of sensor types, C the number of channels and T the number of time samples.
n_outputs (int) – Number of output classes.
n_latent (int, optional) – Number of latent components after spatial demixing. Defaults to 32.
filter_length (int, optional) – Length of temporal convolution kernels. Defaults to 7.
pooling (int, optional) – Temporal pooling factor. Defaults to 2.
stride (int, optional) – Temporal pooling stride. Defaults to 2.
pool_type (str, optional) – Pooling type (‘max’ or ‘avg’). Defaults to ‘max’.
dropout (float, optional) – Dropout rate. Defaults to 0.5.
nonlin (nn.Module, optional) – Activation function class. Defaults to nn.ReLU.
References
signals. Neuroimage. (2019) May 4;197:425-434
Creates a neural network based on the specified option.
net_option (str) – Network architecture option (“MLP”, “meegnet”, “custom”, “VGG”, “EEGNet”, “vanPutNet”).
input_size (int) – Input size of the network.
n_outputs (int) – Number of output neurons.
net_params (dict, optional) – Network parameters (required for “MLP” and “custom” options).
Created neural network.
nn.Module
AttributeError – If net_option is invalid.
Bases: Conv2d
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
Bases: Module
Spatial demixing Layer.
size (int) – Number of output features.
nonlin (callable) – Activation function.
axis (int) – Axis to apply demixing.
specs (dict) – Dictionary of layer specifications.
Applies demixing to input tensor.
Args: x (torch.Tensor): Input tensor.
Returns: torch.Tensor: Demixed tensor.
Bases: Module
Depthwise separable convolutional layer.
in_channels (int) – Number of input channels.
kernel_size (int or tuple) – Size of the convolutional kernel.
depthwise_multiplier (int, optional) – Multiplier for depthwise convolution. Defaults to 1.
Depthwise convolutional layer.
nn.Conv2d
Applies depthwise convolution to the input tensor.
Applies depthwise convolution to the input tensor.
Bases: Module
Flatten layer to connect feature extraction and classification parts of a network.
None
Flattens the input tensor.
Flattens the input tensor.
Bases: Module
Separable convolutional layer (depthwise + pointwise convolution).
in_channels (int) – Number of input channels.
out_channels (int) – Number of output channels.
kernel_size (int or tuple) – Size of the convolutional kernel.
Depthwise convolutional layer.
Pointwise convolutional layer.
nn.Conv2d
Applies separable convolution to the input tensor.
Applies separable convolution to the input tensor.
compute_psd.
data (np.array) – The data to compute psd on. Must be of shape n_channels x n_samples.
fs (int) – The sampling frequency.
option (str) – method option for the psd computation. Can be welch or multitaper.
Checks if a CUDA device is available and returns it.
A CUDA device if one is available, otherwise a CPU device.
torch.device
Time lapsed between t0 and t1.
Returns the time (from time.time()) between t0 and t1 in a more readable fashion.
t0 (float,) – time.time() initial measure of time (eg. at the begining of the script)
t1 (float,) – time.time() time at the end of the script or the execution of a function.
extract_bands.
data (np.array) – the data after it has been transformed to frequency space. Of shape n_samples x n_channels x n_bins or n_channels x n_bins
f (list) – the list of bins. id set to None, a list of all bins every .5 from 0 to n_bins will be generated.
data – the data after averaging for frequency bands of shape n_samples x n_channels x 7 or n_channels x 7 depending on input shape. bands are defined as follow:
delta: .5 to 4 Hz theta: 4 to 8 Hz alpha: 8 to 12 Hz beta1: 12 to 30 Hz beta2: 30 to 60 Hz gamma1: 60 to 90 Hz gamma2: 90 to 120 Hz
np.array
Returns time in a humanly readable format.
Performs stratified sampling for a single subject.
data (torch.Tensor) – The dataset containing all subjects’ data.
targets (torch.Tensor) – The target labels corresponding to the data.
n_samples (int) – The number of samples to draw. If None, all samples are used in a stratified manner.
groups (torch.Tensor, optional) – The group labels indicating the subject for each sample.
subject (int or str, optional) – The subject ID for which to perform stratified sampling.
sampled_indices – The indices of the stratified sampled data for the subject.
torch.Tensor
Converts an array of strings to integers based on unique labels.
array (array-like) – The input array of strings to be converted.
target_labels (list, optional) – A predefined list of unique labels. If None, unique labels will be inferred from the input array.
A tuple containing: - An array of integers corresponding to the input strings. - A list of unique labels used for the mapping.
tuple
ValueError – If the input array is empty or if target_labels contains duplicates.
Apply heatmap on image
org_img (PIL img) – Original image
activation_map (numpy arr) – Activation map (grayscale) 0-255
colormap_name (str) – Name of the colormap
Must be of size k x n_samples. k can be sensor dimension or trial dimension.
The size of the window in ms
Converts 3d image to grayscale
im_as_arr (numpy arr) – RGB image with shape (D,W,H)
Grayscale image with shape (1,W,D)
grayscale_im (numpy_arr)
This is a (kind of) bandaid fix to streamline saving procedure. It converts all the outputs to the same format which is 3xWxH with using sucecssive if clauses.
im_as_arr (Numpy array) – Matrix of shape 1xWxH or WxH or 3xWxH
Generates a figure visualizing saliency maps for MEG data.
This function creates a grid of images showing the saliency maps for types of stimuli (e.g., image and sound) and sensor channels (e.g., MAG, GRAD1, GRAD2). It also plots a topomap for the maximum saliency index along with a color bar.
saliencies (dict) – Dictionary containing saliency maps. Keys should correspond to different types of stimuli (e.g., “image”, “sound”), and values should be numpy arrays of shape 3 x sensors x samples, representing the saliency maps for each channel.
save_path (str, optional) – Path to save the generated figure. Default is an empty string, which means the figure will not be saved automatically.
suffix (str, optional) – Suffix to append to the filename when saving the figure. Default is an empty string.
title (str, optional) – Title for the figure. Default is an empty string.
sensors (list, optional) – List of sensor types to include in the visualization. Default is [“”].
sfreq (int, optional) – Sampling frequency for computation of xticks. Default is 500.
cmap (str, optional) – Colormap to use for displaying the topo- and saliency maps. Default is “coolwarm”.
stim_tick (int, optional) – Tick position for the stimulus event in the time axis. Default is None,
show (bool, optional) – Wether to show the figure or not. Useful for ipynb.
topomap (str, optional) – Must be “window”, “average” or “timing”. if “ average, the average saliency across time is used. If timing, then the saliency at to the highest saliency timing is used. if “window” is used, then the saliency window around the max saliency timing is used.
Notes
The function assumes that the input saliency maps are normalized to have zero mean and unit variance. The colormap used for displaying the saliency maps is “coolwarm” by default, but can be changed with the cmap parameter.
The function creates a grid layout with a subplot for each sensor channel and a subplot for the topomap. The grid layout is dynamically adjusted based on the number of sensors.
The function does not handle exceptions that may occur during the plotting process, such as issues with file I/O or invalid input data.
Gets used variables for almost all visualizations, like the image, model etc.
example_index (int) – Image id to use from examples
Original image read from the file prep_img (numpy_arr): Processed image target_class (int): Target class for the image file_name_to_export (string): File name to export the visualizations pretrained_model(Pytorch model): Model to use for the operations
original_image (numpy arr)
Generates positive and negative saliency maps based on the gradient
gradient (numpy arr) – Gradient of the operation to visualize
pos_saliency ( )
Processes image for CNNs
PIL_img (PIL_img) – PIL Image or numpy array to process
resize_im (bool) – Resize to 224 or not
Variable that contains processed float tensor
im_as_var (torch variable)
Recreates images from a torch variable, sort of reverse preprocessing
im_as_var (torch variable) – Image to recreate
Recreated image in array
recreated_im (numpy arr)
Saves cam activation map and activation map on the original image
org_img (PIL img) – Original image
activation_map (numpy arr) – Activation map (grayscale) 0-255
file_name (str) – File name of the exported image
Exports the original gradient image
gradient (np arr) – Numpy array of the gradient with shape (3, 224, 224)
file_name (str) – File name to be exported
Saves a numpy matrix or PIL image as an image
im_as_arr (Numpy array) – Matrix of shape DxWxH
path (str) – Path to the image