Skip to content

Commit caa2003

Browse files
authored
[PaddlePaddle Hackathon] add AlexNet (#36058)
* add alexnet
1 parent 90457d8 commit caa2003

File tree

5 files changed

+205
-3
lines changed

5 files changed

+205
-3
lines changed

python/paddle/tests/test_pretrained_model.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ def infer(self, arch):
5252
np.testing.assert_allclose(res['dygraph'], res['static'])
5353

5454
def test_models(self):
55-
arches = ['mobilenet_v1', 'mobilenet_v2', 'resnet18', 'vgg16']
55+
arches = [
56+
'mobilenet_v1', 'mobilenet_v2', 'resnet18', 'vgg16', 'alexnet'
57+
]
5658
for arch in arches:
5759
self.infer(arch)
5860

python/paddle/tests/test_vision_models.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14-
1514
import unittest
1615
import numpy as np
1716

@@ -71,6 +70,9 @@ def test_resnet101(self):
7170
def test_resnet152(self):
7271
self.models_infer('resnet152')
7372

73+
def test_alexnet(self):
74+
self.models_infer('alexnet')
75+
7476
def test_vgg16_num_classes(self):
7577
vgg16 = models.__dict__['vgg16'](pretrained=False, num_classes=10)
7678

python/paddle/vision/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@
4444
from .models import vgg16 # noqa: F401
4545
from .models import vgg19 # noqa: F401
4646
from .models import LeNet # noqa: F401
47+
from .models import AlexNet # noqa: F401
48+
from .models import alexnet # noqa: F401
4749
from .transforms import BaseTransform # noqa: F401
4850
from .transforms import Compose # noqa: F401
4951
from .transforms import Resize # noqa: F401

python/paddle/vision/models/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
from .vgg import vgg16 # noqa: F401
2929
from .vgg import vgg19 # noqa: F401
3030
from .lenet import LeNet # noqa: F401
31+
from .alexnet import AlexNet # noqa: F401
32+
from .alexnet import alexnet # noqa: F401
3133

3234
__all__ = [ #noqa
3335
'ResNet',
@@ -45,5 +47,7 @@
4547
'mobilenet_v1',
4648
'MobileNetV2',
4749
'mobilenet_v2',
48-
'LeNet'
50+
'LeNet',
51+
'AlexNet',
52+
'alexnet'
4953
]
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import absolute_import
16+
from __future__ import division
17+
from __future__ import print_function
18+
19+
import math
20+
import paddle
21+
import paddle.nn as nn
22+
import paddle.nn.functional as F
23+
24+
from paddle.nn import Linear, Dropout, ReLU
25+
from paddle.nn import Conv2D, MaxPool2D
26+
from paddle.nn.initializer import Uniform
27+
from paddle.fluid.param_attr import ParamAttr
28+
from paddle.utils.download import get_weights_path_from_url
29+
30+
model_urls = {
31+
"alexnet": (
32+
"https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/AlexNet_pretrained.pdparams",
33+
"7f0f9f737132e02732d75a1459d98a43", )
34+
}
35+
36+
__all__ = []
37+
38+
39+
class ConvPoolLayer(nn.Layer):
40+
def __init__(self,
41+
input_channels,
42+
output_channels,
43+
filter_size,
44+
stride,
45+
padding,
46+
stdv,
47+
groups=1,
48+
act=None):
49+
super(ConvPoolLayer, self).__init__()
50+
51+
self.relu = ReLU() if act == "relu" else None
52+
53+
self._conv = Conv2D(
54+
in_channels=input_channels,
55+
out_channels=output_channels,
56+
kernel_size=filter_size,
57+
stride=stride,
58+
padding=padding,
59+
groups=groups,
60+
weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
61+
bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)))
62+
self._pool = MaxPool2D(kernel_size=3, stride=2, padding=0)
63+
64+
def forward(self, inputs):
65+
x = self._conv(inputs)
66+
if self.relu is not None:
67+
x = self.relu(x)
68+
x = self._pool(x)
69+
return x
70+
71+
72+
class AlexNet(nn.Layer):
73+
"""AlexNet model from
74+
`"ImageNet Classification with Deep Convolutional Neural Networks"
75+
<https://proceedings.neurips.cc/paper/2012/file/c399862d3b9d6b76c8436e924a68c45b-Paper.pdf>`_
76+
77+
Args:
78+
num_classes (int): Output dim of last fc layer. Default: 1000.
79+
80+
Examples:
81+
.. code-block:: python
82+
83+
from paddle.vision.models import AlexNet
84+
85+
alexnet = AlexNet()
86+
87+
"""
88+
89+
def __init__(self, num_classes=1000):
90+
super(AlexNet, self).__init__()
91+
self.num_classes = num_classes
92+
stdv = 1.0 / math.sqrt(3 * 11 * 11)
93+
self._conv1 = ConvPoolLayer(3, 64, 11, 4, 2, stdv, act="relu")
94+
stdv = 1.0 / math.sqrt(64 * 5 * 5)
95+
self._conv2 = ConvPoolLayer(64, 192, 5, 1, 2, stdv, act="relu")
96+
stdv = 1.0 / math.sqrt(192 * 3 * 3)
97+
self._conv3 = Conv2D(
98+
192,
99+
384,
100+
3,
101+
stride=1,
102+
padding=1,
103+
weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
104+
bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)))
105+
stdv = 1.0 / math.sqrt(384 * 3 * 3)
106+
self._conv4 = Conv2D(
107+
384,
108+
256,
109+
3,
110+
stride=1,
111+
padding=1,
112+
weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
113+
bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)))
114+
stdv = 1.0 / math.sqrt(256 * 3 * 3)
115+
self._conv5 = ConvPoolLayer(256, 256, 3, 1, 1, stdv, act="relu")
116+
117+
if self.num_classes > 0:
118+
stdv = 1.0 / math.sqrt(256 * 6 * 6)
119+
self._drop1 = Dropout(p=0.5, mode="downscale_in_infer")
120+
self._fc6 = Linear(
121+
in_features=256 * 6 * 6,
122+
out_features=4096,
123+
weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
124+
bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)))
125+
126+
self._drop2 = Dropout(p=0.5, mode="downscale_in_infer")
127+
self._fc7 = Linear(
128+
in_features=4096,
129+
out_features=4096,
130+
weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
131+
bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)))
132+
self._fc8 = Linear(
133+
in_features=4096,
134+
out_features=num_classes,
135+
weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
136+
bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)))
137+
138+
def forward(self, inputs):
139+
x = self._conv1(inputs)
140+
x = self._conv2(x)
141+
x = self._conv3(x)
142+
x = F.relu(x)
143+
x = self._conv4(x)
144+
x = F.relu(x)
145+
x = self._conv5(x)
146+
147+
if self.num_classes > 0:
148+
x = paddle.flatten(x, start_axis=1, stop_axis=-1)
149+
x = self._drop1(x)
150+
x = self._fc6(x)
151+
x = F.relu(x)
152+
x = self._drop2(x)
153+
x = self._fc7(x)
154+
x = F.relu(x)
155+
x = self._fc8(x)
156+
157+
return x
158+
159+
160+
def _alexnet(arch, pretrained, **kwargs):
161+
model = AlexNet(**kwargs)
162+
163+
if pretrained:
164+
assert arch in model_urls, "{} model do not have a pretrained model now, you should set pretrained=False".format(
165+
arch)
166+
weight_path = get_weights_path_from_url(model_urls[arch][0],
167+
model_urls[arch][1])
168+
169+
param = paddle.load(weight_path)
170+
model.load_dict(param)
171+
172+
return model
173+
174+
175+
def alexnet(pretrained=False, **kwargs):
176+
"""AlexNet model
177+
178+
Args:
179+
pretrained (bool): If True, returns a model pre-trained on ImageNet. Default: False.
180+
181+
Examples:
182+
.. code-block:: python
183+
184+
from paddle.vision.models import alexnet
185+
186+
# build model
187+
model = alexnet()
188+
189+
# build model and load imagenet pretrained weight
190+
# model = alexnet(pretrained=True)
191+
"""
192+
return _alexnet('alexnet', pretrained, **kwargs)

0 commit comments

Comments
 (0)