minerva.models.nets.cpc_networks
Classes
Base class for all neural network modules.  | 
|
Base class for all neural network modules.  | 
|
Base class for all neural network modules.  | 
|
Base class for all neural network modules.  | 
|
Base class for all neural network modules.  | 
|
Base class for all neural network modules.  | 
|
Base class for all neural network modules.  | 
|
Base class for all neural network modules.  | 
|
Base class for all neural network modules.  | 
Module Contents
- class minerva.models.nets.cpc_networks.CNN[source]
 Bases:
lightning.LightningModuleBase class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
Submodules assigned in this way will be registered, and will also have their parameters converted when you call
to(), etc.Note
As per the example above, an
__init__()call to the parent class must be made before assignment on the child.- Variables:
 training (bool) – Boolean represents whether this module is in training or evaluation mode.
Convolutional Neural Network (CNN) encoder for CPC (Contrastive Predictive Coding) for Human Activity Recognition (HAR).
This class serves as a wrapper for the Convolutional1DEncoder class, providing an easy-to-use interface for the CPC model.
- encoder
 
- class minerva.models.nets.cpc_networks.ConvBlock(in_channels=6, out_channels=128, kernel_size=1, stride=1, padding=1, padding_mode='reflect', dropout_prob=0.2)[source]
 Bases:
lightning.LightningModuleBase class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
Submodules assigned in this way will be registered, and will also have their parameters converted when you call
to(), etc.Note
As per the example above, an
__init__()call to the parent class must be made before assignment on the child.- Variables:
 training (bool) – Boolean represents whether this module is in training or evaluation mode.
Convolutional Block for the 1D Convolutional Encoder.
This block consists of a convolutional layer followed by a ReLU activation and dropout.
Parameters
- in_channelsint, optional
 Number of input channels, by default 6.
- out_channelsint, optional
 Number of output channels, by default 128.
- kernel_sizeint, optional
 Size of the convolutional kernel, by default 1.
- strideint, optional
 Stride of the convolution, by default 1.
- paddingint, optional
 Padding for the convolution, by default 1.
- padding_modestr, optional
 Padding mode for the convolution, by default ‘reflect’.
- dropout_probfloat, optional
 Dropout probability, by default 0.2.
- conv
 
- dropout
 
- relu
 
- class minerva.models.nets.cpc_networks.Convolutional1DEncoder(input_size=6, kernel_size=3, stride=1, padding=1)[source]
 Bases:
lightning.LightningModuleBase class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
Submodules assigned in this way will be registered, and will also have their parameters converted when you call
to(), etc.Note
As per the example above, an
__init__()call to the parent class must be made before assignment on the child.- Variables:
 training (bool) – Boolean represents whether this module is in training or evaluation mode.
1D Convolutional Encoder for CPC.
This encoder consists of a sequence of convolutional blocks that process the input time series data.
Parameters
- input_sizeint, optional
 Number of input channels, by default 6.
- kernel_sizeint, optional
 Size of the convolutional kernel, by default 3.
- strideint, optional
 Stride of the convolution, by default 1.
- paddingint, optional
 Padding for the convolution, by default 1.
- encoder
 
- class minerva.models.nets.cpc_networks.Genc_Gar(g_enc, g_ar)[source]
 Bases:
torch.nn.ModuleBase class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
Submodules assigned in this way will be registered, and will also have their parameters converted when you call
to(), etc.Note
As per the example above, an
__init__()call to the parent class must be made before assignment on the child.- Variables:
 training (bool) – Boolean represents whether this module is in training or evaluation mode.
- Parameters:
 g_enc (torch.nn.Module)
g_ar (torch.nn.Module)
Combination of the GENC (encoder) and GAR (autoregressive) networks, forming the backbone of the CPC model for HAR.
Parameters
- g_enc: torch.nn.Module
 Encoder network to extract features from the input data.
- g_artorch.nn.Module
 Autoregressive network to model temporal dependencies in the feature space.
- g_ar
 
- g_enc
 
- class minerva.models.nets.cpc_networks.HARCPCAutoregressive(input_size=128, hidden_size=256, num_layers=2, bidirectional=False, batch_first=True, dropout=0.2)[source]
 Bases:
lightning.LightningModuleBase class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
Submodules assigned in this way will be registered, and will also have their parameters converted when you call
to(), etc.Note
As per the example above, an
__init__()call to the parent class must be made before assignment on the child.- Variables:
 training (bool) – Boolean represents whether this module is in training or evaluation mode.
