Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/keras/src/applications/vgg16.py: 28%

72 statements  

« 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# ============================================================================== 

15 

16"""VGG16 model for Keras. 

17 

18Reference: 

19 - [Very Deep Convolutional Networks for Large-Scale Image Recognition] 

20 (https://arxiv.org/abs/1409.1556) (ICLR 2015) 

21""" 

22 

23import tensorflow.compat.v2 as tf 

24 

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 

31 

32# isort: off 

33from tensorflow.python.util.tf_export import keras_export 

34 

35WEIGHTS_PATH = ( 

36 "https://storage.googleapis.com/tensorflow/keras-applications/" 

37 "vgg16/vgg16_weights_tf_dim_ordering_tf_kernels.h5" 

38) 

39WEIGHTS_PATH_NO_TOP = ( 

40 "https://storage.googleapis.com/tensorflow/" 

41 "keras-applications/vgg16/" 

42 "vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5" 

43) 

44 

45layers = VersionAwareLayers() 

46 

47 

48@keras_export("keras.applications.vgg16.VGG16", "keras.applications.VGG16") 

49def VGG16( 

50 include_top=True, 

51 weights="imagenet", 

52 input_tensor=None, 

53 input_shape=None, 

54 pooling=None, 

55 classes=1000, 

56 classifier_activation="softmax", 

57): 

