Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/keras/src/applications/inception_v3.py: 13%
167 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 07:57 +0000
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 07:57 +0000
1# Copyright 2015 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# ==============================================================================
16"""Inception V3 model for Keras.
18Reference:
19 - [Rethinking the Inception Architecture for Computer Vision](
20 http://arxiv.org/abs/1512.00567) (CVPR 2016)
21"""
23import tensorflow.compat.v2 as tf
25from keras.src import backend
26from keras.src.applications import imagenet_utils
27from keras.src.engine import training
28from keras.src.layers import VersionAwareLayers
29from keras.src.utils import data_utils
30from keras.src.utils import layer_utils
32# isort: off
33from tensorflow.python.util.tf_export import keras_export
35WEIGHTS_PATH = (
36 "https://storage.googleapis.com/tensorflow/keras-applications/"
37 "inception_v3/inception_v3_weights_tf_dim_ordering_tf_kernels.h5"
38)
39WEIGHTS_PATH_NO_TOP = (
40 "https://storage.googleapis.com/tensorflow/keras-applications/"
41 "inception_v3/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5"
42)
44layers = VersionAwareLayers()
47@keras_export(
48 "keras.applications.inception_v3.InceptionV3",
49 "keras.applications.InceptionV3",
50)
51def InceptionV3(
52 include_top=True,
53 weights="imagenet",
54 input_tensor=None,
55 input_shape=None,
56 pooling=None,
57 classes=1000,
58 classifier_activation="softmax",
59):
60 """Instantiates the Inception v3 architecture.
62 Reference:
63 - [Rethinking the Inception Architecture for Computer Vision](
64 http://arxiv.org/abs/1512.00567) (CVPR 2016)
66 This function returns a Keras image classification model,
67 optionally loaded with weights pre-trained on ImageNet.
69 For image classification use cases, see
70 [this page for detailed examples](
71 https://keras.io/api/applications/#usage-examples-for-image-classification-models).
73 For transfer learning use cases, make sure to read the
74 [guide to transfer learning & fine-tuning](
75 https://keras.io/guides/transfer_learning/).
77 Note: each Keras Application expects a specific kind of input preprocessing.
78 For `InceptionV3`, call
79 `tf.keras.applications.inception_v3.preprocess_input` on your inputs before
80 passing them to the model. `inception_v3.preprocess_input` will scale input
81 pixels between -1 and 1.
83 Args:
84 include_top: Boolean, whether to include the fully-connected
85 layer at the top, as the last layer of the network. Defaults to `True`.
86 weights: One of `None` (random initialization),
87 `imagenet` (pre-training on ImageNet),
88 or the path to the weights file to be loaded. Defaults to `imagenet`.
89 input_tensor: Optional Keras tensor (i.e. output of `layers.Input()`)
90 to use as image input for the model. `input_tensor` is useful for
91 sharing inputs between multiple different networks. Defaults to `None`.
92 input_shape: Optional shape tuple, only to be specified
93 if `include_top` is False (otherwise the input shape
94 has to be `(299, 299, 3)` (with `channels_last` data format)
95 or `(3, 299, 299)` (with `channels_first` data format).
96 It should have exactly 3 inputs channels,
97 and width and height should be no smaller than 75.
98 E.g. `(150, 150, 3)` would be one valid value.
99 `input_shape` will be ignored if the `input_tensor` is provided.
100 pooling: Optional pooling mode for feature extraction
101 when `include_top` is `False`.
102 - `None` (default) means that the output of the model will be
103 the 4D tensor output of the last convolutional block.
104 - `avg` means that global average pooling
105 will be applied to the output of the
106 last convolutional block, and thus
107 the output of the model will be a 2D tensor.
108 - `max` means that global max pooling will be applied.
109 classes: optional number of classes to classify images
110 into, only to be specified if `include_top` is True, and
111 if no `weights` argument is specified. Defaults to 1000.
112 classifier_activation: A `str` or callable. The activation function to use
113 on the "top" layer. Ignored unless `include_top=True`. Set
114 `classifier_activation=None` to return the logits of the "top" layer.
115 When loading pretrained weights, `classifier_activation` can only
116 be `None` or `"softmax"`.
118 Returns:
119 A `keras.Model` instance.
120 """
121 if not (weights in {"imagenet", None} or tf.io.gfile.exists(weights)):
122 raise ValueError(
123 "The `weights` argument should be either "
124 "`None` (random initialization), `imagenet` "
125 "(pre-training on ImageNet), "
126 "or the path to the weights file to be loaded; "
127 f"Received: weights={weights}"
128 )
130 if weights == "imagenet" and include_top and classes != 1000:
131 raise ValueError(
132 'If using `weights` as `"imagenet"` with `include_top` '
133 "as true, `classes` should be 1000; "
134 f"Received classes={classes}"
135 )
137 # Determine proper input shape
138 input_shape = imagenet_utils.obtain_input_shape(
139 input_shape,
140 default_size=299,
141 min_size=75,
142 data_format=backend.image_data_format(),
143 require_flatten=include_top,
144 weights=weights,
145 )
147 if input_tensor is None:
148 img_input = layers.Input(shape=input_shape)
149 else:
150 if not backend.is_keras_tensor(input_tensor):
151 img_input = layers.Input(tensor=input_tensor, shape=input_shape)
152 else:
153 img_input = input_tensor
155 if backend.image_data_format() == "channels_first":
156 channel_axis = 1
157 else:
158 channel_axis = 3
160 x = conv2d_bn(img_input, 32, 3, 3, strides=(2, 2), padding="valid")
161 x = conv2d_bn(x, 32, 3, 3, padding="valid")
162 x = conv2d_bn(x, 64, 3, 3)
163 x = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)
165 x = conv2d_bn(x, 80, 1, 1, padding="valid")
166 x = conv2d_bn(x, 192, 3, 3, padding="valid")
167 x = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)
169 # mixed 0: 35 x 35 x 256
170 branch1x1 = conv2d_bn(x, 64, 1, 1)
172 branch5x5 = conv2d_bn(x, 48, 1, 1)
173 branch5x5 = conv2d_bn(branch5x5, 64, 5, 5)
175 branch3x3dbl = conv2d_bn(x, 64, 1, 1)
176 branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
177 branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
179 branch_pool = layers.AveragePooling2D(
180 (3, 3), strides=(1, 1), padding="same"
181 )(x)
182 branch_pool = conv2d_bn(branch_pool, 32, 1, 1)
183 x = layers.concatenate(
184 [branch1x1, branch5x5, branch3x3dbl, branch_pool],
185 axis=channel_axis,
186 name="mixed0",
187 )
189 # mixed 1: 35 x 35 x 288
190 branch1x1 = conv2d_bn(x, 64, 1, 1)
192 branch5x5 = conv2d_bn(x, 48, 1, 1)
193 branch5x5 = conv2d_bn(branch5x5, 64, 5, 5)
195 branch3x3dbl = conv2d_bn(x, 64, 1, 1)
196 branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
197 branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
199 branch_pool = layers.AveragePooling2D(
200 (3, 3), strides=(1, 1), padding="same"
201 )(x)
202 branch_pool = conv2d_bn(branch_pool, 64, 1, 1)
203 x = layers.concatenate(
204 [branch1x1, branch5x5, branch3x3dbl, branch_pool],
205 axis=channel_axis,
206 name="mixed1",
207 )
209 # mixed 2: 35 x 35 x 288
210 branch1x1 = conv2d_bn(x, 64, 1, 1)
212 branch5x5 = conv2d_bn(x, 48, 1, 1)
213 branch5x5 = conv2d_bn(branch5x5, 64, 5, 5)
215 branch3x3dbl = conv2d_bn(x, 64, 1, 1)
216 branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
217 branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
219 branch_pool = layers.AveragePooling2D(
220 (3, 3), strides=(1, 1), padding="same"
221 )(x)
222 branch_pool = conv2d_bn(branch_pool, 64, 1, 1)
223 x = layers.concatenate(
224 [branch1x1, branch5x5, branch3x3dbl, branch_pool],
225 axis=channel_axis,
226 name="mixed2",
227 )
229 # mixed 3: 17 x 17 x 768
230 branch3x3 = conv2d_bn(x, 384, 3, 3, strides=(2, 2), padding="valid")
232 branch3x3dbl = conv2d_bn(x, 64, 1, 1)
233 branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
234 branch3x3dbl = conv2d_bn(
235 branch3x3dbl, 96, 3, 3, strides=(2, 2), padding="valid"
236 )
238 branch_pool = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)
239 x = layers.concatenate(
240 [branch3x3, branch3x3dbl, branch_pool], axis=channel_axis, name="mixed3"
241 )
243 # mixed 4: 17 x 17 x 768
244 branch1x1 = conv2d_bn(x, 192, 1, 1)
246 branch7x7 = conv2d_bn(x, 128, 1, 1)
247 branch7x7 = conv2d_bn(branch7x7, 128, 1, 7)
248 branch7x7 = conv2d_bn(branch7x7, 192, 7, 1)
250 branch7x7dbl = conv2d_bn(x, 128, 1, 1)
251 branch7x7dbl = conv2d_bn(branch7x7dbl, 128, 7, 1)
252 branch7x7dbl = conv2d_bn(branch7x7dbl, 128, 1, 7)
253 branch7x7dbl = conv2d_bn(branch7x7dbl, 128, 7, 1)
254 branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)
256 branch_pool = layers.AveragePooling2D(
257 (3, 3), strides=(1, 1), padding="same"
258 )(x)
259 branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
260 x = layers.concatenate(
261 [branch1x1, branch7x7, branch7x7dbl, branch_pool],
262 axis=channel_axis,
263 name="mixed4",
264 )
266 # mixed 5, 6: 17 x 17 x 768
267 for i in range(2):
268 branch1x1 = conv2d_bn(x, 192, 1, 1)
270 branch7x7 = conv2d_bn(x, 160, 1, 1)
271 branch7x7 = conv2d_bn(branch7x7, 160, 1, 7)
272 branch7x7 = conv2d_bn(branch7x7, 192, 7, 1)
274 branch7x7dbl = conv2d_bn(x, 160, 1, 1)
275 branch7x7dbl = conv2d_bn(branch7x7dbl, 160, 7, 1)
276 branch7x7dbl = conv2d_bn(branch7x7dbl, 160, 1, 7)
277 branch7x7dbl = conv2d_bn(branch7x7dbl, 160, 7, 1)
278 branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)
280 branch_pool = layers.AveragePooling2D(
281 (3, 3), strides=(1, 1), padding="same"
282 )(x)
283 branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
284 x = layers.concatenate(
285 [branch1x1, branch7x7, branch7x7dbl, branch_pool],
286 axis=channel_axis,
287 name="mixed" + str(5 + i),
288 )
290 # mixed 7: 17 x 17 x 768
291 branch1x1 = conv2d_bn(x, 192, 1, 1)
293 branch7x7 = conv2d_bn(x, 192, 1, 1)
294 branch7x7 = conv2d_bn(branch7x7, 192, 1, 7)
295 branch7x7 = conv2d_bn(branch7x7, 192, 7, 1)
297 branch7x7dbl = conv2d_bn(x, 192, 1, 1)
298 branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 7, 1)
299 branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)
300 branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 7, 1)
301 branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)
303 branch_pool = layers.AveragePooling2D(
304 (3, 3), strides=(1, 1), padding="same"
305 )(x)
306 branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
307 x = layers.concatenate(
308 [branch1x1, branch7x7, branch7x7dbl, branch_pool],
309 axis=channel_axis,
310 name="mixed7",
311 )
313 # mixed 8: 8 x 8 x 1280
314 branch3x3 = conv2d_bn(x, 192, 1, 1)
315 branch3x3 = conv2d_bn(branch3x3, 320, 3, 3, strides=(2, 2), padding="valid")
317 branch7x7x3 = conv2d_bn(x, 192, 1, 1)
318 branch7x7x3 = conv2d_bn(branch7x7x3, 192, 1, 7)
319 branch7x7x3 = conv2d_bn(branch7x7x3, 192, 7, 1)
320 branch7x7x3 = conv2d_bn(
321 branch7x7x3, 192, 3, 3, strides=(2, 2), padding="valid"
322 )
324 branch_pool = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)
325 x = layers.concatenate(
326 [branch3x3, branch7x7x3, branch_pool], axis=channel_axis, name="mixed8"
327 )
329 # mixed 9: 8 x 8 x 2048
330 for i in range(2):
331 branch1x1 = conv2d_bn(x, 320, 1, 1)
333 branch3x3 = conv2d_bn(x, 384, 1, 1)
334 branch3x3_1 = conv2d_bn(branch3x3, 384, 1, 3)
335 branch3x3_2 = conv2d_bn(branch3x3, 384, 3, 1)
336 branch3x3 = layers.concatenate(
337 [branch3x3_1, branch3x3_2],
338 axis=channel_axis,
339 name="mixed9_" + str(i),
340 )
342 branch3x3dbl = conv2d_bn(x, 448, 1, 1)
343 branch3x3dbl = conv2d_bn(branch3x3dbl, 384, 3, 3)
344 branch3x3dbl_1 = conv2d_bn(branch3x3dbl, 384, 1, 3)
345 branch3x3dbl_2 = conv2d_bn(branch3x3dbl, 384, 3, 1)
346 branch3x3dbl = layers.concatenate(
347 [branch3x3dbl_1, branch3x3dbl_2], axis=channel_axis
348 )
350 branch_pool = layers.AveragePooling2D(
351 (3, 3), strides=(1, 1), padding="same"
352 )(x)
353 branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
354 x = layers.concatenate(
355 [branch1x1, branch3x3, branch3x3dbl, branch_pool],
356 axis=channel_axis,
357 name="mixed" + str(9 + i),
358 )
359 if include_top:
360 # Classification block
361 x = layers.GlobalAveragePooling2D(name="avg_pool")(x)
362 imagenet_utils.validate_activation(classifier_activation, weights)
363 x = layers.Dense(
364 classes, activation=classifier_activation, name="predictions"
365 )(x)
366 else:
367 if pooling == "avg":
368 x = layers.GlobalAveragePooling2D()(x)
369 elif pooling == "max":
370 x = layers.GlobalMaxPooling2D()(x)
372 # Ensure that the model takes into account
373 # any potential predecessors of `input_tensor`.
374 if input_tensor is not None:
375 inputs = layer_utils.get_source_inputs(input_tensor)
376 else:
377 inputs = img_input
378 # Create model.
379 model = training.Model(inputs, x, name="inception_v3")
381 # Load weights.
382 if weights == "imagenet":
383 if include_top:
384 weights_path = data_utils.get_file(
385 "inception_v3_weights_tf_dim_ordering_tf_kernels.h5",
386 WEIGHTS_PATH,
387 cache_subdir="models",
388 file_hash="9a0d58056eeedaa3f26cb7ebd46da564",
389 )
390 else:
391 weights_path = data_utils.get_file(
392 "inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5",
393 WEIGHTS_PATH_NO_TOP,
394 cache_subdir="models",
395 file_hash="bcbd6486424b2319ff4ef7d526e38f63",
396 )
397 model.load_weights(weights_path)
398 elif weights is not None:
399 model.load_weights(weights)
401 return model
404def conv2d_bn(
405 x, filters, num_row, num_col, padding="same", strides=(1, 1), name=None
406):
407 """Utility function to apply conv + BN.
409 Args:
410 x: input tensor.
411 filters: filters in `Conv2D`.
412 num_row: height of the convolution kernel.
413 num_col: width of the convolution kernel.
414 padding: padding mode in `Conv2D`.
415 strides: strides in `Conv2D`.
416 name: name of the ops; will become `name + '_conv'`
417 for the convolution and `name + '_bn'` for the
418 batch norm layer.
420 Returns:
421 Output tensor after applying `Conv2D` and `BatchNormalization`.
422 """
423 if name is not None:
424 bn_name = name + "_bn"
425 conv_name = name + "_conv"
426 else:
427 bn_name = None
428 conv_name = None
429 if backend.image_data_format() == "channels_first":
430 bn_axis = 1
431 else:
432 bn_axis = 3
433 x = layers.Conv2D(
434 filters,
435 (num_row, num_col),
436 strides=strides,
437 padding=padding,
438 use_bias=False,
439 name=conv_name,
440 )(x)
441 x = layers.BatchNormalization(axis=bn_axis, scale=False, name=bn_name)(x)
442 x = layers.Activation("relu", name=name)(x)
443 return x
446@keras_export("keras.applications.inception_v3.preprocess_input")
447def preprocess_input(x, data_format=None):
448 return imagenet_utils.preprocess_input(
449 x, data_format=data_format, mode="tf"
450 )
453@keras_export("keras.applications.inception_v3.decode_predictions")
454def decode_predictions(preds, top=5):
455 return imagenet_utils.decode_predictions(preds, top=top)
458preprocess_input.__doc__ = imagenet_utils.PREPROCESS_INPUT_DOC.format(
459 mode="",
460 ret=imagenet_utils.PREPROCESS_INPUT_RET_DOC_TF,
461 error=imagenet_utils.PREPROCESS_INPUT_ERROR_DOC,
462)
463decode_predictions.__doc__ = imagenet_utils.decode_predictions.__doc__