├── .gitignore ├── Keras_efficientnet_transfer_learning.ipynb ├── MANIFEST.in ├── README.md ├── __init__.py ├── efficientnet ├── __init__.py ├── __version__.py ├── initializers.py ├── layers.py ├── model.py ├── params.py └── preprocessing.py ├── examples ├── base_conv.ipynb ├── custom_initializer.ipynb └── inference_exmaple.ipynb ├── misc ├── labels_map.txt └── panda.jpg └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | .idea/ 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | .hypothesis/ 49 | .pytest_cache/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | db.sqlite3 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # pyenv 77 | .python-version 78 | 79 | # celery beat schedule file 80 | celerybeat-schedule 81 | 82 | # SageMath parsed files 83 | *.sage.py 84 | 85 | # Environments 86 | .env 87 | .venv 88 | env/ 89 | venv/ 90 | ENV/ 91 | env.bak/ 92 | venv.bak/ 93 | 94 | # Spyder project settings 95 | .spyderproject 96 | .spyproject 97 | 98 | # Rope project settings 99 | .ropeproject 100 | 101 | # mkdocs documentation 102 | /site 103 | 104 | # mypy 105 | .mypy_cache/ 106 | 107 | .vscode/ 108 | 109 | models/ 110 | data/ 111 | examples/*.png 112 | examples/*.svg 113 | *.h5 114 | *.pb -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EfficientNet-Keras 2 | 3 | This repository contains Keras reimplementation of EfficientNet, the new convolutional neural network architecture from [EfficientNet](https://arxiv.org/abs/1905.11946) ([TensorFlow implementation](https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet)). 4 | 5 | ### Table of content 6 | 1. [About EfficientNets](#about) 7 | 2. [Examples](#examples) 8 | 3. [Models](#models) 9 | 4. [Installation](#installation) 10 | 11 | 12 | ### About EfficientNet Models 13 | 14 | If you're new to EfficientNets, here is an explanation straight from the official TensorFlow implementation: 15 | 16 | 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. EfficientNets are based on AutoML and Compound Scaling. In particular, [AutoML Mobile framework](https://ai.googleblog.com/2018/08/mnasnet-towards-automating-design-of.html) have been used to develop a mobile-size baseline network, named as EfficientNet-B0; Then, the compound scaling method is used to scale up this baseline to obtain EfficientNet-B1 to B7. 17 | 18 | 19 | 20 | 23 | 26 | 27 |
21 | 22 | 24 | 25 |
28 | 29 | EfficientNets achieve state-of-the-art accuracy on ImageNet with an order of magnitude better efficiency: 30 | 31 | 32 | * In high-accuracy regime, EfficientNet-B7 achieves state-of-the-art 84.4% top-1 / 97.1% top-5 accuracy on ImageNet with 66M parameters and 37B FLOPS, being 8.4x smaller and 6.1x faster on CPU inference than previous best [Gpipe](https://arxiv.org/abs/1811.06965). 33 | 34 | * In middle-accuracy regime, EfficientNet-B1 is 7.6x smaller and 5.7x faster on CPU inference than [ResNet-152](https://arxiv.org/abs/1512.03385), with similar ImageNet accuracy. 35 | 36 | * Compared with the widely used [ResNet-50](https://arxiv.org/abs/1512.03385), EfficientNet-B4 improves the top-1 accuracy from 76.3% of ResNet-50 to 82.6% (+6.3%), under similar FLOPS constraint. 37 | 38 | ### Examples 39 | 40 | - Two lines to create model: 41 | 42 | ```python 43 | from efficientnet import EfficientNetB0 44 | 45 | model = EfficientNetB0(weights='imagenet') 46 | 47 | ``` 48 | 49 | - Inference example: 50 | [inference_example.ipynb](https://github.com/qubvel/efficientnet/blob/master/examples/inference_exmaple.ipynb) 51 | 52 | - Loading saved model: 53 | 54 | ```python 55 | from efficientnet import load_model 56 | 57 | model = load_model('path/to/model.h5') 58 | ``` 59 | 60 | ### Models 61 | 62 | Available architectures and pretrained weights (converted from original repo): 63 | 64 | | Architecture | @top1*| @top5*| Weights | 65 | |----------------|:-----:|:-----:|:-------:| 66 | | EfficientNetB0 |0.7668 |0.9312 | + | 67 | | EfficientNetB1 |0.7863 |0.9418 | + | 68 | | EfficientNetB2 |0.7968 |0.9475 | + | 69 | | EfficientNetB3 |0.8083 |0.9531 | + | 70 | | EfficientNetB4 | - | - | - | 71 | | EfficientNetB5 | - | - | - | 72 | | EfficientNetB6 | - | - | - | 73 | | EfficientNetB7 | - | - | - | 74 | 75 | "*" - topK accuracy score for converted models (imagenet `val` set) 76 | 77 | Weights for B4-B7 are not released yet ([issue](https://github.com/tensorflow/tpu/issues/377)). 78 | 79 | ### Installation 80 | 81 | Requirements: 82 | - keras >= 2.2.0 (tensorflow) 83 | - scikit-image 84 | 85 | Source: 86 | 87 | ```bash 88 | $ pip install -U git+https://github.com/qubvel/efficientnet 89 | ``` 90 | 91 | PyPI: 92 | 93 | ```bash 94 | $ pip install -U efficientnet 95 | ``` 96 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from .efficientnet import * -------------------------------------------------------------------------------- /efficientnet/__init__.py: -------------------------------------------------------------------------------- 1 | from .model import * 2 | from .preprocessing import center_crop_and_resize 3 | from .preprocessing import preprocess_input 4 | from keras.models import load_model -------------------------------------------------------------------------------- /efficientnet/__version__.py: -------------------------------------------------------------------------------- 1 | VERSION = (0, 0, 3) 2 | 3 | __version__ = '.'.join(map(str, VERSION)) -------------------------------------------------------------------------------- /efficientnet/initializers.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorflow as tf 3 | import keras.backend as K 4 | 5 | from keras.initializers import Initializer 6 | from keras.utils.generic_utils import get_custom_objects 7 | 8 | 9 | class EfficientConv2DKernelInitializer(Initializer): 10 | """Initialization for convolutional kernels. 11 | 12 | The main difference with tf.variance_scaling_initializer is that 13 | tf.variance_scaling_initializer uses a truncated normal with an uncorrected 14 | standard deviation, whereas here we use a normal distribution. Similarly, 15 | tf.contrib.layers.variance_scaling_initializer uses a truncated normal with 16 | a corrected standard deviation. 17 | 18 | Args: 19 | shape: shape of variable 20 | dtype: dtype of variable 21 | partition_info: unused 22 | 23 | Returns: 24 | an initialization for the variable 25 | """ 26 | 27 | def __call__(self, shape, dtype=K.floatx(), **kwargs): 28 | kernel_height, kernel_width, _, out_filters = shape 29 | fan_out = int(kernel_height * kernel_width * out_filters) 30 | return tf.random_normal( 31 | shape, mean=0.0, stddev=np.sqrt(2.0 / fan_out), dtype=dtype) 32 | 33 | 34 | class EfficientDenseKernelInitializer(Initializer): 35 | """Initialization for dense kernels. 36 | 37 | This initialization is equal to 38 | tf.variance_scaling_initializer(scale=1.0/3.0, mode='fan_out', 39 | distribution='uniform'). 40 | It is written out explicitly here for clarity. 41 | 42 | Args: 43 | shape: shape of variable 44 | dtype: dtype of variable 45 | 46 | Returns: 47 | an initialization for the variable 48 | """ 49 | 50 | def __call__(self, shape, dtype=K.floatx(), **kwargs): 51 | """Initialization for dense kernels. 52 | 53 | This initialization is equal to 54 | tf.variance_scaling_initializer(scale=1.0/3.0, mode='fan_out', 55 | distribution='uniform'). 56 | It is written out explicitly here for clarity. 57 | 58 | Args: 59 | shape: shape of variable 60 | dtype: dtype of variable 61 | 62 | Returns: 63 | an initialization for the variable 64 | """ 65 | init_range = 1.0 / np.sqrt(shape[1]) 66 | return tf.random_uniform(shape, -init_range, init_range, dtype=dtype) 67 | 68 | 69 | conv_kernel_initializer = EfficientConv2DKernelInitializer() 70 | dense_kernel_initializer = EfficientDenseKernelInitializer() 71 | 72 | 73 | get_custom_objects().update({ 74 | 'EfficientDenseKernelInitializer': EfficientDenseKernelInitializer, 75 | 'EfficientConv2DKernelInitializer': EfficientConv2DKernelInitializer, 76 | }) 77 | -------------------------------------------------------------------------------- /efficientnet/layers.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import tensorflow.keras.backend as K 3 | import tensorflow.keras.layers as KL 4 | from tensorflow.keras.utils import get_custom_objects 5 | 6 | 7 | class Swish(KL.Layer): 8 | def __init__(self, **kwargs): 9 | super().__init__(**kwargs) 10 | def call(self, inputs, **kwargs): 11 | return tf.nn.swish(inputs) 12 | 13 | 14 | class DropConnect(KL.Layer): 15 | 16 | def __init__(self, drop_connect_rate=0., **kwargs): 17 | super().__init__(**kwargs) 18 | self.drop_connect_rate = drop_connect_rate 19 | 20 | def call(self, inputs, training=None): 21 | 22 | def drop_connect(): 23 | keep_prob = 1.0 - self.drop_connect_rate 24 | 25 | # Compute drop_connect tensor 26 | batch_size = tf.shape(inputs)[0] 27 | random_tensor = keep_prob 28 | random_tensor += tf.random_uniform([batch_size, 1, 1, 1], dtype=inputs.dtype) 29 | binary_tensor = tf.floor(random_tensor) 30 | output = tf.div(inputs, keep_prob) * binary_tensor 31 | return output 32 | 33 | 34 | return K.in_train_phase(drop_connect, inputs, training=training) 35 | 36 | def get_config(self): 37 | config = super().get_config() 38 | config['drop_connect_rate'] = self.drop_connect_rate 39 | return config 40 | 41 | 42 | get_custom_objects().update({ 43 | 'DropConnect': DropConnect, 44 | 'Swish': Swish, 45 | }) 46 | -------------------------------------------------------------------------------- /efficientnet/model.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved. 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 | """Contains definitions for EfficientNet model. 16 | 17 | [1] Mingxing Tan, Quoc V. Le 18 | EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks. 19 | ICML'19, https://arxiv.org/abs/1905.11946 20 | """ 21 | 22 | from __future__ import absolute_import 23 | from __future__ import division 24 | from __future__ import print_function 25 | 26 | import collections 27 | import math 28 | import numpy as np 29 | import six 30 | from six.moves import xrange # pylint: disable=redefined-builtin 31 | import tensorflow as tf 32 | 33 | import tensorflow.keras.backend as K 34 | import tensorflow.keras.models as KM 35 | import tensorflow.keras.layers as KL 36 | from tensorflow.keras.utils import get_file 37 | from tensorflow.keras.initializers import Initializer 38 | from .layers import Swish, DropConnect 39 | from .params import get_model_params, IMAGENET_WEIGHTS 40 | from .initializers import conv_kernel_initializer, dense_kernel_initializer 41 | 42 | 43 | __all__ = ['EfficientNet', 'EfficientNetB0', 'EfficientNetB1', 'EfficientNetB2', 'EfficientNetB3', 44 | 'EfficientNetB4', 'EfficientNetB5', 'EfficientNetB6', 'EfficientNetB7'] 45 | 46 | class ConvKernalInitializer(Initializer): 47 | def __call__(self, shape, dtype=K.floatx(), partition_info=None): 48 | """Initialization for convolutional kernels. 49 | 50 | The main difference with tf.variance_scaling_initializer is that 51 | tf.variance_scaling_initializer uses a truncated normal with an uncorrected 52 | standard deviation, whereas here we use a normal distribution. Similarly, 53 | tf.contrib.layers.variance_scaling_initializer uses a truncated normal with 54 | a corrected standard deviation. 55 | 56 | Args: 57 | shape: shape of variable 58 | dtype: dtype of variable 59 | partition_info: unused 60 | 61 | Returns: 62 | an initialization for the variable 63 | """ 64 | del partition_info 65 | kernel_height, kernel_width, _, out_filters = shape 66 | fan_out = int(kernel_height * kernel_width * out_filters) 67 | return tf.random_normal( 68 | shape, mean=0.0, stddev=np.sqrt(2.0 / fan_out), dtype=dtype) 69 | 70 | class DenseKernalInitializer(Initializer): 71 | def __call__(self, shape, dtype=K.floatx(), partition_info=None): 72 | """Initialization for dense kernels. 73 | 74 | This initialization is equal to 75 | tf.variance_scaling_initializer(scale=1.0/3.0, mode='fan_out', 76 | distribution='uniform'). 77 | It is written out explicitly here for clarity. 78 | 79 | Args: 80 | shape: shape of variable 81 | dtype: dtype of variable 82 | partition_info: unused 83 | 84 | Returns: 85 | an initialization for the variable 86 | """ 87 | del partition_info 88 | init_range = 1.0 / np.sqrt(shape[1]) 89 | return tf.random_uniform(shape, -init_range, init_range, dtype=dtype) 90 | 91 | 92 | def round_filters(filters, global_params): 93 | """Round number of filters based on depth multiplier.""" 94 | orig_f = filters 95 | multiplier = global_params.width_coefficient 96 | divisor = global_params.depth_divisor 97 | min_depth = global_params.min_depth 98 | if not multiplier: 99 | return filters 100 | 101 | filters *= multiplier 102 | min_depth = min_depth or divisor 103 | new_filters = max(min_depth, int(filters + divisor / 2) // divisor * divisor) 104 | # Make sure that round down does not go down by more than 10%. 105 | if new_filters < 0.9 * filters: 106 | new_filters += divisor 107 | # print('round_filter input={} output={}'.format(orig_f, new_filters)) 108 | return int(new_filters) 109 | 110 | 111 | def round_repeats(repeats, global_params): 112 | """Round number of filters based on depth multiplier.""" 113 | multiplier = global_params.depth_coefficient 114 | if not multiplier: 115 | return repeats 116 | return int(math.ceil(multiplier * repeats)) 117 | 118 | 119 | def SEBlock(block_args, global_params): 120 | num_reduced_filters = max( 121 | 1, int(block_args.input_filters * block_args.se_ratio)) 122 | filters = block_args.input_filters * block_args.expand_ratio 123 | if global_params.data_format == 'channels_first': 124 | channel_axis = 1 125 | spatial_dims = [2, 3] 126 | else: 127 | channel_axis = -1 128 | spatial_dims = [1, 2] 129 | 130 | def block(inputs): 131 | x = inputs 132 | x = KL.Lambda(lambda a: K.mean(a, axis=spatial_dims, keepdims=True))(x) 133 | x = KL.Conv2D( 134 | num_reduced_filters, 135 | kernel_size=[1, 1], 136 | strides=[1, 1], 137 | kernel_initializer=ConvKernalInitializer(), 138 | padding='same', 139 | use_bias=True 140 | )(x) 141 | x = Swish()(x) 142 | # Excite 143 | x = KL.Conv2D( 144 | filters, 145 | kernel_size=[1, 1], 146 | strides=[1, 1], 147 | kernel_initializer=ConvKernalInitializer(), 148 | padding='same', 149 | use_bias=True 150 | )(x) 151 | x = KL.Activation('sigmoid')(x) 152 | out = KL.Multiply()([x, inputs]) 153 | return out 154 | 155 | return block 156 | 157 | 158 | def MBConvBlock(block_args, global_params, drop_connect_rate=None): 159 | batch_norm_momentum = global_params.batch_norm_momentum 160 | batch_norm_epsilon = global_params.batch_norm_epsilon 161 | 162 | if global_params.data_format == 'channels_first': 163 | channel_axis = 1 164 | spatial_dims = [2, 3] 165 | else: 166 | channel_axis = -1 167 | spatial_dims = [1, 2] 168 | 169 | has_se = (block_args.se_ratio is not None) and ( 170 | block_args.se_ratio > 0) and (block_args.se_ratio <= 1) 171 | 172 | filters = block_args.input_filters * block_args.expand_ratio 173 | kernel_size = block_args.kernel_size 174 | 175 | def block(inputs): 176 | 177 | if block_args.expand_ratio != 1: 178 | x = KL.Conv2D( 179 | filters, 180 | kernel_size=[1, 1], 181 | strides=[1, 1], 182 | kernel_initializer=ConvKernalInitializer(), 183 | padding='same', 184 | use_bias=False 185 | )(inputs) 186 | x = KL.BatchNormalization( 187 | axis=channel_axis, 188 | momentum=batch_norm_momentum, 189 | epsilon=batch_norm_epsilon 190 | )(x) 191 | x = Swish()(x) 192 | else: 193 | x = inputs 194 | 195 | x = KL.DepthwiseConv2D( 196 | [kernel_size, kernel_size], 197 | strides=block_args.strides, 198 | depthwise_initializer=ConvKernalInitializer(), 199 | padding='same', 200 | use_bias=False 201 | )(x) 202 | x = KL.BatchNormalization( 203 | axis=channel_axis, 204 | momentum=batch_norm_momentum, 205 | epsilon=batch_norm_epsilon 206 | )(x) 207 | x = Swish()(x) 208 | 209 | if has_se: 210 | x = SEBlock(block_args, global_params)(x) 211 | 212 | # output phase 213 | 214 | x = KL.Conv2D( 215 | block_args.output_filters, 216 | kernel_size=[1, 1], 217 | strides=[1, 1], 218 | kernel_initializer=ConvKernalInitializer(), 219 | padding='same', 220 | use_bias=False 221 | )(x) 222 | x = KL.BatchNormalization( 223 | axis=channel_axis, 224 | momentum=batch_norm_momentum, 225 | epsilon=batch_norm_epsilon 226 | )(x) 227 | 228 | if block_args.id_skip: 229 | if all( 230 | s == 1 for s in block_args.strides 231 | ) and block_args.input_filters == block_args.output_filters: 232 | # only apply drop_connect if skip presents. 233 | if drop_connect_rate: 234 | x = DropConnect(drop_connect_rate)(x) 235 | x = KL.Add()([x, inputs]) 236 | return x 237 | 238 | return block 239 | 240 | 241 | def EfficientNet(input_shape, block_args_list, global_params, include_top=True, pooling=None): 242 | batch_norm_momentum = global_params.batch_norm_momentum 243 | batch_norm_epsilon = global_params.batch_norm_epsilon 244 | if global_params.data_format == 'channels_first': 245 | channel_axis = 1 246 | else: 247 | channel_axis = -1 248 | 249 | # Stem part 250 | inputs = KL.Input(shape=input_shape) 251 | x = inputs 252 | x = KL.Conv2D( 253 | filters=round_filters(32, global_params), 254 | kernel_size=[3, 3], 255 | strides=[2, 2], 256 | kernel_initializer=ConvKernalInitializer(), 257 | padding='same', 258 | use_bias=False 259 | )(x) 260 | x = KL.BatchNormalization( 261 | axis=channel_axis, 262 | momentum=batch_norm_momentum, 263 | epsilon=batch_norm_epsilon 264 | )(x) 265 | x = Swish()(x) 266 | 267 | # Blocks part 268 | block_idx = 1 269 | n_blocks = sum([block_args.num_repeat for block_args in block_args_list]) 270 | drop_rate = global_params.drop_connect_rate or 0 271 | drop_rate_dx = drop_rate / n_blocks 272 | 273 | for block_args in block_args_list: 274 | assert block_args.num_repeat > 0 275 | # Update block input and output filters based on depth multiplier. 276 | block_args = block_args._replace( 277 | input_filters=round_filters(block_args.input_filters, global_params), 278 | output_filters=round_filters(block_args.output_filters, global_params), 279 | num_repeat=round_repeats(block_args.num_repeat, global_params) 280 | ) 281 | 282 | # The first block needs to take care of stride and filter size increase. 283 | x = MBConvBlock(block_args, global_params, 284 | drop_connect_rate=drop_rate_dx * block_idx)(x) 285 | block_idx += 1 286 | 287 | if block_args.num_repeat > 1: 288 | block_args = block_args._replace(input_filters=block_args.output_filters, strides=[1, 1]) 289 | 290 | for _ in xrange(block_args.num_repeat - 1): 291 | x = MBConvBlock(block_args, global_params, 292 | drop_connect_rate=drop_rate_dx * block_idx)(x) 293 | block_idx += 1 294 | 295 | # Head part 296 | x = KL.Conv2D( 297 | filters=round_filters(1280, global_params), 298 | kernel_size=[1, 1], 299 | strides=[1, 1], 300 | kernel_initializer=ConvKernalInitializer(), 301 | padding='same', 302 | use_bias=False 303 | )(x) 304 | x = KL.BatchNormalization( 305 | axis=channel_axis, 306 | momentum=batch_norm_momentum, 307 | epsilon=batch_norm_epsilon 308 | )(x) 309 | x = Swish()(x) 310 | 311 | if include_top: 312 | x = KL.GlobalAveragePooling2D(data_format=global_params.data_format)(x) 313 | if global_params.dropout_rate > 0: 314 | x = KL.Dropout(global_params.dropout_rate)(x) 315 | x = KL.Dense(global_params.num_classes, kernel_initializer=DenseKernalInitializer())(x) 316 | x = KL.Activation('softmax')(x) 317 | else: 318 | if pooling == 'avg': 319 | x = KL.GlobalAveragePooling2D(data_format=global_params.data_format)(x) 320 | elif pooling == 'max': 321 | x = KL.GlobalMaxPooling2D(data_format=global_params.data_format)(x) 322 | 323 | outputs = x 324 | model = KM.Model(inputs, outputs) 325 | 326 | return model 327 | 328 | 329 | def _get_model_by_name(model_name, input_shape=None, include_top=True, weights=None, classes=1000, pooling=None): 330 | """Re-Implementation of EfficientNet for Keras 331 | 332 | Reference: 333 | https://arxiv.org/abs/1807.11626 334 | 335 | Args: 336 | input_shape: optional, if ``None`` default_input_shape is used 337 | EfficientNetB0 - (224, 224, 3) 338 | EfficientNetB1 - (240, 240, 3) 339 | EfficientNetB2 - (260, 260, 3) 340 | EfficientNetB3 - (300, 300, 3) 341 | EfficientNetB4 - (380, 380, 3) 342 | EfficientNetB5 - (456, 456, 3) 343 | EfficientNetB6 - (528, 528, 3) 344 | EfficientNetB7 - (600, 600, 3) 345 | include_top: whether to include the fully-connected 346 | layer at the top of the network. 347 | weights: one of `None` (random initialization), 348 | 'imagenet' (pre-training on ImageNet). 349 | classes: optional number of classes to classify images 350 | into, only to be specified if `include_top` is True, and 351 | if no `weights` argument is specified. 352 | pooling: optional [None, 'avg', 'max'], if ``include_top=False`` 353 | add global pooling on top of the network 354 | - avg: GlobalAveragePooling2D 355 | - max: GlobalMaxPooling2D 356 | 357 | Returns: 358 | A Keras model instance. 359 | 360 | """ 361 | if weights not in {None, 'imagenet'}: 362 | raise ValueError('Parameter `weights` should be one of [None, "imagenet"]') 363 | 364 | if weights == 'imagenet' and model_name not in IMAGENET_WEIGHTS: 365 | raise ValueError('There are not pretrained weights for {} model.'.format(model_name)) 366 | 367 | if weights == 'imagenet' and include_top and classes != 1000: 368 | raise ValueError('If using `weights` and `include_top`' 369 | ' `classes` should be 1000') 370 | 371 | block_agrs_list, global_params, default_input_shape = get_model_params( 372 | model_name, override_params={'num_classes': classes} 373 | ) 374 | 375 | if input_shape is None: 376 | input_shape = (default_input_shape, default_input_shape, 3) 377 | 378 | model = EfficientNet(input_shape, block_agrs_list, global_params, include_top=include_top, pooling=pooling) 379 | model._name = model_name 380 | 381 | if weights: 382 | if not include_top: 383 | weights_name = model_name + '-notop' 384 | else: 385 | weights_name = model_name 386 | weights = IMAGENET_WEIGHTS[weights_name] 387 | weights_path = get_file( 388 | weights['name'], 389 | weights['url'], 390 | cache_subdir='models', 391 | md5_hash=weights['md5'], 392 | ) 393 | model.load_weights(weights_path) 394 | 395 | return model 396 | 397 | 398 | def EfficientNetB0(include_top=True, input_shape=None, weights=None, classes=1000, pooling=None): 399 | return _get_model_by_name('efficientnet-b0', include_top=include_top, input_shape=input_shape, 400 | weights=weights, classes=classes, pooling=pooling) 401 | 402 | 403 | def EfficientNetB1(include_top=True, input_shape=None, weights=None, classes=1000, pooling=None): 404 | return _get_model_by_name('efficientnet-b1', include_top=include_top, input_shape=input_shape, 405 | weights=weights, classes=classes, pooling=pooling) 406 | 407 | 408 | def EfficientNetB2(include_top=True, input_shape=None, weights=None, classes=1000, pooling=None): 409 | return _get_model_by_name('efficientnet-b2', include_top=include_top, input_shape=input_shape, 410 | weights=weights, classes=classes, pooling=pooling) 411 | 412 | 413 | def EfficientNetB3(include_top=True, input_shape=None, weights=None, classes=1000, pooling=None): 414 | return _get_model_by_name('efficientnet-b3', include_top=include_top, input_shape=input_shape, 415 | weights=weights, classes=classes, pooling=pooling) 416 | 417 | 418 | def EfficientNetB4(include_top=True, input_shape=None, weights=None, classes=1000, pooling=None): 419 | return _get_model_by_name('efficientnet-b4', include_top=include_top, input_shape=input_shape, 420 | weights=weights, classes=classes, pooling=pooling) 421 | 422 | 423 | def EfficientNetB5(include_top=True, input_shape=None, weights=None, classes=1000, pooling=None): 424 | return _get_model_by_name('efficientnet-b5', include_top=include_top, input_shape=input_shape, 425 | weights=weights, classes=classes, pooling=pooling) 426 | 427 | 428 | def EfficientNetB6(include_top=True, input_shape=None, weights=None, classes=1000, pooling=None): 429 | return _get_model_by_name('efficientnet-b6', include_top=include_top, input_shape=input_shape, 430 | weights=weights, classes=classes, pooling=pooling) 431 | 432 | 433 | def EfficientNetB7(include_top=True, input_shape=None, weights=None, classes=1000, pooling=None): 434 | return _get_model_by_name('efficientnet-b7', include_top=include_top, input_shape=input_shape, 435 | weights=weights, classes=classes, pooling=pooling) 436 | 437 | 438 | EfficientNetB0.__doc__ = _get_model_by_name.__doc__ 439 | EfficientNetB1.__doc__ = _get_model_by_name.__doc__ 440 | EfficientNetB2.__doc__ = _get_model_by_name.__doc__ 441 | EfficientNetB3.__doc__ = _get_model_by_name.__doc__ 442 | EfficientNetB4.__doc__ = _get_model_by_name.__doc__ 443 | EfficientNetB5.__doc__ = _get_model_by_name.__doc__ 444 | EfficientNetB6.__doc__ = _get_model_by_name.__doc__ 445 | EfficientNetB7.__doc__ = _get_model_by_name.__doc__ 446 | -------------------------------------------------------------------------------- /efficientnet/params.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import collections 4 | 5 | 6 | IMAGENET_WEIGHTS = { 7 | 8 | 'efficientnet-b0': { 9 | 'name': 'efficientnet-b0_imagenet_1000.h5', 10 | 'url': 'https://github.com/qubvel/efficientnet/releases/download/v0.0.1/efficientnet-b0_imagenet_1000.h5', 11 | 'md5': 'bca04d16b1b8a7c607b1152fe9261af7', 12 | }, 13 | 14 | 'efficientnet-b0-notop': { 15 | 'name': 'efficientnet-b0_imagenet_1000_notop.h5', 16 | 'url': 'https://github.com/qubvel/efficientnet/releases/download/v0.0.1/efficientnet-b0_imagenet_1000_notop.h5', 17 | 'md5': '45d2f3b6330c2401ef66da3961cad769', 18 | }, 19 | 20 | 'efficientnet-b1': { 21 | 'name': 'efficientnet-b1_imagenet_1000.h5', 22 | 'url': 'https://github.com/qubvel/efficientnet/releases/download/v0.0.1/efficientnet-b1_imagenet_1000.h5', 23 | 'md5': 'bd4a2b82f6f6bada74fc754553c464fc', 24 | }, 25 | 26 | 'efficientnet-b1-notop': { 27 | 'name': 'efficientnet-b1_imagenet_1000_notop.h5', 28 | 'url': 'https://github.com/qubvel/efficientnet/releases/download/v0.0.1/efficientnet-b1_imagenet_1000_notop.h5', 29 | 'md5': '884aed586c2d8ca8dd15a605ec42f564', 30 | }, 31 | 32 | 'efficientnet-b2': { 33 | 'name': 'efficientnet-b2_imagenet_1000.h5', 34 | 'url': 'https://github.com/qubvel/efficientnet/releases/download/v0.0.1/efficientnet-b2_imagenet_1000.h5', 35 | 'md5': '45b28b26f15958bac270ab527a376999', 36 | }, 37 | 38 | 'efficientnet-b2-notop': { 39 | 'name': 'efficientnet-b2_imagenet_1000_notop.h5', 40 | 'url': 'https://github.com/qubvel/efficientnet/releases/download/v0.0.1/efficientnet-b2_imagenet_1000_notop.h5', 41 | 'md5': '42fb9f2d9243d461d62b4555d3a53b7b', 42 | }, 43 | 44 | 'efficientnet-b3': { 45 | 'name': 'efficientnet-b3_imagenet_1000.h5', 46 | 'url': 'https://github.com/qubvel/efficientnet/releases/download/v0.0.1/efficientnet-b3_imagenet_1000.h5', 47 | 'md5': 'decd2c8a23971734f9d3f6b4053bf424', 48 | }, 49 | 50 | 'efficientnet-b3-notop': { 51 | 'name': 'efficientnet-b3_imagenet_1000_notop.h5', 52 | 'url': 'https://github.com/qubvel/efficientnet/releases/download/v0.0.1/efficientnet-b3_imagenet_1000_notop.h5', 53 | 'md5': '1f7d9a8c2469d2e3d3b97680d45df1e1', 54 | }, 55 | 56 | } 57 | 58 | 59 | GlobalParams = collections.namedtuple('GlobalParams', [ 60 | 'batch_norm_momentum', 'batch_norm_epsilon', 'dropout_rate', 'data_format', 61 | 'num_classes', 'width_coefficient', 'depth_coefficient', 62 | 'depth_divisor', 'min_depth', 'drop_connect_rate', 63 | ]) 64 | GlobalParams.__new__.__defaults__ = (None,) * len(GlobalParams._fields) 65 | 66 | BlockArgs = collections.namedtuple('BlockArgs', [ 67 | 'kernel_size', 'num_repeat', 'input_filters', 'output_filters', 68 | 'expand_ratio', 'id_skip', 'strides', 'se_ratio' 69 | ]) 70 | # defaults will be a public argument for namedtuple in Python 3.7 71 | # https://docs.python.org/3/library/collections.html#collections.namedtuple 72 | BlockArgs.__new__.__defaults__ = (None,) * len(BlockArgs._fields) 73 | 74 | 75 | def efficientnet_params(model_name): 76 | """Get efficientnet params based on model name.""" 77 | params_dict = { 78 | # (width_coefficient, depth_coefficient, resolution, dropout_rate) 79 | 'efficientnet-b0': (1.0, 1.0, 224, 0.2), 80 | 'efficientnet-b1': (1.0, 1.1, 240, 0.2), 81 | 'efficientnet-b2': (1.1, 1.2, 260, 0.3), 82 | 'efficientnet-b3': (1.2, 1.4, 300, 0.3), 83 | 'efficientnet-b4': (1.4, 1.8, 380, 0.4), 84 | 'efficientnet-b5': (1.6, 2.2, 456, 0.4), 85 | 'efficientnet-b6': (1.8, 2.6, 528, 0.5), 86 | 'efficientnet-b7': (2.0, 3.1, 600, 0.5), 87 | } 88 | return params_dict[model_name] 89 | 90 | 91 | class BlockDecoder(object): 92 | """Block Decoder for readability.""" 93 | 94 | def _decode_block_string(self, block_string): 95 | """Gets a block through a string notation of arguments.""" 96 | assert isinstance(block_string, str) 97 | ops = block_string.split('_') 98 | options = {} 99 | for op in ops: 100 | splits = re.split(r'(\d.*)', op) 101 | if len(splits) >= 2: 102 | key, value = splits[:2] 103 | options[key] = value 104 | 105 | if 's' not in options or len(options['s']) != 2: 106 | raise ValueError('Strides options should be a pair of integers.') 107 | 108 | return BlockArgs( 109 | kernel_size=int(options['k']), 110 | num_repeat=int(options['r']), 111 | input_filters=int(options['i']), 112 | output_filters=int(options['o']), 113 | expand_ratio=int(options['e']), 114 | id_skip=('noskip' not in block_string), 115 | se_ratio=float(options['se']) if 'se' in options else None, 116 | strides=[int(options['s'][0]), int(options['s'][1])]) 117 | 118 | def _encode_block_string(self, block): 119 | """Encodes a block to a string.""" 120 | args = [ 121 | 'r%d' % block.num_repeat, 122 | 'k%d' % block.kernel_size, 123 | 's%d%d' % (block.strides[0], block.strides[1]), 124 | 'e%s' % block.expand_ratio, 125 | 'i%d' % block.input_filters, 126 | 'o%d' % block.output_filters 127 | ] 128 | if block.se_ratio > 0 and block.se_ratio <= 1: 129 | args.append('se%s' % block.se_ratio) 130 | if block.id_skip is False: 131 | args.append('noskip') 132 | return '_'.join(args) 133 | 134 | def decode(self, string_list): 135 | """Decodes a list of string notations to specify blocks inside the network. 136 | 137 | Args: 138 | string_list: a list of strings, each string is a notation of block. 139 | 140 | Returns: 141 | A list of namedtuples to represent blocks arguments. 142 | """ 143 | assert isinstance(string_list, list) 144 | blocks_args = [] 145 | for block_string in string_list: 146 | blocks_args.append(self._decode_block_string(block_string)) 147 | return blocks_args 148 | 149 | def encode(self, blocks_args): 150 | """Encodes a list of Blocks to a list of strings. 151 | 152 | Args: 153 | blocks_args: A list of namedtuples to represent blocks arguments. 154 | Returns: 155 | a list of strings, each string is a notation of block. 156 | """ 157 | block_strings = [] 158 | for block in blocks_args: 159 | block_strings.append(self._encode_block_string(block)) 160 | return block_strings 161 | 162 | 163 | def efficientnet(width_coefficient=None, 164 | depth_coefficient=None, 165 | dropout_rate=0.2, 166 | drop_connect_rate=0.2): 167 | """Creates a efficientnet model.""" 168 | blocks_args = [ 169 | 'r1_k3_s11_e1_i32_o16_se0.25', 'r2_k3_s22_e6_i16_o24_se0.25', 170 | 'r2_k5_s22_e6_i24_o40_se0.25', 'r3_k3_s22_e6_i40_o80_se0.25', 171 | 'r3_k5_s11_e6_i80_o112_se0.25', 'r4_k5_s22_e6_i112_o192_se0.25', 172 | 'r1_k3_s11_e6_i192_o320_se0.25', 173 | ] 174 | global_params = GlobalParams( 175 | batch_norm_momentum=0.99, 176 | batch_norm_epsilon=1e-3, 177 | dropout_rate=dropout_rate, 178 | drop_connect_rate=drop_connect_rate, 179 | data_format='channels_last', 180 | num_classes=1000, 181 | width_coefficient=width_coefficient, 182 | depth_coefficient=depth_coefficient, 183 | depth_divisor=8, 184 | min_depth=None) 185 | decoder = BlockDecoder() 186 | return decoder.decode(blocks_args), global_params 187 | 188 | 189 | def get_model_params(model_name, override_params=None): 190 | """Get the block args and global params for a given model.""" 191 | if model_name.startswith('efficientnet'): 192 | width_coefficient, depth_coefficient, input_shape, dropout_rate = ( 193 | efficientnet_params(model_name)) 194 | blocks_args, global_params = efficientnet( 195 | width_coefficient, depth_coefficient, dropout_rate) 196 | else: 197 | raise NotImplementedError('model name is not pre-defined: %s' % model_name) 198 | 199 | if override_params: 200 | # ValueError will be raised here if override_params has fields not included 201 | # in global_params. 202 | global_params = global_params._replace(**override_params) 203 | 204 | #print('global_params= %s', global_params) 205 | #print('blocks_args= %s', blocks_args) 206 | return blocks_args, global_params, input_shape 207 | -------------------------------------------------------------------------------- /efficientnet/preprocessing.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from skimage.transform import resize 3 | 4 | MEAN_RGB = [0.485 * 255, 0.456 * 255, 0.406 * 255] 5 | STDDEV_RGB = [0.229 * 255, 0.224 * 255, 0.225 * 255] 6 | 7 | MAP_INTERPOLATION_TO_ORDER = { 8 | 'nearest': 0, 9 | 'bilinear': 1, 10 | 'biquadratic': 2, 11 | 'bicubic': 3, 12 | } 13 | 14 | 15 | def center_crop_and_resize(image, image_size, crop_padding=32, interpolation='bicubic'): 16 | assert image.ndim in {2, 3} 17 | assert interpolation in MAP_INTERPOLATION_TO_ORDER.keys() 18 | 19 | h, w = image.shape[:2] 20 | 21 | padded_center_crop_size = int((image_size / (image_size + crop_padding)) * min(h, w)) 22 | offset_height = ((h - padded_center_crop_size) + 1) // 2 23 | offset_width = ((w - padded_center_crop_size) + 1) // 2 24 | 25 | image_crop = image[offset_height:padded_center_crop_size + offset_height, 26 | offset_width:padded_center_crop_size + offset_width] 27 | resized_image = resize( 28 | image_crop, 29 | (image_size, image_size), 30 | order=MAP_INTERPOLATION_TO_ORDER[interpolation], 31 | preserve_range=True, 32 | ) 33 | 34 | return resized_image 35 | 36 | 37 | def preprocess_input(x): 38 | assert x.ndim in (3, 4) 39 | assert x.shape[-1] == 3 40 | 41 | x = x - np.array(MEAN_RGB) 42 | x = x / np.array(STDDEV_RGB) 43 | 44 | return x 45 | -------------------------------------------------------------------------------- /examples/custom_initializer.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 14, 6 | "metadata": { 7 | "ExecuteTime": { 8 | "end_time": "2019-06-03T05:27:06.451163Z", 9 | "start_time": "2019-06-03T05:27:06.429226Z" 10 | } 11 | }, 12 | "outputs": [], 13 | "source": [ 14 | "# import tensorflow.keras.layers as KL\n", 15 | "# from tensorflow.keras.initializers import Initializer\n", 16 | "# import tensorflow.keras.backend as K\n", 17 | "# import tensorflow as tf\n", 18 | "# import numpy as np\n", 19 | "# import tensorflow.keras.models as KM\n", 20 | "\n", 21 | "# class ConvKernalInitializer(Initializer):\n", 22 | "# def __call__(self, shape, dtype=K.floatx(), partition_info=None):\n", 23 | "# \"\"\"Initialization for convolutional kernels.\n", 24 | "\n", 25 | "# The main difference with tf.variance_scaling_initializer is that\n", 26 | "# tf.variance_scaling_initializer uses a truncated normal with an uncorrected\n", 27 | "# standard deviation, whereas here we use a normal distribution. Similarly,\n", 28 | "# tf.contrib.layers.variance_scaling_initializer uses a truncated normal with\n", 29 | "# a corrected standard deviation.\n", 30 | "\n", 31 | "# Args:\n", 32 | "# shape: shape of variable\n", 33 | "# dtype: dtype of variable\n", 34 | "# partition_info: unused\n", 35 | "\n", 36 | "# Returns:\n", 37 | "# an initialization for the variable\n", 38 | "# \"\"\"\n", 39 | "# del partition_info\n", 40 | "# kernel_height, kernel_width, _, out_filters = shape\n", 41 | "# fan_out = int(kernel_height * kernel_width * out_filters)\n", 42 | "# return tf.random_normal(\n", 43 | "# shape, mean=0.0, stddev=np.sqrt(2.0 / fan_out), dtype=dtype)\n" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": 17, 49 | "metadata": { 50 | "ExecuteTime": { 51 | "end_time": "2019-06-03T05:27:33.372874Z", 52 | "start_time": "2019-06-03T05:27:33.342957Z" 53 | } 54 | }, 55 | "outputs": [], 56 | "source": [ 57 | "# x = KL.Input(shape=(32,32,3))\n", 58 | "# conv = KL.Conv2D(\n", 59 | "# 8,\n", 60 | "# kernel_size=[1, 1],\n", 61 | "# strides=[1, 1],\n", 62 | "# kernel_initializer=ConvKernalInitializer(),\n", 63 | "# padding='same',\n", 64 | "# use_bias=True\n", 65 | "# )\n", 66 | "# y = conv(x)\n", 67 | "\n", 68 | "# model = KM.Model(x, y)" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": 1, 74 | "metadata": { 75 | "ExecuteTime": { 76 | "end_time": "2019-06-03T05:32:43.201808Z", 77 | "start_time": "2019-06-03T05:32:43.191837Z" 78 | } 79 | }, 80 | "outputs": [], 81 | "source": [ 82 | "import os\n", 83 | "import sys\n", 84 | "sys.path.append('..')" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": 2, 90 | "metadata": { 91 | "ExecuteTime": { 92 | "end_time": "2019-06-03T05:32:43.220788Z", 93 | "start_time": "2019-06-03T05:32:43.205799Z" 94 | } 95 | }, 96 | "outputs": [], 97 | "source": [ 98 | "batch_size = 32\n", 99 | "\n", 100 | "width = 150\n", 101 | "height = 150\n", 102 | "input_shape = (height, width, 3)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": 3, 108 | "metadata": { 109 | "ExecuteTime": { 110 | "end_time": "2019-06-03T05:33:04.142265Z", 111 | "start_time": "2019-06-03T05:32:43.222752Z" 112 | } 113 | }, 114 | "outputs": [ 115 | { 116 | "name": "stdout", 117 | "output_type": "stream", 118 | "text": [ 119 | "WARNING:tensorflow:From c:\\users\\hasee\\appdata\\local\\programs\\python\\python35\\lib\\site-packages\\tensorflow\\python\\ops\\resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\n", 120 | "Instructions for updating:\n", 121 | "Colocations handled automatically by placer.\n", 122 | "WARNING:tensorflow:From c:\\users\\hasee\\appdata\\local\\programs\\python\\python35\\lib\\site-packages\\tensorflow\\python\\framework\\function.py:1007: calling Graph.create_op (from tensorflow.python.framework.ops) with compute_shapes is deprecated and will be removed in a future version.\n", 123 | "Instructions for updating:\n", 124 | "Shapes are always computed; don't use the compute_shapes as it has no effect.\n", 125 | "WARNING:tensorflow:From ..\\efficientnet\\layers.py:30: div (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n", 126 | "Instructions for updating:\n", 127 | "Deprecated in favor of operator or tf.math.divide.\n" 128 | ] 129 | } 130 | ], 131 | "source": [ 132 | "from tensorflow.python.keras.applications.imagenet_utils import decode_predictions\n", 133 | "\n", 134 | "from efficientnet import EfficientNetB0 as Net\n", 135 | "from efficientnet import center_crop_and_resize, preprocess_input\n", 136 | "model = Net(weights=None, include_top=False, input_shape=(336, 336, 3))\n", 137 | "fname = \"I:/Users/hasee/.keras/models/efficientnet-b0_imagenet_1000_notop.h5\"\n", 138 | "model.load_weights(fname)\n", 139 | "model.save(\"../models/conv_base_336_b0.h5\", include_optimizer=False)" 140 | ] 141 | }, 142 | { 143 | "cell_type": "markdown", 144 | "metadata": {}, 145 | "source": [ 146 | "## Load" 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": 1, 152 | "metadata": { 153 | "ExecuteTime": { 154 | "end_time": "2019-06-03T05:33:19.972872Z", 155 | "start_time": "2019-06-03T05:33:16.028327Z" 156 | } 157 | }, 158 | "outputs": [], 159 | "source": [ 160 | "import sys\n", 161 | "sys.path.append('..')\n", 162 | "\n", 163 | "from efficientnet.layers import Swish, DropConnect\n", 164 | "from efficientnet.model import ConvKernalInitializer\n", 165 | "from tensorflow.keras.utils import get_custom_objects\n", 166 | "\n", 167 | "get_custom_objects().update({\n", 168 | " 'ConvKernalInitializer': ConvKernalInitializer,\n", 169 | " 'Swish': Swish,\n", 170 | " 'DropConnect':DropConnect\n", 171 | "})" 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": 2, 177 | "metadata": { 178 | "ExecuteTime": { 179 | "end_time": "2019-06-03T05:33:27.171082Z", 180 | "start_time": "2019-06-03T05:33:19.975769Z" 181 | } 182 | }, 183 | "outputs": [ 184 | { 185 | "name": "stdout", 186 | "output_type": "stream", 187 | "text": [ 188 | "WARNING:tensorflow:From c:\\users\\hasee\\appdata\\local\\programs\\python\\python35\\lib\\site-packages\\tensorflow\\python\\ops\\resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\n", 189 | "Instructions for updating:\n", 190 | "Colocations handled automatically by placer.\n", 191 | "WARNING:tensorflow:From c:\\users\\hasee\\appdata\\local\\programs\\python\\python35\\lib\\site-packages\\tensorflow\\python\\framework\\function.py:1007: calling Graph.create_op (from tensorflow.python.framework.ops) with compute_shapes is deprecated and will be removed in a future version.\n", 192 | "Instructions for updating:\n", 193 | "Shapes are always computed; don't use the compute_shapes as it has no effect.\n", 194 | "WARNING:tensorflow:From ..\\efficientnet\\layers.py:30: div (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n", 195 | "Instructions for updating:\n", 196 | "Deprecated in favor of operator or tf.math.divide.\n", 197 | "WARNING:tensorflow:No training configuration found in save file: the model was *not* compiled. Compile it manually.\n" 198 | ] 199 | } 200 | ], 201 | "source": [ 202 | "from tensorflow.keras.models import load_model\n", 203 | "model = load_model(\"../models/conv_base_336_b0.h5\")" 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": 4, 209 | "metadata": { 210 | "ExecuteTime": { 211 | "end_time": "2019-06-03T05:57:27.456684Z", 212 | "start_time": "2019-06-03T05:57:27.439730Z" 213 | } 214 | }, 215 | "outputs": [ 216 | { 217 | "data": { 218 | "text/plain": [ 219 | "'efficientnet'" 220 | ] 221 | }, 222 | "execution_count": 4, 223 | "metadata": {}, 224 | "output_type": "execute_result" 225 | } 226 | ], 227 | "source": [ 228 | "os.path.split(file)[-1]" 229 | ] 230 | } 231 | ], 232 | "metadata": { 233 | "kernelspec": { 234 | "display_name": "Python 3", 235 | "language": "python", 236 | "name": "python3" 237 | }, 238 | "language_info": { 239 | "codemirror_mode": { 240 | "name": "ipython", 241 | "version": 3 242 | }, 243 | "file_extension": ".py", 244 | "mimetype": "text/x-python", 245 | "name": "python", 246 | "nbconvert_exporter": "python", 247 | "pygments_lexer": "ipython3", 248 | "version": "3.5.2" 249 | }, 250 | "toc": { 251 | "base_numbering": 1, 252 | "nav_menu": {}, 253 | "number_sections": true, 254 | "sideBar": true, 255 | "skip_h1_title": false, 256 | "title_cell": "Table of Contents", 257 | "title_sidebar": "Contents", 258 | "toc_cell": false, 259 | "toc_position": {}, 260 | "toc_section_display": true, 261 | "toc_window_display": false 262 | } 263 | }, 264 | "nbformat": 4, 265 | "nbformat_minor": 2 266 | } 267 | -------------------------------------------------------------------------------- /misc/labels_map.txt: -------------------------------------------------------------------------------- 1 | {"0": "tench, Tinca tinca", "1": "goldfish, Carassius auratus", "2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias", "3": "tiger shark, Galeocerdo cuvieri", "4": "hammerhead, hammerhead shark", "5": "electric ray, crampfish, numbfish, torpedo", "6": "stingray", "7": "cock", "8": "hen", "9": "ostrich, Struthio camelus", "10": "brambling, Fringilla montifringilla", "11": "goldfinch, Carduelis carduelis", "12": "house finch, linnet, Carpodacus mexicanus", "13": "junco, snowbird", "14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea", "15": "robin, American robin, Turdus migratorius", "16": "bulbul", "17": "jay", "18": "magpie", "19": "chickadee", "20": "water ouzel, dipper", "21": "kite", "22": "bald eagle, American eagle, Haliaeetus leucocephalus", "23": "vulture", "24": "great grey owl, great gray owl, Strix nebulosa", "25": "European fire salamander, Salamandra salamandra", "26": "common newt, Triturus vulgaris", "27": "eft", "28": "spotted salamander, Ambystoma maculatum", "29": "axolotl, mud puppy, Ambystoma mexicanum", "30": "bullfrog, Rana catesbeiana", "31": "tree frog, tree-frog", "32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui", "33": "loggerhead, loggerhead turtle, Caretta caretta", "34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea", "35": "mud turtle", "36": "terrapin", "37": "box turtle, box tortoise", "38": "banded gecko", "39": "common iguana, iguana, Iguana iguana", "40": "American chameleon, anole, Anolis carolinensis", "41": "whiptail, whiptail lizard", "42": "agama", "43": "frilled lizard, Chlamydosaurus kingi", "44": "alligator lizard", "45": "Gila monster, Heloderma suspectum", "46": "green lizard, Lacerta viridis", "47": "African chameleon, Chamaeleo chamaeleon", "48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis", "49": "African crocodile, Nile crocodile, Crocodylus niloticus", "50": "American alligator, Alligator mississipiensis", "51": "triceratops", "52": "thunder snake, worm snake, Carphophis amoenus", "53": "ringneck snake, ring-necked snake, ring snake", "54": "hognose snake, puff adder, sand viper", "55": "green snake, grass snake", "56": "king snake, kingsnake", "57": "garter snake, grass snake", "58": "water snake", "59": "vine snake", "60": "night snake, Hypsiglena torquata", "61": "boa constrictor, Constrictor constrictor", "62": "rock python, rock snake, Python sebae", "63": "Indian cobra, Naja naja", "64": "green mamba", "65": "sea snake", "66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus", "67": "diamondback, diamondback rattlesnake, Crotalus adamanteus", "68": "sidewinder, horned rattlesnake, Crotalus cerastes", "69": "trilobite", "70": "harvestman, daddy longlegs, Phalangium opilio", "71": "scorpion", "72": "black and gold garden spider, Argiope aurantia", "73": "barn spider, Araneus cavaticus", "74": "garden spider, Aranea diademata", "75": "black widow, Latrodectus mactans", "76": "tarantula", "77": "wolf spider, hunting spider", "78": "tick", "79": "centipede", "80": "black grouse", "81": "ptarmigan", "82": "ruffed grouse, partridge, Bonasa umbellus", "83": "prairie chicken, prairie grouse, prairie fowl", "84": "peacock", "85": "quail", "86": "partridge", "87": "African grey, African gray, Psittacus erithacus", "88": "macaw", "89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita", "90": "lorikeet", "91": "coucal", "92": "bee eater", "93": "hornbill", "94": "hummingbird", "95": "jacamar", "96": "toucan", "97": "drake", "98": "red-breasted merganser, Mergus serrator", "99": "goose", "100": "black swan, Cygnus atratus", "101": "tusker", "102": "echidna, spiny anteater, anteater", "103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus", "104": "wallaby, brush kangaroo", "105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus", "106": "wombat", "107": "jellyfish", "108": "sea anemone, anemone", "109": "brain coral", "110": "flatworm, platyhelminth", "111": "nematode, nematode worm, roundworm", "112": "conch", "113": "snail", "114": "slug", "115": "sea slug, nudibranch", "116": "chiton, coat-of-mail shell, sea cradle, polyplacophore", "117": "chambered nautilus, pearly nautilus, nautilus", "118": "Dungeness crab, Cancer magister", "119": "rock crab, Cancer irroratus", "120": "fiddler crab", "121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica", "122": "American lobster, Northern lobster, Maine lobster, Homarus americanus", "123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish", "124": "crayfish, crawfish, crawdad, crawdaddy", "125": "hermit crab", "126": "isopod", "127": "white stork, Ciconia ciconia", "128": "black stork, Ciconia nigra", "129": "spoonbill", "130": "flamingo", "131": "little blue heron, Egretta caerulea", "132": "American egret, great white heron, Egretta albus", "133": "bittern", "134": "crane", "135": "limpkin, Aramus pictus", "136": "European gallinule, Porphyrio porphyrio", "137": "American coot, marsh hen, mud hen, water hen, Fulica americana", "138": "bustard", "139": "ruddy turnstone, Arenaria interpres", "140": "red-backed sandpiper, dunlin, Erolia alpina", "141": "redshank, Tringa totanus", "142": "dowitcher", "143": "oystercatcher, oyster catcher", "144": "pelican", "145": "king penguin, Aptenodytes patagonica", "146": "albatross, mollymawk", "147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus", "148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca", "149": "dugong, Dugong dugon", "150": "sea lion", "151": "Chihuahua", "152": "Japanese spaniel", "153": "Maltese dog, Maltese terrier, Maltese", "154": "Pekinese, Pekingese, Peke", "155": "Shih-Tzu", "156": "Blenheim spaniel", "157": "papillon", "158": "toy terrier", "159": "Rhodesian ridgeback", "160": "Afghan hound, Afghan", "161": "basset, basset hound", "162": "beagle", "163": "bloodhound, sleuthhound", "164": "bluetick", "165": "black-and-tan coonhound", "166": "Walker hound, Walker foxhound", "167": "English foxhound", "168": "redbone", "169": "borzoi, Russian wolfhound", "170": "Irish wolfhound", "171": "Italian greyhound", "172": "whippet", "173": "Ibizan hound, Ibizan Podenco", "174": "Norwegian elkhound, elkhound", "175": "otterhound, otter hound", "176": "Saluki, gazelle hound", "177": "Scottish deerhound, deerhound", "178": "Weimaraner", "179": "Staffordshire bullterrier, Staffordshire bull terrier", "180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier", "181": "Bedlington terrier", "182": "Border terrier", "183": "Kerry blue terrier", "184": "Irish terrier", "185": "Norfolk terrier", "186": "Norwich terrier", "187": "Yorkshire terrier", "188": "wire-haired fox terrier", "189": "Lakeland terrier", "190": "Sealyham terrier, Sealyham", "191": "Airedale, Airedale terrier", "192": "cairn, cairn terrier", "193": "Australian terrier", "194": "Dandie Dinmont, Dandie Dinmont terrier", "195": "Boston bull, Boston terrier", "196": "miniature schnauzer", "197": "giant schnauzer", "198": "standard schnauzer", "199": "Scotch terrier, Scottish terrier, Scottie", "200": "Tibetan terrier, chrysanthemum dog", "201": "silky terrier, Sydney silky", "202": "soft-coated wheaten terrier", "203": "West Highland white terrier", "204": "Lhasa, Lhasa apso", "205": "flat-coated retriever", "206": "curly-coated retriever", "207": "golden retriever", "208": "Labrador retriever", "209": "Chesapeake Bay retriever", "210": "German short-haired pointer", "211": "vizsla, Hungarian pointer", "212": "English setter", "213": "Irish setter, red setter", "214": "Gordon setter", "215": "Brittany spaniel", "216": "clumber, clumber spaniel", "217": "English springer, English springer spaniel", "218": "Welsh springer spaniel", "219": "cocker spaniel, English cocker spaniel, cocker", "220": "Sussex spaniel", "221": "Irish water spaniel", "222": "kuvasz", "223": "schipperke", "224": "groenendael", "225": "malinois", "226": "briard", "227": "kelpie", "228": "komondor", "229": "Old English sheepdog, bobtail", "230": "Shetland sheepdog, Shetland sheep dog, Shetland", "231": "collie", "232": "Border collie", "233": "Bouvier des Flandres, Bouviers des Flandres", "234": "Rottweiler", "235": "German shepherd, German shepherd dog, German police dog, alsatian", "236": "Doberman, Doberman pinscher", "237": "miniature pinscher", "238": "Greater Swiss Mountain dog", "239": "Bernese mountain dog", "240": "Appenzeller", "241": "EntleBucher", "242": "boxer", "243": "bull mastiff", "244": "Tibetan mastiff", "245": "French bulldog", "246": "Great Dane", "247": "Saint Bernard, St Bernard", "248": "Eskimo dog, husky", "249": "malamute, malemute, Alaskan malamute", "250": "Siberian husky", "251": "dalmatian, coach dog, carriage dog", "252": "affenpinscher, monkey pinscher, monkey dog", "253": "basenji", "254": "pug, pug-dog", "255": "Leonberg", "256": "Newfoundland, Newfoundland dog", "257": "Great Pyrenees", "258": "Samoyed, Samoyede", "259": "Pomeranian", "260": "chow, chow chow", "261": "keeshond", "262": "Brabancon griffon", "263": "Pembroke, Pembroke Welsh corgi", "264": "Cardigan, Cardigan Welsh corgi", "265": "toy poodle", "266": "miniature poodle", "267": "standard poodle", "268": "Mexican hairless", "269": "timber wolf, grey wolf, gray wolf, Canis lupus", "270": "white wolf, Arctic wolf, Canis lupus tundrarum", "271": "red wolf, maned wolf, Canis rufus, Canis niger", "272": "coyote, prairie wolf, brush wolf, Canis latrans", "273": "dingo, warrigal, warragal, Canis dingo", "274": "dhole, Cuon alpinus", "275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus", "276": "hyena, hyaena", "277": "red fox, Vulpes vulpes", "278": "kit fox, Vulpes macrotis", "279": "Arctic fox, white fox, Alopex lagopus", "280": "grey fox, gray fox, Urocyon cinereoargenteus", "281": "tabby, tabby cat", "282": "tiger cat", "283": "Persian cat", "284": "Siamese cat, Siamese", "285": "Egyptian cat", "286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor", "287": "lynx, catamount", "288": "leopard, Panthera pardus", "289": "snow leopard, ounce, Panthera uncia", "290": "jaguar, panther, Panthera onca, Felis onca", "291": "lion, king of beasts, Panthera leo", "292": "tiger, Panthera tigris", "293": "cheetah, chetah, Acinonyx jubatus", "294": "brown bear, bruin, Ursus arctos", "295": "American black bear, black bear, Ursus americanus, Euarctos americanus", "296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus", "297": "sloth bear, Melursus ursinus, Ursus ursinus", "298": "mongoose", "299": "meerkat, mierkat", "300": "tiger beetle", "301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle", "302": "ground beetle, carabid beetle", "303": "long-horned beetle, longicorn, longicorn beetle", "304": "leaf beetle, chrysomelid", "305": "dung beetle", "306": "rhinoceros beetle", "307": "weevil", "308": "fly", "309": "bee", "310": "ant, emmet, pismire", "311": "grasshopper, hopper", "312": "cricket", "313": "walking stick, walkingstick, stick insect", "314": "cockroach, roach", "315": "mantis, mantid", "316": "cicada, cicala", "317": "leafhopper", "318": "lacewing, lacewing fly", "319": "dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk", "320": "damselfly", "321": "admiral", "322": "ringlet, ringlet butterfly", "323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus", "324": "cabbage butterfly", "325": "sulphur butterfly, sulfur butterfly", "326": "lycaenid, lycaenid butterfly", "327": "starfish, sea star", "328": "sea urchin", "329": "sea cucumber, holothurian", "330": "wood rabbit, cottontail, cottontail rabbit", "331": "hare", "332": "Angora, Angora rabbit", "333": "hamster", "334": "porcupine, hedgehog", "335": "fox squirrel, eastern fox squirrel, Sciurus niger", "336": "marmot", "337": "beaver", "338": "guinea pig, Cavia cobaya", "339": "sorrel", "340": "zebra", "341": "hog, pig, grunter, squealer, Sus scrofa", "342": "wild boar, boar, Sus scrofa", "343": "warthog", "344": "hippopotamus, hippo, river horse, Hippopotamus amphibius", "345": "ox", "346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis", "347": "bison", "348": "ram, tup", "349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis", "350": "ibex, Capra ibex", "351": "hartebeest", "352": "impala, Aepyceros melampus", "353": "gazelle", "354": "Arabian camel, dromedary, Camelus dromedarius", "355": "llama", "356": "weasel", "357": "mink", "358": "polecat, fitch, foulmart, foumart, Mustela putorius", "359": "black-footed ferret, ferret, Mustela nigripes", "360": "otter", "361": "skunk, polecat, wood pussy", "362": "badger", "363": "armadillo", "364": "three-toed sloth, ai, Bradypus tridactylus", "365": "orangutan, orang, orangutang, Pongo pygmaeus", "366": "gorilla, Gorilla gorilla", "367": "chimpanzee, chimp, Pan troglodytes", "368": "gibbon, Hylobates lar", "369": "siamang, Hylobates syndactylus, Symphalangus syndactylus", "370": "guenon, guenon monkey", "371": "patas, hussar monkey, Erythrocebus patas", "372": "baboon", "373": "macaque", "374": "langur", "375": "colobus, colobus monkey", "376": "proboscis monkey, Nasalis larvatus", "377": "marmoset", "378": "capuchin, ringtail, Cebus capucinus", "379": "howler monkey, howler", "380": "titi, titi monkey", "381": "spider monkey, Ateles geoffroyi", "382": "squirrel monkey, Saimiri sciureus", "383": "Madagascar cat, ring-tailed lemur, Lemur catta", "384": "indri, indris, Indri indri, Indri brevicaudatus", "385": "Indian elephant, Elephas maximus", "386": "African elephant, Loxodonta africana", "387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens", "388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca", "389": "barracouta, snoek", "390": "eel", "391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch", "392": "rock beauty, Holocanthus tricolor", "393": "anemone fish", "394": "sturgeon", "395": "gar, garfish, garpike, billfish, Lepisosteus osseus", "396": "lionfish", "397": "puffer, pufferfish, blowfish, globefish", "398": "abacus", "399": "abaya", "400": "academic gown, academic robe, judge's robe", "401": "accordion, piano accordion, squeeze box", "402": "acoustic guitar", "403": "aircraft carrier, carrier, flattop, attack aircraft carrier", "404": "airliner", "405": "airship, dirigible", "406": "altar", "407": "ambulance", "408": "amphibian, amphibious vehicle", "409": "analog clock", "410": "apiary, bee house", "411": "apron", "412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin", "413": "assault rifle, assault gun", "414": "backpack, back pack, knapsack, packsack, rucksack, haversack", "415": "bakery, bakeshop, bakehouse", "416": "balance beam, beam", "417": "balloon", "418": "ballpoint, ballpoint pen, ballpen, Biro", "419": "Band Aid", "420": "banjo", "421": "bannister, banister, balustrade, balusters, handrail", "422": "barbell", "423": "barber chair", "424": "barbershop", "425": "barn", "426": "barometer", "427": "barrel, cask", "428": "barrow, garden cart, lawn cart, wheelbarrow", "429": "baseball", "430": "basketball", "431": "bassinet", "432": "bassoon", "433": "bathing cap, swimming cap", "434": "bath towel", "435": "bathtub, bathing tub, bath, tub", "436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon", "437": "beacon, lighthouse, beacon light, pharos", "438": "beaker", "439": "bearskin, busby, shako", "440": "beer bottle", "441": "beer glass", "442": "bell cote, bell cot", "443": "bib", "444": "bicycle-built-for-two, tandem bicycle, tandem", "445": "bikini, two-piece", "446": "binder, ring-binder", "447": "binoculars, field glasses, opera glasses", "448": "birdhouse", "449": "boathouse", "450": "bobsled, bobsleigh, bob", "451": "bolo tie, bolo, bola tie, bola", "452": "bonnet, poke bonnet", "453": "bookcase", "454": "bookshop, bookstore, bookstall", "455": "bottlecap", "456": "bow", "457": "bow tie, bow-tie, bowtie", "458": "brass, memorial tablet, plaque", "459": "brassiere, bra, bandeau", "460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty", "461": "breastplate, aegis, egis", "462": "broom", "463": "bucket, pail", "464": "buckle", "465": "bulletproof vest", "466": "bullet train, bullet", "467": "butcher shop, meat market", "468": "cab, hack, taxi, taxicab", "469": "caldron, cauldron", "470": "candle, taper, wax light", "471": "cannon", "472": "canoe", "473": "can opener, tin opener", "474": "cardigan", "475": "car mirror", "476": "carousel, carrousel, merry-go-round, roundabout, whirligig", "477": "carpenter's kit, tool kit", "478": "carton", "479": "car wheel", "480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM", "481": "cassette", "482": "cassette player", "483": "castle", "484": "catamaran", "485": "CD player", "486": "cello, violoncello", "487": "cellular telephone, cellular phone, cellphone, cell, mobile phone", "488": "chain", "489": "chainlink fence", "490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour", "491": "chain saw, chainsaw", "492": "chest", "493": "chiffonier, commode", "494": "chime, bell, gong", "495": "china cabinet, china closet", "496": "Christmas stocking", "497": "church, church building", "498": "cinema, movie theater, movie theatre, movie house, picture palace", "499": "cleaver, meat cleaver, chopper", "500": "cliff dwelling", "501": "cloak", "502": "clog, geta, patten, sabot", "503": "cocktail shaker", "504": "coffee mug", "505": "coffeepot", "506": "coil, spiral, volute, whorl, helix", "507": "combination lock", "508": "computer keyboard, keypad", "509": "confectionery, confectionary, candy store", "510": "container ship, containership, container vessel", "511": "convertible", "512": "corkscrew, bottle screw", "513": "cornet, horn, trumpet, trump", "514": "cowboy boot", "515": "cowboy hat, ten-gallon hat", "516": "cradle", "517": "crane", "518": "crash helmet", "519": "crate", "520": "crib, cot", "521": "Crock Pot", "522": "croquet ball", "523": "crutch", "524": "cuirass", "525": "dam, dike, dyke", "526": "desk", "527": "desktop computer", "528": "dial telephone, dial phone", "529": "diaper, nappy, napkin", "530": "digital clock", "531": "digital watch", "532": "dining table, board", "533": "dishrag, dishcloth", "534": "dishwasher, dish washer, dishwashing machine", "535": "disk brake, disc brake", "536": "dock, dockage, docking facility", "537": "dogsled, dog sled, dog sleigh", "538": "dome", "539": "doormat, welcome mat", "540": "drilling platform, offshore rig", "541": "drum, membranophone, tympan", "542": "drumstick", "543": "dumbbell", "544": "Dutch oven", "545": "electric fan, blower", "546": "electric guitar", "547": "electric locomotive", "548": "entertainment center", "549": "envelope", "550": "espresso maker", "551": "face powder", "552": "feather boa, boa", "553": "file, file cabinet, filing cabinet", "554": "fireboat", "555": "fire engine, fire truck", "556": "fire screen, fireguard", "557": "flagpole, flagstaff", "558": "flute, transverse flute", "559": "folding chair", "560": "football helmet", "561": "forklift", "562": "fountain", "563": "fountain pen", "564": "four-poster", "565": "freight car", "566": "French horn, horn", "567": "frying pan, frypan, skillet", "568": "fur coat", "569": "garbage truck, dustcart", "570": "gasmask, respirator, gas helmet", "571": "gas pump, gasoline pump, petrol pump, island dispenser", "572": "goblet", "573": "go-kart", "574": "golf ball", "575": "golfcart, golf cart", "576": "gondola", "577": "gong, tam-tam", "578": "gown", "579": "grand piano, grand", "580": "greenhouse, nursery, glasshouse", "581": "grille, radiator grille", "582": "grocery store, grocery, food market, market", "583": "guillotine", "584": "hair slide", "585": "hair spray", "586": "half track", "587": "hammer", "588": "hamper", "589": "hand blower, blow dryer, blow drier, hair dryer, hair drier", "590": "hand-held computer, hand-held microcomputer", "591": "handkerchief, hankie, hanky, hankey", "592": "hard disc, hard disk, fixed disk", "593": "harmonica, mouth organ, harp, mouth harp", "594": "harp", "595": "harvester, reaper", "596": "hatchet", "597": "holster", "598": "home theater, home theatre", "599": "honeycomb", "600": "hook, claw", "601": "hoopskirt, crinoline", "602": "horizontal bar, high bar", "603": "horse cart, horse-cart", "604": "hourglass", "605": "iPod", "606": "iron, smoothing iron", "607": "jack-o'-lantern", "608": "jean, blue jean, denim", "609": "jeep, landrover", "610": "jersey, T-shirt, tee shirt", "611": "jigsaw puzzle", "612": "jinrikisha, ricksha, rickshaw", "613": "joystick", "614": "kimono", "615": "knee pad", "616": "knot", "617": "lab coat, laboratory coat", "618": "ladle", "619": "lampshade, lamp shade", "620": "laptop, laptop computer", "621": "lawn mower, mower", "622": "lens cap, lens cover", "623": "letter opener, paper knife, paperknife", "624": "library", "625": "lifeboat", "626": "lighter, light, igniter, ignitor", "627": "limousine, limo", "628": "liner, ocean liner", "629": "lipstick, lip rouge", "630": "Loafer", "631": "lotion", "632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system", "633": "loupe, jeweler's loupe", "634": "lumbermill, sawmill", "635": "magnetic compass", "636": "mailbag, postbag", "637": "mailbox, letter box", "638": "maillot", "639": "maillot, tank suit", "640": "manhole cover", "641": "maraca", "642": "marimba, xylophone", "643": "mask", "644": "matchstick", "645": "maypole", "646": "maze, labyrinth", "647": "measuring cup", "648": "medicine chest, medicine cabinet", "649": "megalith, megalithic structure", "650": "microphone, mike", "651": "microwave, microwave oven", "652": "military uniform", "653": "milk can", "654": "minibus", "655": "miniskirt, mini", "656": "minivan", "657": "missile", "658": "mitten", "659": "mixing bowl", "660": "mobile home, manufactured home", "661": "Model T", "662": "modem", "663": "monastery", "664": "monitor", "665": "moped", "666": "mortar", "667": "mortarboard", "668": "mosque", "669": "mosquito net", "670": "motor scooter, scooter", "671": "mountain bike, all-terrain bike, off-roader", "672": "mountain tent", "673": "mouse, computer mouse", "674": "mousetrap", "675": "moving van", "676": "muzzle", "677": "nail", "678": "neck brace", "679": "necklace", "680": "nipple", "681": "notebook, notebook computer", "682": "obelisk", "683": "oboe, hautboy, hautbois", "684": "ocarina, sweet potato", "685": "odometer, hodometer, mileometer, milometer", "686": "oil filter", "687": "organ, pipe organ", "688": "oscilloscope, scope, cathode-ray oscilloscope, CRO", "689": "overskirt", "690": "oxcart", "691": "oxygen mask", "692": "packet", "693": "paddle, boat paddle", "694": "paddlewheel, paddle wheel", "695": "padlock", "696": "paintbrush", "697": "pajama, pyjama, pj's, jammies", "698": "palace", "699": "panpipe, pandean pipe, syrinx", "700": "paper towel", "701": "parachute, chute", "702": "parallel bars, bars", "703": "park bench", "704": "parking meter", "705": "passenger car, coach, carriage", "706": "patio, terrace", "707": "pay-phone, pay-station", "708": "pedestal, plinth, footstall", "709": "pencil box, pencil case", "710": "pencil sharpener", "711": "perfume, essence", "712": "Petri dish", "713": "photocopier", "714": "pick, plectrum, plectron", "715": "pickelhaube", "716": "picket fence, paling", "717": "pickup, pickup truck", "718": "pier", "719": "piggy bank, penny bank", "720": "pill bottle", "721": "pillow", "722": "ping-pong ball", "723": "pinwheel", "724": "pirate, pirate ship", "725": "pitcher, ewer", "726": "plane, carpenter's plane, woodworking plane", "727": "planetarium", "728": "plastic bag", "729": "plate rack", "730": "plow, plough", "731": "plunger, plumber's helper", "732": "Polaroid camera, Polaroid Land camera", "733": "pole", "734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria", "735": "poncho", "736": "pool table, billiard table, snooker table", "737": "pop bottle, soda bottle", "738": "pot, flowerpot", "739": "potter's wheel", "740": "power drill", "741": "prayer rug, prayer mat", "742": "printer", "743": "prison, prison house", "744": "projectile, missile", "745": "projector", "746": "puck, hockey puck", "747": "punching bag, punch bag, punching ball, punchball", "748": "purse", "749": "quill, quill pen", "750": "quilt, comforter, comfort, puff", "751": "racer, race car, racing car", "752": "racket, racquet", "753": "radiator", "754": "radio, wireless", "755": "radio telescope, radio reflector", "756": "rain barrel", "757": "recreational vehicle, RV, R.V.", "758": "reel", "759": "reflex camera", "760": "refrigerator, icebox", "761": "remote control, remote", "762": "restaurant, eating house, eating place, eatery", "763": "revolver, six-gun, six-shooter", "764": "rifle", "765": "rocking chair, rocker", "766": "rotisserie", "767": "rubber eraser, rubber, pencil eraser", "768": "rugby ball", "769": "rule, ruler", "770": "running shoe", "771": "safe", "772": "safety pin", "773": "saltshaker, salt shaker", "774": "sandal", "775": "sarong", "776": "sax, saxophone", "777": "scabbard", "778": "scale, weighing machine", "779": "school bus", "780": "schooner", "781": "scoreboard", "782": "screen, CRT screen", "783": "screw", "784": "screwdriver", "785": "seat belt, seatbelt", "786": "sewing machine", "787": "shield, buckler", "788": "shoe shop, shoe-shop, shoe store", "789": "shoji", "790": "shopping basket", "791": "shopping cart", "792": "shovel", "793": "shower cap", "794": "shower curtain", "795": "ski", "796": "ski mask", "797": "sleeping bag", "798": "slide rule, slipstick", "799": "sliding door", "800": "slot, one-armed bandit", "801": "snorkel", "802": "snowmobile", "803": "snowplow, snowplough", "804": "soap dispenser", "805": "soccer ball", "806": "sock", "807": "solar dish, solar collector, solar furnace", "808": "sombrero", "809": "soup bowl", "810": "space bar", "811": "space heater", "812": "space shuttle", "813": "spatula", "814": "speedboat", "815": "spider web, spider's web", "816": "spindle", "817": "sports car, sport car", "818": "spotlight, spot", "819": "stage", "820": "steam locomotive", "821": "steel arch bridge", "822": "steel drum", "823": "stethoscope", "824": "stole", "825": "stone wall", "826": "stopwatch, stop watch", "827": "stove", "828": "strainer", "829": "streetcar, tram, tramcar, trolley, trolley car", "830": "stretcher", "831": "studio couch, day bed", "832": "stupa, tope", "833": "submarine, pigboat, sub, U-boat", "834": "suit, suit of clothes", "835": "sundial", "836": "sunglass", "837": "sunglasses, dark glasses, shades", "838": "sunscreen, sunblock, sun blocker", "839": "suspension bridge", "840": "swab, swob, mop", "841": "sweatshirt", "842": "swimming trunks, bathing trunks", "843": "swing", "844": "switch, electric switch, electrical switch", "845": "syringe", "846": "table lamp", "847": "tank, army tank, armored combat vehicle, armoured combat vehicle", "848": "tape player", "849": "teapot", "850": "teddy, teddy bear", "851": "television, television system", "852": "tennis ball", "853": "thatch, thatched roof", "854": "theater curtain, theatre curtain", "855": "thimble", "856": "thresher, thrasher, threshing machine", "857": "throne", "858": "tile roof", "859": "toaster", "860": "tobacco shop, tobacconist shop, tobacconist", "861": "toilet seat", "862": "torch", "863": "totem pole", "864": "tow truck, tow car, wrecker", "865": "toyshop", "866": "tractor", "867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi", "868": "tray", "869": "trench coat", "870": "tricycle, trike, velocipede", "871": "trimaran", "872": "tripod", "873": "triumphal arch", "874": "trolleybus, trolley coach, trackless trolley", "875": "trombone", "876": "tub, vat", "877": "turnstile", "878": "typewriter keyboard", "879": "umbrella", "880": "unicycle, monocycle", "881": "upright, upright piano", "882": "vacuum, vacuum cleaner", "883": "vase", "884": "vault", "885": "velvet", "886": "vending machine", "887": "vestment", "888": "viaduct", "889": "violin, fiddle", "890": "volleyball", "891": "waffle iron", "892": "wall clock", "893": "wallet, billfold, notecase, pocketbook", "894": "wardrobe, closet, press", "895": "warplane, military plane", "896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin", "897": "washer, automatic washer, washing machine", "898": "water bottle", "899": "water jug", "900": "water tower", "901": "whiskey jug", "902": "whistle", "903": "wig", "904": "window screen", "905": "window shade", "906": "Windsor tie", "907": "wine bottle", "908": "wing", "909": "wok", "910": "wooden spoon", "911": "wool, woolen, woollen", "912": "worm fence, snake fence, snake-rail fence, Virginia fence", "913": "wreck", "914": "yawl", "915": "yurt", "916": "web site, website, internet site, site", "917": "comic book", "918": "crossword puzzle, crossword", "919": "street sign", "920": "traffic light, traffic signal, stoplight", "921": "book jacket, dust cover, dust jacket, dust wrapper", "922": "menu", "923": "plate", "924": "guacamole", "925": "consomme", "926": "hot pot, hotpot", "927": "trifle", "928": "ice cream, icecream", "929": "ice lolly, lolly, lollipop, popsicle", "930": "French loaf", "931": "bagel, beigel", "932": "pretzel", "933": "cheeseburger", "934": "hotdog, hot dog, red hot", "935": "mashed potato", "936": "head cabbage", "937": "broccoli", "938": "cauliflower", "939": "zucchini, courgette", "940": "spaghetti squash", "941": "acorn squash", "942": "butternut squash", "943": "cucumber, cuke", "944": "artichoke, globe artichoke", "945": "bell pepper", "946": "cardoon", "947": "mushroom", "948": "Granny Smith", "949": "strawberry", "950": "orange", "951": "lemon", "952": "fig", "953": "pineapple, ananas", "954": "banana", "955": "jackfruit, jak, jack", "956": "custard apple", "957": "pomegranate", "958": "hay", "959": "carbonara", "960": "chocolate sauce, chocolate syrup", "961": "dough", "962": "meat loaf, meatloaf", "963": "pizza, pizza pie", "964": "potpie", "965": "burrito", "966": "red wine", "967": "espresso", "968": "cup", "969": "eggnog", "970": "alp", "971": "bubble", "972": "cliff, drop, drop-off", "973": "coral reef", "974": "geyser", "975": "lakeside, lakeshore", "976": "promontory, headland, head, foreland", "977": "sandbar, sand bar", "978": "seashore, coast, seacoast, sea-coast", "979": "valley, vale", "980": "volcano", "981": "ballplayer, baseball player", "982": "groom, bridegroom", "983": "scuba diver", "984": "rapeseed", "985": "daisy", "986": "yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum", "987": "corn", "988": "acorn", "989": "hip, rose hip, rosehip", "990": "buckeye, horse chestnut, conker", "991": "coral fungus", "992": "agaric", "993": "gyromitra", "994": "stinkhorn, carrion fungus", "995": "earthstar", "996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa", "997": "bolete", "998": "ear, spike, capitulum", "999": "toilet tissue, toilet paper, bathroom tissue"} -------------------------------------------------------------------------------- /misc/panda.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tony607/efficientnet_keras_transfer_learning/11e10560c23688990f81702e81cf527f8ce5ab35/misc/panda.jpg -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Note: To use the 'upload' functionality of this file, you must: 5 | # $ pip install twine 6 | 7 | import io 8 | import os 9 | import sys 10 | from shutil import rmtree 11 | 12 | from setuptools import find_packages, setup, Command 13 | 14 | # Package meta-data. 15 | NAME = 'efficientnet' 16 | DESCRIPTION = 'EfficientNet model re-implementation. Keras.' 17 | URL = 'https://github.com/qubvel/efficientnet' 18 | EMAIL = 'qubvel@gmail.com' 19 | AUTHOR = 'Pavel Yakubovskiy' 20 | REQUIRES_PYTHON = '>=3.0.0' 21 | VERSION = None 22 | 23 | # The rest you shouldn't have to touch too much :) 24 | # ------------------------------------------------ 25 | # Except, perhaps the License and Trove Classifiers! 26 | # If you do change the License, remember to change the Trove Classifier for that! 27 | 28 | here = os.path.abspath(os.path.dirname(__file__)) 29 | 30 | # What packages are required for this module to be executed? 31 | try: 32 | with open(os.path.join(here, 'requirements.txt'), encoding='utf-8') as f: 33 | REQUIRED = f.read().split('\n') 34 | except: 35 | REQUIRED = [] 36 | 37 | # What packages are optional? 38 | EXTRAS = { 39 | 'test': ['pytest'] 40 | } 41 | 42 | # Import the README and use it as the long-description. 43 | # Note: this will only work if 'README.md' is present in your MANIFEST.in file! 44 | try: 45 | with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: 46 | long_description = '\n' + f.read() 47 | except FileNotFoundError: 48 | long_description = DESCRIPTION 49 | 50 | # Load the package's __version__.py module as a dictionary. 51 | about = {} 52 | if not VERSION: 53 | with open(os.path.join(here, NAME, '__version__.py')) as f: 54 | exec(f.read(), about) 55 | else: 56 | about['__version__'] = VERSION 57 | 58 | 59 | class UploadCommand(Command): 60 | """Support setup.py upload.""" 61 | 62 | description = 'Build and publish the package.' 63 | user_options = [] 64 | 65 | @staticmethod 66 | def status(s): 67 | """Prints things in bold.""" 68 | print(s) 69 | 70 | def initialize_options(self): 71 | pass 72 | 73 | def finalize_options(self): 74 | pass 75 | 76 | def run(self): 77 | try: 78 | self.status('Removing previous builds...') 79 | rmtree(os.path.join(here, 'dist')) 80 | except OSError: 81 | pass 82 | 83 | self.status('Building Source and Wheel (universal) distribution...') 84 | os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) 85 | 86 | self.status('Uploading the package to PyPI via Twine...') 87 | os.system('twine upload dist/*') 88 | 89 | self.status('Pushing git tags...') 90 | os.system('git tag v{0}'.format(about['__version__'])) 91 | os.system('git push --tags') 92 | 93 | sys.exit() 94 | 95 | 96 | # Where the magic happens: 97 | setup( 98 | name=NAME, 99 | version=about['__version__'], 100 | description=DESCRIPTION, 101 | long_description=long_description, 102 | long_description_content_type='text/markdown', 103 | author=AUTHOR, 104 | author_email=EMAIL, 105 | python_requires=REQUIRES_PYTHON, 106 | url=URL, 107 | packages=find_packages(exclude=('examples', 'misc')), 108 | # If your package is a single module, use this instead of 'packages': 109 | # py_modules=['mypackage'], 110 | 111 | # entry_points={ 112 | # 'console_scripts': ['mycli=mymodule:cli'], 113 | # }, 114 | install_requires=REQUIRED, 115 | extras_require=EXTRAS, 116 | include_package_data=True, 117 | license='MIT', 118 | classifiers=[ 119 | # Trove classifiers 120 | # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers 121 | 'License :: OSI Approved :: MIT License', 122 | 'Programming Language :: Python', 123 | 'Programming Language :: Python :: 3', 124 | 'Programming Language :: Python :: Implementation :: CPython', 125 | 'Programming Language :: Python :: Implementation :: PyPy' 126 | ], 127 | # $ setup.py publish support. 128 | cmdclass={ 129 | 'upload': UploadCommand, 130 | }, 131 | ) --------------------------------------------------------------------------------