58 """Instantiates the VGG16 model. 

59 

60 Reference: 

61 - [Very Deep Convolutional Networks for Large-Scale Image Recognition]( 

62 https://arxiv.org/abs/1409.1556) (ICLR 2015) 

63 

64 For image classification use cases, see 

65 [this page for detailed examples]( 

66 https://keras.io/api/applications/#usage-examples-for-image-classification-models). 

67 

68 For transfer learning use cases, make sure to read the 

69 [guide to transfer learning & fine-tuning]( 

70 https://keras.io/guides/transfer_learning/). 

71 

72 The default input size for this model is 224x224. 

73 

74 Note: each Keras Application expects a specific kind of input preprocessing. 

75 For VGG16, call `tf.keras.applications.vgg16.preprocess_input` on your 

76 inputs before passing them to the model. 

77 `vgg16.preprocess_input` will convert the input images from RGB to BGR, 

78 then will zero-center each color channel with respect to the ImageNet 

79 dataset, without scaling. 

80 

81 Args: 

82 include_top: whether to include the 3 fully-connected 

83 layers at the top of the network. 

84 weights: one of `None` (random initialization), 

85 'imagenet' (pre-training on ImageNet), 

86 or the path to the weights file to be loaded. 

87 input_tensor: optional Keras tensor 

88 (i.e. output of `layers.Input()`) 

89 to use as image input for the model. 

90 input_shape: optional shape tuple, only to be specified 

91 if `include_top` is False (otherwise the input shape 

92 has to be `(224, 224, 3)` 

93 (with `channels_last` data format) 

94 or `(3, 224, 224)` (with `channels_first` data format). 

95 It should have exactly 3 input channels, 

96 and width and height should be no smaller than 32. 

97 E.g. `(200, 200, 3)` would be one valid value. 

98 pooling: Optional pooling mode for feature extraction 

99 when `include_top` is `False`. 

100 - `None` means that the output of the model will be 

101 the 4D tensor output of the 

102 last convolutional block. 

103 - `avg` means that global average pooling 

104 will be applied to the output of the 

105 last convolutional block, and thus 

106 the output of the model will be a 2D tensor. 

107 - `max` means that global max pooling will 

108 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. 

112 classifier_activation: A `str` or callable. The activation function to 

113 use on the "top" layer. Ignored unless `include_top=True`. Set 

114 `classifier_activation=None` to return the logits of the "top" 

115 layer. When loading pretrained weights, `classifier_activation` can 

116 only be `None` or `"softmax"`. 

117 

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. Received: " 

127 f"weights={weights}" 

128 ) 

129 

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 ) 

136 # Determine proper input shape 

137 input_shape = imagenet_utils.obtain_input_shape( 

138 input_shape, 

139 default_size=224, 

140 min_size=32, 

141 data_format=backend.image_data_format(), 

142 require_flatten=include_top, 

143 weights=weights, 

144 ) 

145 

146 if input_tensor is None: 

147 img_input = layers.Input(shape=input_shape) 

148 else: 

149 if not backend.is_keras_tensor(input_tensor): 

150 img_input = layers.Input(tensor=input_tensor, shape=input_shape) 

151 else: 

152 img_input = input_tensor 

153 # Block 1 

154 x = layers.Conv2D( 

155 64, (3, 3), activation="relu", padding="same", name="block1_conv1" 

156 )(img_input) 

157 x = layers.Conv2D( 

158 64, (3, 3), activation="relu", padding="same", name="block1_conv2" 

159 )(x) 

160 x = layers.MaxPooling2D((2, 2), strides=(2, 2), name="block1_pool")(x) 

161 

162 # Block 2 

163 x = layers.Conv2D( 

164 128, (3, 3), activation="relu", padding="same", name="block2_conv1" 

165 )(x) 

166 x = layers.Conv2D( 

167 128, (3, 3), activation="relu", padding="same", name="block2_conv2" 

168 )(x) 

169 x = layers.MaxPooling2D((2, 2), strides=(2, 2), name="block2_pool")(x) 

170 

171 # Block 3 

172 x = layers.Conv2D( 

173 256, (3, 3), activation="relu", padding="same", name="block3_conv1" 

174 )(x) 

175 x = layers.Conv2D( 

176 256, (3, 3), activation="relu", padding="same", name="block3_conv2" 

177 )(x) 

178 x = layers.Conv2D( 

179 256, (3, 3), activation="relu", padding="same", name="block3_conv3" 

180 )(x) 

181 x = layers.MaxPooling2D((2, 2), strides=(2, 2), name="block3_pool")(x) 

182 

183 # Block 4 

184 x = layers.Conv2D( 

185 512, (3, 3), activation="relu", padding="same", name="block4_conv1" 

186 )(x) 

187 x = layers.Conv2D( 

188 512, (3, 3), activation="relu", padding="same", name="block4_conv2" 

189 )(x) 

190 x = layers.Conv2D( 

191 512, (3, 3), activation="relu", padding="same", name="block4_conv3" 

192 )(x) 

193 x = layers.MaxPooling2D((2, 2), strides=(2, 2), name="block4_pool")(x) 

194 

195 # Block 5 

196 x = layers.Conv2D( 

197 512, (3, 3), activation="relu", padding="same", name="block5_conv1" 

198 )(x) 

199 x = layers.Conv2D( 

200 512, (3, 3), activation="relu", padding="same", name="block5_conv2" 

201 )(x) 

202 x = layers.Conv2D( 

203 512, (3, 3), activation="relu", padding="same", name="block5_conv3" 

204 )(x) 

205 x = layers.MaxPooling2D((2, 2), strides=(2, 2), name="block5_pool")(x) 

206 

207 if include_top: 

208 # Classification block 

209 x = layers.Flatten(name="flatten")(x) 

210 x = layers.Dense(4096, activation="relu", name="fc1")(x) 

211 x = layers.Dense(4096, activation="relu", name="fc2")(x) 

212 

213 imagenet_utils.validate_activation(classifier_activation, weights) 

214 x = layers.Dense( 

215 classes, activation=classifier_activation, name="predictions" 

216 )(x) 

217 else: 

218 if pooling == "avg": 

219 x = layers.GlobalAveragePooling2D()(x) 

220 elif pooling == "max": 

221 x = layers.GlobalMaxPooling2D()(x) 

222 

223 # Ensure that the model takes into account 

224 # any potential predecessors of `input_tensor`. 

225 if input_tensor is not None: 

226 inputs = layer_utils.get_source_inputs(input_tensor) 

227 else: 

228 inputs = img_input 

229 # Create model. 

230 model = training.Model(inputs, x, name="vgg16") 

231 

232 # Load weights. 

233 if weights == "imagenet": 

234 if include_top: 

235 weights_path = data_utils.get_file( 

236 "vgg16_weights_tf_dim_ordering_tf_kernels.h5", 

237 WEIGHTS_PATH, 

238 cache_subdir="models", 

239 file_hash="64373286793e3c8b2b4e3219cbf3544b", 

240 ) 

241 else: 

242 weights_path = data_utils.get_file( 

243 "vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5", 

244 WEIGHTS_PATH_NO_TOP, 

245 cache_subdir="models", 

246 file_hash="6d6bbae143d832006294945121d1f1fc", 

247 ) 

248 model.load_weights(weights_path) 

249 elif weights is not None: 

250 model.load_weights(weights) 

251 

252 return model 

253 

254 

255@keras_export("keras.applications.vgg16.preprocess_input") 

256def preprocess_input(x, data_format=None): 

257 return imagenet_utils.preprocess_input( 

258 x, data_format=data_format, mode="caffe" 

259 ) 

260 

261 

262@keras_export("keras.applications.vgg16.decode_predictions") 

263def decode_predictions(preds, top=5): 

264 return imagenet_utils.decode_predictions(preds, top=top) 

265 

266 

267preprocess_input.__doc__ = imagenet_utils.PREPROCESS_INPUT_DOC.format( 

268 mode="", 

269 ret=imagenet_utils.PREPROCESS_INPUT_RET_DOC_CAFFE, 

270 error=imagenet_utils.PREPROCESS_INPUT_ERROR_DOC, 

271) 

272decode_predictions.__doc__ = imagenet_utils.decode_predictions.__doc__ 

273