Module laplace.utils.feature_extractor
Classes
class FeatureExtractor (model: torch.nn.modules.module.Module, last_layer_name: Optional[str] = None, enable_backprop: bool = False)
-
Feature extractor for a PyTorch neural network. A wrapper which can return the output of the penultimate layer in addition to the output of the last layer for each forward pass. If the name of the last layer is not known, it can determine it automatically. It assumes that the last layer is linear and that for every forward pass the last layer is the same. If the name of the last layer is known, it can be passed as a parameter at initilization; this is the safest way to use this class. Based on https://gist.github.com/fkodom/27ed045c9051a39102e8bcf4ce31df76.
Parameters
model
:torch.nn.Module
- PyTorch model
last_layer_name
:str
, default=None
- if the name of the last layer is already known, otherwise it will be determined automatically.
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Ancestors
- torch.nn.modules.module.Module
Methods
def forward(self, x: torch.Tensor) ‑> torch.Tensor
-
Forward pass. If the last layer is not known yet, it will be determined when this function is called for the first time.
Parameters
x
:torch.Tensor
- one batch of data to use as input for the forward pass
def forward_with_features(self, x: torch.Tensor) ‑> Tuple[torch.Tensor, torch.Tensor]
-
Forward pass which returns the output of the penultimate layer along with the output of the last layer. If the last layer is not known yet, it will be determined when this function is called for the first time.
Parameters
x
:torch.Tensor
- one batch of data to use as input for the forward pass
def set_last_layer(self, last_layer_name: str) ‑> None
-
Set the last layer of the model by its name. This sets the forward hook to get the output of the penultimate layer.
Parameters
last_layer_name
:str
- the name of the last layer (fixed in
model.named_modules()
).
def find_last_layer(self, x: torch.Tensor) ‑> torch.Tensor
-
Automatically determines the last layer of the model with one forward pass. It assumes that the last layer is the same for every forward pass and that it is an instance of
torch.nn.Linear
. Might not work with every architecture, but is tested with all PyTorch torchvision classification models (besides SqueezeNet, which has no linear last layer).Parameters
x
:torch.Tensor
- one batch of data to use as input for the forward pass