Skip to content

Commit f543b74

Browse files
authored
Merge pull request #215 from chrisyeh96/linting
Cosmetic improvements to code
2 parents 2eb7a7d + 85e0a35 commit f543b74

File tree

4 files changed

+62
-76
lines changed

4 files changed

+62
-76
lines changed

README.md

Lines changed: 34 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# EfficientNet PyTorch
22

3-
### Quickstart
3+
### Quickstart
44

55
Install with `pip install efficientnet_pytorch` and load a pretrained EfficientNet with:
66
```python
@@ -12,46 +12,45 @@ model = EfficientNet.from_pretrained('efficientnet-b0')
1212

1313
#### Update (May 14, 2020)
1414

15-
This update adds comprehensive comments and documentation (thanks to @workingcoder).
15+
This update adds comprehensive comments and documentation (thanks to @workingcoder).
1616

1717
#### Update (January 23, 2020)
1818

1919
This update adds a new category of pre-trained model based on adversarial training, called _advprop_. It is important to note that the preprocessing required for the advprop pretrained models is slightly different from normal ImageNet preprocessing. As a result, by default, advprop models are not used. To load a model with advprop, use:
20-
```
20+
```python
2121
model = EfficientNet.from_pretrained("efficientnet-b0", advprop=True)
2222
```
2323
There is also a new, large `efficientnet-b8` pretrained model that is only available in advprop form. When using these models, replace ImageNet preprocessing code as follows:
24-
```
24+
```python
2525
if advprop: # for models using advprop pretrained weights
2626
normalize = transforms.Lambda(lambda img: img * 2.0 - 1.0)
2727
else:
28-
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
28+
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
2929
std=[0.229, 0.224, 0.225])
30-
3130
```
32-
This update also addresses multiple other issues ([#115](https://github.com/lukemelas/EfficientNet-PyTorch/issues/115), [#128](https://github.com/lukemelas/EfficientNet-PyTorch/issues/128)).
31+
This update also addresses multiple other issues ([#115](https://github.com/lukemelas/EfficientNet-PyTorch/issues/115), [#128](https://github.com/lukemelas/EfficientNet-PyTorch/issues/128)).
3332

3433
#### Update (October 15, 2019)
3534

3635
This update allows you to choose whether to use a memory-efficient Swish activation. The memory-efficient version is chosen by default, but it cannot be used when exporting using PyTorch JIT. For this purpose, we have also included a standard (export-friendly) swish activation function. To switch to the export-friendly version, simply call `model.set_swish(memory_efficient=False)` after loading your desired model. This update addresses issues [#88](https://github.com/lukemelas/EfficientNet-PyTorch/pull/88) and [#89](https://github.com/lukemelas/EfficientNet-PyTorch/pull/89).
3736

3837
#### Update (October 12, 2019)
3938

40-
This update makes the Swish activation function more memory-efficient. It also addresses pull requests [#72](https://github.com/lukemelas/EfficientNet-PyTorch/pull/72), [#73](https://github.com/lukemelas/EfficientNet-PyTorch/pull/73), [#85](https://github.com/lukemelas/EfficientNet-PyTorch/pull/85), and [#86](https://github.com/lukemelas/EfficientNet-PyTorch/pull/86). Thanks to the authors of all the pull requests!
39+
This update makes the Swish activation function more memory-efficient. It also addresses pull requests [#72](https://github.com/lukemelas/EfficientNet-PyTorch/pull/72), [#73](https://github.com/lukemelas/EfficientNet-PyTorch/pull/73), [#85](https://github.com/lukemelas/EfficientNet-PyTorch/pull/85), and [#86](https://github.com/lukemelas/EfficientNet-PyTorch/pull/86). Thanks to the authors of all the pull requests!
4140

4241
#### Update (July 31, 2019)
4342

4443
_Upgrade the pip package with_ `pip install --upgrade efficientnet-pytorch`
4544

46-
The B6 and B7 models are now available. Additionally, _all_ pretrained models have been updated to use AutoAugment preprocessing, which translates to better performance across the board. Usage is the same as before:
45+
The B6 and B7 models are now available. Additionally, _all_ pretrained models have been updated to use AutoAugment preprocessing, which translates to better performance across the board. Usage is the same as before:
4746
```python
4847
from efficientnet_pytorch import EfficientNet
49-
model = EfficientNet.from_pretrained('efficientnet-b7')
48+
model = EfficientNet.from_pretrained('efficientnet-b7')
5049
```
5150

5251
#### Update (June 29, 2019)
5352

54-
This update adds easy model exporting ([#20](https://github.com/lukemelas/EfficientNet-PyTorch/issues/20)) and feature extraction ([#38](https://github.com/lukemelas/EfficientNet-PyTorch/issues/38)).
53+
This update adds easy model exporting ([#20](https://github.com/lukemelas/EfficientNet-PyTorch/issues/20)) and feature extraction ([#38](https://github.com/lukemelas/EfficientNet-PyTorch/issues/38)).
5554

5655
* [Example: Export to ONNX](#example-export)
5756
* [Example: Extract features](#example-feature-extraction)
@@ -60,29 +59,29 @@ This update adds easy model exporting ([#20](https://github.com/lukemelas/Effici
6059
It is also now incredibly simple to load a pretrained model with a new number of classes for transfer learning:
6160
```python
6261
model = EfficientNet.from_pretrained('efficientnet-b1', num_classes=23)
63-
```
62+
```
6463