Autoregressive model for CPC used in Human Activity Recognition (HAR).
This network models the temporal dependencies in the feature space.
Parameters
- input_sizeint, optional
 Number of input features, by default 128.
- hidden_sizeint, optional
 Number of hidden units, by default 256.
- num_layersint, optional
 Number of recurrent layers, by default 2.
- bidirectionalbool, optional
 If True, becomes a bidirectional GRU, by default False.
- batch_firstbool, optional
 If True, the input and output tensors are provided as (batch, seq, feature), by default True.
- dropoutfloat, optional
 Dropout probability, by default 0.2.
- rnn
 
- class minerva.models.nets.cpc_networks.HARPredictionHead(num_classes=9)[source]
 Bases:
lightning.LightningModuleBase class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
Submodules assigned in this way will be registered, and will also have their parameters converted when you call
to(), etc.Note
As per the example above, an
__init__()call to the parent class must be made before assignment on the child.- Variables:
 training (bool) – Boolean represents whether this module is in training or evaluation mode.
- Parameters:
 num_classes (int)
Prediction head for Human Activity Recognition (HAR).
This network takes the encoded and temporally modeled features and outputs the final activity classification.
Parameters
- num_classesint, optional
 Number of activity classes to predict, by default 9 (RW_waist).
- model
 
- class minerva.models.nets.cpc_networks.LinearClassifier(backbone, head, num_classes=6, learning_rate=0.001, flatten=True, freeze_backbone=False, loss_fn=None)[source]
 Bases:
lightning.LightningModuleBase class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
Submodules assigned in this way will be registered, and will also have their parameters converted when you call
to(), etc.Note
As per the example above, an
__init__()call to the parent class must be made before assignment on the child.- Variables:
 training (bool) – Boolean represents whether this module is in training or evaluation mode.
- Parameters:
 backbone (lightning.LightningModule)
head (lightning.LightningModule)
num_classes (int)
learning_rate (float)
flatten (bool)
freeze_backbone (bool)
loss_fn (torch.nn.modules.loss._Loss)
A linear classifier model built on top of a backbone and a head network, designed for tasks such as classification. This model leverages PyTorch Lightning for easier training and evaluation.
Parameters
- backboneL.LightningModule
 The backbone network used for feature extraction.
- headL.LightningModule
 The head network used for the final classification.
- num_classesint, optional
 The number of output classes, by default 6.
- learning_ratefloat, optional
 The learning rate for the optimizer, by default 0.001.
- flattenbool, optional
 Whether to flatten the output of the backbone before passing it to the head, by default True.
- freeze_backbonebool, optional
 Whether to freeze the backbone during training, by default False.
- loss_fntorch.nn.modules.loss._Loss, optional
 The loss function to use, by default CrossEntropyLoss.
- _freeze(model)[source]
 Freezes the model, i.e. sets the requires_grad parameter of all the parameters to False.
Parameters
- modeltype
 The model to freeze
- backbone
 
- calculate_metrics(y_pred, y_true, stage_name)[source]
 Calculate metrics for the given batch.
Parameters
- y_predtorch.Tensor
 Predicted labels.
- y_truetorch.Tensor
 True labels.
Returns
- dict
 Dictionary of metrics.
- Parameters:
 y_pred (torch.Tensor)
y_true (torch.Tensor)
stage_name (str)
- Return type:
 dict
- configure_optimizers()[source]
 Configures the optimizer. If update_backbone is True, it will update the parameters of the backbone and the head. Otherwise, it will only update the parameters of the head.
- flatten = True
 
- forward(x)[source]
 Same as
torch.nn.Module.forward().- Args:
 *args: Whatever you decide to pass into the forward method. **kwargs: Keyword arguments are also possible.
- Return:
 Your model’s output
- Parameters:
 x (torch.Tensor)
- freeze_backbone = False
 
- head
 
- learning_rate = 0.001
 
- loss_fn = None
 
- num_classes = 6
 
- test_step(batch, batch_idx)[source]
 Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.
- Args:
 batch: The output of your data iterable, normally a
DataLoader. batch_idx: The index of this batch. dataloader_idx: The index of the dataloader that produced this batch.(only if multiple dataloaders used)
- Return:
 Tensor- The loss tensordict- A dictionary. Can include any keys, but must include the key'loss'.None- Skip to the next batch.
