alexnet.py 2.22 KB
Newer Older
1
2
from typing import Any

3
import torch
4
import torch.nn as nn
5

6
from .._internally_replaced_utils import load_state_dict_from_url
7
8


9
__all__ = ["AlexNet", "alexnet"]
10
11
12


model_urls = {
13
    "alexnet": "https://download.pytorch.org/models/alexnet-owt-7be5be79.pth",
14
15
16
}


Soumith Chintala's avatar
Soumith Chintala committed
17
class AlexNet(nn.Module):
18
    def __init__(self, num_classes: int = 1000, dropout: float = 0.5) -> None:
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(64, 192, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(192, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )
35
        self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
36
        self.classifier = nn.Sequential(
37
            nn.Dropout(p=dropout),
38
39
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
40
            nn.Dropout(p=dropout),
41
42
43
44
45
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, num_classes),
        )

46
    def forward(self, x: torch.Tensor) -> torch.Tensor:
47
        x = self.features(x)
48
        x = self.avgpool(x)
49
        x = torch.flatten(x, 1)
50
51
52
53
        x = self.classifier(x)
        return x


54
def alexnet(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> AlexNet:
55
56
    r"""AlexNet model architecture from the
    `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
57
    The required minimum input size of the model is 63x63.
58
59
60

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
61
        progress (bool): If True, displays a progress bar of the download to stderr
62
    """
63
    model = AlexNet(**kwargs)
64
    if pretrained:
65
        state_dict = load_state_dict_from_url(model_urls["alexnet"], progress=progress)
66
        model.load_state_dict(state_dict)
67
    return model