-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathwrn_batchnorm.py
296 lines (230 loc) · 11.2 KB
/
wrn_batchnorm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# -*- coding: utf-8 -*-
"""Wide Residual Network models for Keras.
# Reference
- [Wide Residual Networks](https://arxiv.org/abs/1605.07146)
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import warnings
from keras.models import Model
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import AveragePooling2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.layers import Input, merge
from keras.utils.layer_utils import convert_all_kernels_in_model
from keras.utils.data_utils import get_file
from keras.engine.topology import get_source_inputs
from keras.applications.imagenet_utils import _obtain_input_shape
import keras.backend as K
TH_WEIGHTS_PATH = 'https://github.com/titu1994/Wide-Residual-Networks/releases/download/v1.2/wrn_28_8_th_kernels_th_dim_ordering.h5'
TF_WEIGHTS_PATH = 'https://github.com/titu1994/Wide-Residual-Networks/releases/download/v1.2/wrn_28_8_tf_kernels_tf_dim_ordering.h5'
TH_WEIGHTS_PATH_NO_TOP = 'https://github.com/titu1994/Wide-Residual-Networks/releases/download/v1.2/wrn_28_8_th_kernels_th_dim_ordering_no_top.h5'
TF_WEIGHTS_PATH_NO_TOP = 'https://github.com/titu1994/Wide-Residual-Networks/releases/download/v1.2/wrn_28_8_tf_kernels_tf_dim_ordering_no_top.h5'
def WideResidualNetwork(depth=28, width=8, dropout_rate=0.0,
include_top=True, weights='cifar10',
input_tensor=None, input_shape=None,
classes=10):
"""Instantiate the Wide Residual Network architecture,
optionally loading weights pre-trained
on CIFAR-10. Note that when using TensorFlow,
for best performance you should set
`image_dim_ordering="tf"` in your Keras config
at ~/.keras/keras.json.
The model and the weights are compatible with both
TensorFlow and Theano. The dimension ordering
convention used by the model is the one
specified in your Keras config file.
# Arguments
depth: number or layers in the DenseNet
width: multiplier to the ResNet width (number of filters)
dropout_rate: dropout rate
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization) or
"cifar10" (pre-training on CIFAR-10)..
input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(32, 32, 3)` (with `tf` dim ordering)
or `(3, 32, 32)` (with `th` dim ordering).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 8.
E.g. `(200, 200, 3)` would be one valid value.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
# Returns
A Keras model instance.
"""
if weights not in {'cifar10', None}:
raise ValueError('The `weights` argument should be either '
'`None` (random initialization) or `cifar10` '
'(pre-training on CIFAR-10).')
if weights == 'cifar10' and include_top and classes != 10:
raise ValueError('If using `weights` as CIFAR 10 with `include_top`'
' as true, `classes` should be 10')
if (depth - 4) % 6 != 0:
raise ValueError('Depth of the network must be such that (depth - 4)'
'should be divisible by 6.')
# Determine proper input shape
input_shape = _obtain_input_shape(input_shape,
default_size=32,
min_size=8,
dim_ordering=K.image_dim_ordering(),
include_top=include_top)
if input_tensor is None:
img_input = Input(shape=input_shape)
else:
if not K.is_keras_tensor(input_tensor):
img_input = Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
x = __create_wide_residual_network(classes, img_input, include_top, depth, width,
dropout_rate)
# Ensure that the model takes into account
# any potential predecessors of `input_tensor`.
if input_tensor is not None:
inputs = get_source_inputs(input_tensor)
else:
inputs = img_input
# Create model.
model = Model(inputs, x, name='wide-resnet')
# load weights
if weights == 'cifar10':
if (depth == 28) and (width == 8) and (dropout_rate == 0.0):
# Default parameters match. Weights for this model exist:
if K.image_dim_ordering() == 'th':
if include_top:
weights_path = get_file('wide_resnet_28_8_th_dim_ordering_th_kernels.h5',
TH_WEIGHTS_PATH,
cache_subdir='models')
else:
weights_path = get_file('wide_resnet_28_8_th_dim_ordering_th_kernels_no_top.h5',
TH_WEIGHTS_PATH_NO_TOP,
cache_subdir='models')
model.load_weights(weights_path)
if K.backend() == 'tensorflow':
warnings.warn('You are using the TensorFlow backend, yet you '
'are using the Theano '
'image dimension ordering convention '
'(`image_dim_ordering="th"`). '
'For best performance, set '
'`image_dim_ordering="tf"` in '
'your Keras config '
'at ~/.keras/keras.json.')
convert_all_kernels_in_model(model)
else:
if include_top:
weights_path = get_file('wide_resnet_28_8_tf_dim_ordering_tf_kernels.h5',
TF_WEIGHTS_PATH,
cache_subdir='models')
else:
weights_path = get_file('wide_resnet_28_8_tf_dim_ordering_tf_kernels_no_top.h5',
TF_WEIGHTS_PATH_NO_TOP,
cache_subdir='models')
model.load_weights(weights_path)
if K.backend() == 'theano':
convert_all_kernels_in_model(model)
return model
def __conv1_block(input):
x = Convolution2D(16, 3, 3, border_mode='same')(input)
channel_axis = 1 if K.image_dim_ordering() == "th" else -1
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
return x
def __conv2_block(input, k=1, dropout=0.0):
init = input
channel_axis = 1 if K.image_dim_ordering() == "th" else -1
# Check if input number of filters is same as 16 * k, else create convolution2d for this input
if K.image_dim_ordering() == "th":
if init._keras_shape[1] != 16 * k:
init = Convolution2D(16 * k, 1, 1, activation='linear', border_mode='same')(init)
else:
if init._keras_shape[-1] != 16 * k:
init = Convolution2D(16 * k, 1, 1, activation='linear', border_mode='same')(init)
x = Convolution2D(16 * k, 3, 3, border_mode='same')(input)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
if dropout > 0.0:
x = Dropout(dropout)(x)
x = Convolution2D(16 * k, 3, 3, border_mode='same')(x)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
m = merge([init, x], mode='sum')
return m
def __conv3_block(input, k=1, dropout=0.0):
init = input
channel_axis = 1 if K.image_dim_ordering() == "th" else -1
# Check if input number of filters is same as 32 * k, else create convolution2d for this input
if K.image_dim_ordering() == "th":
if init._keras_shape[1] != 32 * k:
init = Convolution2D(32 * k, 1, 1, activation='linear', border_mode='same')(init)
else:
if init._keras_shape[-1] != 32 * k:
init = Convolution2D(32 * k, 1, 1, activation='linear', border_mode='same')(init)
x = Convolution2D(32 * k, 3, 3, border_mode='same')(input)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
if dropout > 0.0:
x = Dropout(dropout)(x)
x = Convolution2D(32 * k, 3, 3, border_mode='same')(x)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
m = merge([init, x], mode='sum')
return m
def ___conv4_block(input, k=1, dropout=0.0):
init = input
channel_axis = 1 if K.image_dim_ordering() == "th" else -1
# Check if input number of filters is same as 64 * k, else create convolution2d for this input
if K.image_dim_ordering() == "th":
if init._keras_shape[1] != 64 * k:
init = Convolution2D(64 * k, 1, 1, activation='linear', border_mode='same')(init)
else:
if init._keras_shape[-1] != 64 * k:
init = Convolution2D(64 * k, 1, 1, activation='linear', border_mode='same')(init)
x = Convolution2D(64 * k, 3, 3, border_mode='same')(input)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
if dropout > 0.0:
x = Dropout(dropout)(x)
x = Convolution2D(64 * k, 3, 3, border_mode='same')(x)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
m = merge([init, x], mode='sum')
return m
def __create_wide_residual_network(nb_classes, img_input, include_top, depth=28, width=8, dropout=0.0):
''' Creates a Wide Residual Network with specified parameters
Args:
nb_classes: Number of output classes
img_input: Input tensor or layer
include_top: Flag to include the last dense layer
depth: Depth of the network. Compute N = (n - 4) / 6.
For a depth of 16, n = 16, N = (16 - 4) / 6 = 2
For a depth of 28, n = 28, N = (28 - 4) / 6 = 4
For a depth of 40, n = 40, N = (40 - 4) / 6 = 6
width: Width of the network.
dropout: Adds dropout if value is greater than 0.0
Returns:a Keras Model
'''
N = (depth - 4) // 6
x = __conv1_block(img_input)
nb_conv = 4
for i in range(N):
x = __conv2_block(x, width, dropout)
nb_conv += 2
x = MaxPooling2D((2, 2))(x)
for i in range(N):
x = __conv3_block(x, width, dropout)
nb_conv += 2
x = MaxPooling2D((2, 2))(x)
for i in range(N):
x = ___conv4_block(x, width, dropout)
nb_conv += 2
x = AveragePooling2D((8, 8))(x)
if include_top:
x = Flatten()(x)
x = Dense(nb_classes, activation='softmax')(x)
return x