6564

6665
#### Update (June 23, 2019)
6766

68-
The B4 and B5 models are now available. Their usage is identical to the other models:
67+
The B4 and B5 models are now available. Their usage is identical to the other models:
6968
```python
7069
from efficientnet_pytorch import EfficientNet
71-
model = EfficientNet.from_pretrained('efficientnet-b4')
70+
model = EfficientNet.from_pretrained('efficientnet-b4')
7271
```
7372

7473
### Overview
75-
This repository contains an op-for-op PyTorch reimplementation of [EfficientNet](https://arxiv.org/abs/1905.11946), along with pre-trained models and examples.
74+
This repository contains an op-for-op PyTorch reimplementation of [EfficientNet](https://arxiv.org/abs/1905.11946), along with pre-trained models and examples.
7675

77-
The goal of this implementation is to be simple, highly extensible, and easy to integrate into your own projects. This implementation is a work in progress -- new features are currently being implemented.
76+
The goal of this implementation is to be simple, highly extensible, and easy to integrate into your own projects. This implementation is a work in progress -- new features are currently being implemented.
7877

79-
At the moment, you can easily:
80-
* Load pretrained EfficientNet models
81-
* Use EfficientNet models for classification or feature extraction
78+
At the moment, you can easily:
79+
* Load pretrained EfficientNet models
80+
* Use EfficientNet models for classification or feature extraction
8281
* Evaluate EfficientNet models on ImageNet or your own images
8382

8483
_Upcoming features_: In the next few days, you will be able to:
85-
* Train new models from scratch on ImageNet with a simple command
84+
* Train new models from scratch on ImageNet with a simple command
8685
* Quickly finetune an EfficientNet on your own dataset
8786
* Export EfficientNet models for production
8887

@@ -95,11 +94,11 @@ _Upcoming features_: In the next few days, you will be able to:
9594
* [Example: Classify](#example-classification)
9695
* [Example: Extract features](#example-feature-extraction)
9796
* [Example: Export to ONNX](#example-export)
98-
6. [Contributing](#contributing)
97+
6. [Contributing](#contributing)
9998

10099
### About EfficientNet
101100

102-
If you're new to EfficientNets, here is an explanation straight from the official TensorFlow implementation:
101+
If you're new to EfficientNets, here is an explanation straight from the official TensorFlow implementation:
103102

104103
EfficientNets are a family of image classification models, which achieve state-of-the-art accuracy, yet being an order-of-magnitude smaller and faster than previous models. We develop EfficientNets based on AutoML and Compound Scaling. In particular, we first use [AutoML Mobile framework](https://ai.googleblog.com/2018/08/mnasnet-towards-automating-design-of.html) to develop a mobile-size baseline network, named as EfficientNet-B0; Then, we use the compound scaling method to scale up this baseline to obtain EfficientNet-B1 to B7.
105104

@@ -141,25 +140,25 @@ Or install from source:
141140
git clone https://github.com/lukemelas/EfficientNet-PyTorch
142141
cd EfficientNet-Pytorch
143142
pip install -e .
144-
```
143+
```
145144

146145
### Usage
147146

148147
#### Loading pretrained models
149148

150-
Load an EfficientNet:
149+
Load an EfficientNet:
151150
```python
152151
from efficientnet_pytorch import EfficientNet
153152
model = EfficientNet.from_name('efficientnet-b0')
154153
```
155154

156-
Load a pretrained EfficientNet:
155+
Load a pretrained EfficientNet:
157156
```python
158157
from efficientnet_pytorch import EfficientNet
159158
model = EfficientNet.from_pretrained('efficientnet-b0')
160159
```
161160

162-
Details about the models are below:
161+
Details about the models are below:
163162

164163
| *Name* |*# Params*|*Top-1 Acc.*|*Pretrained?*|
165164
|:-----------------:|:--------:|:----------:|:-----------:|
@@ -177,7 +176,7 @@ Details about the models are below:
177176

178177
Below is a simple, complete example. It may also be found as a jupyter notebook in `examples/simple` or as a [Colab Notebook](https://colab.research.google.com/drive/1Jw28xZ1NJq4Cja4jLe6tJ6_F5lCzElb4).
179178

180-
We assume that in your current directory, there is a `img.jpg` file and a `labels_map.txt` file (ImageNet class names). These are both included in `examples/simple`.
179+
We assume that in your current directory, there is a `img.jpg` file and a `labels_map.txt` file (ImageNet class names). These are both included in `examples/simple`.
181180

182181
```python
183182
import json
@@ -210,7 +209,7 @@ for idx in torch.topk(outputs, k=5).indices.squeeze(0).tolist():
210209
print('{label:<75} ({p:.2f}%)'.format(label=labels_map[idx], p=prob*100))
211210
```
212211

213-
#### Example: Feature Extraction
212+
#### Example: Feature Extraction
214213

215214
You can easily extract features with `model.extract_features`:
216215
```python
@@ -224,20 +223,20 @@ features = model.extract_features(img)
224223
print(features.shape) # torch.Size([1, 1280, 7, 7])
225224
```
226225

227-
#### Example: Export to ONNX
226+
#### Example: Export to ONNX
228227

229-
Exporting to ONNX for deploying to production is now simple:
228+
Exporting to ONNX for deploying to production is now simple:
230229
```python
231-
import torch
230+
import torch
232231
from efficientnet_pytorch import EfficientNet
233232

234233
model = EfficientNet.from_pretrained('efficientnet-b1')
235234
dummy_input = torch.randn(10, 3, 240, 240)
236235

237236
torch.onnx.export(model, dummy_input, "test-b1.onnx", verbose=True)
238-
```
237+
```
239238

240-
[Here](https://colab.research.google.com/drive/1rOAEXeXHaA8uo3aG2YcFDHItlRJMV0VP) is a Colab example.
239+
[Here](https://colab.research.google.com/drive/1rOAEXeXHaA8uo3aG2YcFDHItlRJMV0VP) is a Colab example.
241240

242241

243242
#### ImageNet
@@ -246,6 +245,6 @@ See `examples/imagenet` for details about evaluating on ImageNet.
246245

247246
### Contributing
248247

249-
If you find a bug, create a GitHub issue, or even better, submit a pull request. Similarly, if you have questions, simply post them as GitHub issues.
248+
If you find a bug, create a GitHub issue, or even better, submit a pull request. Similarly, if you have questions, simply post them as GitHub issues.
250249

251-
I look forward to seeing what the community does with these models!
250+
I look forward to seeing what the community does with these models!

efficientnet_pytorch/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,3 @@
77
efficientnet,
88
get_model_params,
99
)
10-

efficientnet_pytorch/model.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def __init__(self, block_args, global_params, image_size=None):
7676

7777
# Squeeze and Excitation layer, if desired
7878
if self.has_se:
79-
Conv2d = get_same_padding_conv2d(image_size=(1,1))
79+
Conv2d = get_same_padding_conv2d(image_size=(1, 1))
8080
num_squeezed_channels = max(1, int(self._block_args.input_filters * self._block_args.se_ratio))
8181
self._se_reduce = Conv2d(in_channels=oup, out_channels=num_squeezed_channels, kernel_size=1)
8282
self._se_expand = Conv2d(in_channels=num_squeezed_channels, out_channels=oup, kernel_size=1)
@@ -147,7 +147,7 @@ class EfficientNet(nn.Module):
147147
Args:
148148
blocks_args (list[namedtuple]): A list of BlockArgs to construct blocks.
149149
global_params (namedtuple): A set of GlobalParams shared between blocks.
150-
150+
151151
References:
152152
[1] https://arxiv.org/abs/1905.11946 (EfficientNet)
153153
@@ -261,12 +261,12 @@ def extract_endpoints(self, inputs):
261261
drop_connect_rate *= float(idx) / len(self._blocks) # scale drop connect_rate
262262
x = block(x, drop_connect_rate=drop_connect_rate)
263263
if prev_x.size(2) > x.size(2):
264-
endpoints[f'reduction_{len(endpoints)+1}'] = prev_x
264+
endpoints['reduction_{}'.format(len(endpoints)+1)] = prev_x
265265
prev_x = x
266266

267267
# Head
268268
x = self._swish(self._bn1(self._conv_head(x)))
269-
endpoints[f'reduction_{len(endpoints)+1}'] = x
269+
endpoints['reduction_{}'.format(len(endpoints)+1)] = x
270270

271271
return endpoints
272272

@@ -277,7 +277,7 @@ def extract_features(self, inputs):
277277
inputs (tensor): Input tensor.
278278
279279
Returns:
280-
Output of the final convolution
280+
Output of the final convolution
281281
layer in the efficientnet model.
282282
"""
283283
# Stem
@@ -289,7 +289,7 @@ def extract_features(self, inputs):
289289
if drop_connect_rate:
290290
drop_connect_rate *= float(idx) / len(self._blocks) # scale drop connect_rate
291291
x = block(x, drop_connect_rate=drop_connect_rate)
292-
292+
293293
# Head
294294
x = self._swish(self._bn1(self._conv_head(x)))
295295

@@ -323,7 +323,7 @@ def from_name(cls, model_name, in_channels=3, **override_params):
323323
Args:
324324
model_name (str): Name for efficientnet.
325325
in_channels (int): Input data's channel number.
326-
override_params (other key word params):
326+
override_params (other key word params):
327327
Params to override model's global_params.
328328
Optional key:
329329
'width_coefficient', 'depth_coefficient',
@@ -342,35 +342,35 @@ def from_name(cls, model_name, in_channels=3, **override_params):
342342
return model
343343

344344
@classmethod
345-
def from_pretrained(cls, model_name, weights_path=None, advprop=False,
345+
def from_pretrained(cls, model_name, weights_path=None, advprop=False,
346346
in_channels=3, num_classes=1000, **override_params):
347347
"""create an efficientnet model according to name.
348348
349349
Args:
350350
model_name (str): Name for efficientnet.
351-
weights_path (None or str):
351+
weights_path (None or str):
352352
str: path to pretrained weights file on the local disk.
353353
None: use pretrained weights downloaded from the Internet.
354-
advprop (bool):
354+
advprop (bool):
355355
Whether to load pretrained weights
356356
trained with advprop (valid when weights_path is None).
357357
in_channels (int): Input data's channel number.
358-
num_classes (int):
358+
num_classes (int):
359359
Number of categories for classification.
360360
It controls the output size for final linear layer.
361-
override_params (other key word params):
361+
override_params (other key word params):
362362
Params to override model's global_params.
363363
Optional key:
364364
'width_coefficient', 'depth_coefficient',
365365
'image_size', 'dropout_rate',
366-
'num_classes', 'batch_norm_momentum',
366+
'batch_norm_momentum',
367367
'batch_norm_epsilon', 'drop_connect_rate',
368368
'depth_divisor', 'min_depth'
369369
370370
Returns:
371371
A pretrained efficientnet model.
372372
"""
373-
model = cls.from_name(model_name, num_classes = num_classes, **override_params)
373+
model = cls.from_name(model_name, num_classes=num_classes, **override_params)
374374
load_pretrained_weights(model, model_name, weights_path=weights_path, load_fc=(num_classes == 1000), advprop=advprop)
375375
model._change_in_channels(in_channels)
376376
return model
@@ -391,7 +391,7 @@ def get_image_size(cls, model_name):
391391

392392
@classmethod
393393
def _check_model_name_is_valid(cls, model_name):
394-
"""Validates model name.
394+
"""Validates model name.
395395
396396
Args:
397397
model_name (str): Name for efficientnet.
@@ -409,6 +409,6 @@ def _change_in_channels(self, in_channels):
409409
in_channels (int): Input data's channel number.
410410
"""
411411
if in_channels != 3:
412-
Conv2d = get_same_padding_conv2d(image_size = self._global_params.image_size)
412+
Conv2d = get_same_padding_conv2d(image_size=self._global_params.image_size)
413413
out_channels = round_filters(32, self._global_params)
414414
self._conv_stem = Conv2d(in_channels, out_channels, kernel_size=3, stride=2, bias=False)

0 commit comments

Comments
 (0)