mednet.models.detect.faster_rcnn¶
Faster R-CNN object detection (and classification) network architecture, from [RHGS17].
Classes
|
Faster R-CNN object detection (and classification) network architecture, from [RHGS17]. |
- class mednet.models.detect.faster_rcnn.FasterRCNN(optimizer_type=<class 'torch.optim.sgd.SGD'>, optimizer_arguments={'lr': 0.005, 'momentum': 0.9, 'weight_decay': 0.0005}, scheduler_type=<class 'torch.optim.lr_scheduler.StepLR'>, scheduler_arguments={'gamma': 0.1, 'step_size': 3}, model_transforms=None, augmentation_transforms=None, pretrained=False, num_classes=1, variant='mobilenetv3-small')[source]¶
Bases:
Model
Faster R-CNN object detection (and classification) network architecture, from [RHGS17].
- Parameters:
optimizer_type (
type
[Optimizer
]) – The type of optimizer to use for training.optimizer_arguments (
dict
[str
,Any
]) – Arguments to the optimizer afterparams
.scheduler_type (
type
[LRScheduler
] |None
) – The type of scheduler to use for training.scheduler_arguments (
dict
[str
,Any
]) – Arguments to the scheduler afterparams
.model_transforms (
Optional
[Sequence
[Callable
[[Tensor
],Tensor
]]]) – An optional sequence of torch modules containing transforms to be applied on the input before it is fed into the network.augmentation_transforms (
Optional
[Sequence
[Callable
[[Tensor
],Tensor
]]]) – An optional sequence of torch modules containing transforms to be applied on the input before it is fed into the network.pretrained (
bool
) – If set to True, loads pretrained model weights during initialization, else trains a new model.num_classes (
int
) – Number of outputs (classes) for this model. Do not account for the background (we compensate internally).variant (
Literal
['resnet50-v1'
,'resnet50-v2'
,'mobilenetv3-large'
,'mobilenetv3-small'
]) – One of the torchvision supported variants.
- property num_classes: int¶
Number of outputs (classes) for this model.
- Returns:
The number of outputs supported by this model.
- Return type:
- on_save_checkpoint(checkpoint)[source]¶
Perform actions during checkpoint saving (called by lightning).
Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save. Use on_load_checkpoint() to restore what additional data is saved here.
- Parameters:
checkpoint (
MutableMapping
[str
,Any
]) – The checkpoint to save.- Return type:
- on_load_checkpoint(checkpoint)[source]¶
Perform actions during model loading (called by lightning).
If you saved something with on_save_checkpoint() this is your chance to restore this.
- Parameters:
checkpoint (
MutableMapping
[str
,Any
]) – The loaded checkpoint.- Return type:
- forward(images, targets=None)[source]¶
Forward the input tensor through the network, producing a prediction.
- Parameters:
images (
list
[Tensor
]) – Input images, to be analyzed or trained on.targets (
list
[dict
[str
,Tensor
]] |None
) – Targets for the current input images. Targets should be passed only if training. It should be alist of dictionaries, each corresponding to one of the input images inimages
. Each dictionary should have two keys:boxes
, that contains the bounding boxes associated with the image, andlabels
, that contains the labels associated with each bounding box.
- Returns:
A list with various dictionaries, each referring to one of the
- 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.
- Parameters:
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)
- Returns:
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_batches
internally.
- validation_step(batch, batch_idx, dataloader_idx=0)[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.
- Parameters:
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)
- Returns:
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.
- predict_step(batch, batch_idx, dataloader_idx=0)[source]¶
Step function called during
predict()
. By default, it callsforward()
. Override to add any processing logic.The
predict_step()
is used to scale inference on multi-devices.To prevent an OOM error, it is possible to use
BasePredictionWriter
callback to write the predictions to disk or database after each batch or on epoch end.The
BasePredictionWriter
should be used while using a spawn based accelerator. This happens forTrainer(strategy="ddp_spawn")
or training on 8 TPU cores withTrainer(accelerator="tpu", devices=8)
as predictions won’t be returned.- Parameters:
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)
- Returns:
Predicted output (optional).
Example
class MyModel(LightningModule): def predict_step(self, batch, batch_idx, dataloader_idx=0): return self(batch) dm = ... model = MyModel() trainer = Trainer(accelerator="gpu", devices=2) predictions = trainer.predict(model, dm)