# if you have one test dataloader: def test_step(self, batch, batch_idx): ... # if you have multiple test dataloaders: def test_step(self, batch, batch_idx, dataloader_idx=0): ...
Examples:
# CASE 1: A single test dataset def test_step(self, batch, batch_idx): x, y = batch # implement your own out = self(x) loss = self.loss(out, y) # log 6 example images # or generated text... or whatever sample_imgs = x[:6] grid = torchvision.utils.make_grid(sample_imgs) self.logger.experiment.add_image('example_images', grid, 0) # calculate acc labels_hat = torch.argmax(out, dim=1) test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs! self.log_dict({'test_loss': loss, 'test_acc': test_acc})
If you pass in multiple test dataloaders,
test_step()will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.# CASE 2: multiple test dataloaders def test_step(self, batch, batch_idx, dataloader_idx=0): # dataloader_idx tells you which dataset this is. ...
- Note:
 If you don’t need to test you don’t need to implement this method.
- Note:
 When the
test_step()is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.
- Parameters:
 batch (torch.Tensor)
batch_idx (int)
- training_step(batch, batch_idx)[source]
 Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.
- Args:
 batch: The output of your data iterable, normally a
DataLoader. batch_idx: The index of this batch. dataloader_idx: The index of the dataloader that produced this batch.(only if multiple dataloaders used)
- Return:
 Tensor- The loss tensordict- A dictionary which can include any keys, but must include the key'loss'in the case of automatic optimization.None- In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.
In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.
Example:
def training_step(self, batch, batch_idx): x, y, z = batch out = self.encoder(x) loss = self.loss(out, x) return loss
To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:
def __init__(self): super().__init__() self.automatic_optimization = False # Multiple optimizers (e.g.: GANs) def training_step(self, batch, batch_idx): opt1, opt2 = self.optimizers() # do training_step with encoder ... opt1.step() # do training_step with decoder ... opt2.step()
- Note:
 When
accumulate_grad_batches> 1, the loss returned here will be automatically normalized byaccumulate_grad_batchesinternally.
- Parameters:
 batch (torch.Tensor)
batch_idx (int)
- validation_step(batch, batch_idx)[source]
 Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.
- Args:
 batch: The output of your data iterable, normally a
DataLoader. batch_idx: The index of this batch. dataloader_idx: The index of the dataloader that produced this batch.(only if multiple dataloaders used)
- Return:
 Tensor- The loss tensordict- A dictionary. Can include any keys, but must include the key'loss'.None- Skip to the next batch.
# if you have one val dataloader: def validation_step(self, batch, batch_idx): ... # if you have multiple val dataloaders: def validation_step(self, batch, batch_idx, dataloader_idx=0): ...
Examples:
# CASE 1: A single validation dataset def validation_step(self, batch, batch_idx): x, y = batch # implement your own out = self(x) loss = self.loss(out, y) # log 6 example images # or generated text... or whatever sample_imgs = x[:6] grid = torchvision.utils.make_grid(sample_imgs) self.logger.experiment.add_image('example_images', grid, 0) # calculate acc labels_hat = torch.argmax(out, dim=1) val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs! self.log_dict({'val_loss': loss, 'val_acc': val_acc})
If you pass in multiple val dataloaders,
validation_step()will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.# CASE 2: multiple validation dataloaders def validation_step(self, batch, batch_idx, dataloader_idx=0): # dataloader_idx tells you which dataset this is. ...
- Note:
 If you don’t need to validate you don’t need to implement this method.
- Note:
 When the
validation_step()is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.
- Parameters:
 batch (torch.Tensor)
batch_idx (int)
- class minerva.models.nets.cpc_networks.PredictionNetwork(in_channels=256, out_channels=128)[source]
 Bases:
lightning.LightningModuleBase class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
Submodules assigned in this way will be registered, and will also have their parameters converted when you call
to(), etc.Note
As per the example above, an
__init__()call to the parent class must be made before assignment on the child.- Variables:
 training (bool) – Boolean represents whether this module is in training or evaluation mode.
Projection head for CPC used in Human Activity Recognition (HAR).
This network projects the encoded representations to a lower-dimensional space to facilitate the contrastive learning process.
Parameters
- in_channelsint, optional
 Number of input channels, by default 256.
- out_channelsint, optional
 Number of output channels, by default 128.
- Wk
 
- class minerva.models.nets.cpc_networks.ResNetEncoder(permute=True, *args, **kwargs)[source]
 Bases:
minerva.models.nets.time_series.resnet._ResNet1DBase class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
Submodules assigned in this way will be registered, and will also have their parameters converted when you call
to(), etc.Note
As per the example above, an
__init__()call to the parent class must be made before assignment on the child.- Variables:
 training (bool) – Boolean represents whether this module is in training or evaluation mode.
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- permute = True