Module earthvision.models.resisc45.vgg16
Expand source code
import torch
from torch import nn
from typing import Any
from torchvision.models import VGG
from torchvision.models.vgg import make_layers, cfgs
from .utils import load_state_dict_from_url
__all__ = ['VGG', 'vgg16']
model_urls = {
"vgg16": (
"https://drive.google.com/uc?id=1fxw_aFVAI7Z-XxmFjp-q0XapWyrBMYdA",
"resisc45_vgg16.pth",
)
}
class VGG16Resisc45(VGG):
def __init__(
self,
features: nn.Module,
num_classes: int = 45,
init_weights: bool = True
):
super().__init__(features, num_classes=num_classes, init_weights=init_weights)
def _vgg(arch: str, cfg: str, batch_norm: bool, pretrained: bool, progress: bool = True, **kwargs: Any) -> VGG16Resisc45:
if pretrained:
kwargs['init_weights'] = False
model = VGG16Resisc45(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)
if pretrained:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
state_dict = load_state_dict_from_url(model_urls[arch], map_location=device)
model.load_state_dict(state_dict, strict=False)
return model
def vgg16(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
r"""VGG 16-layer model (configuration "D")
`"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
The required minimum input size of the model is 32x32.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _vgg('vgg16', 'D', False, pretrained, progress, **kwargs)
Functions
def vgg16(pretrained: bool = False, progress: bool = True, **kwargs: Any) ‑> torchvision.models.vgg.VGG
-
VGG 16-layer model (configuration "D")
"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>
_. The required minimum input size of the model is 32x32.Args
pretrained
:bool
- If True, returns a model pre-trained on ImageNet
progress
:bool
- If True, displays a progress bar of the download to stderr
Expand source code
def vgg16(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG: r"""VGG 16-layer model (configuration "D") `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_. The required minimum input size of the model is 32x32. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _vgg('vgg16', 'D', False, pretrained, progress, **kwargs)
Classes
class VGG (features: torch.nn.modules.module.Module, num_classes: int = 1000, init_weights: bool = True)
-
Base class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing to nest them 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): super(Model, self).__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 have their parameters converted too when you call :meth:
to
, etc.:ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool
Initializes internal Module state, shared by both nn.Module and ScriptModule.
Expand source code
class VGG(nn.Module): def __init__( self, features: nn.Module, num_classes: int = 1000, init_weights: bool = True ) -> None: super(VGG, self).__init__() self.features = features self.avgpool = nn.AdaptiveAvgPool2d((7, 7)) self.classifier = nn.Sequential( nn.Linear(512 * 7 * 7, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, num_classes), ) if init_weights: self._initialize_weights() def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.features(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.classifier(x) return x def _initialize_weights(self) -> None: for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.normal_(m.weight, 0, 0.01) nn.init.constant_(m.bias, 0)
Ancestors
- torch.nn.modules.module.Module
Subclasses
- earthvision.models.resisc45.vgg16.VGG16Resisc45
Class variables
var dump_patches : bool
var training : bool
Methods
def forward(self, x: torch.Tensor) ‑> torch.Tensor
-
Defines 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 :class:
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.Expand source code
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.features(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.classifier(x) return x