Data Format aware version of tf.nn.batch_normalization.
(x, mean, variance, offset, scale, variance_epsilon, data_format, name=None)
| 116 | |
| 117 | |
| 118 | def batch_normalization(x, mean, variance, offset, scale, variance_epsilon, data_format, name=None): |
| 119 | """Data Format aware version of tf.nn.batch_normalization.""" |
| 120 | if data_format == 'channels_last': |
| 121 | mean = tf.reshape(mean, [1] * (len(x.shape) - 1) + [-1]) |
| 122 | variance = tf.reshape(variance, [1] * (len(x.shape) - 1) + [-1]) |
| 123 | offset = tf.reshape(offset, [1] * (len(x.shape) - 1) + [-1]) |
| 124 | scale = tf.reshape(scale, [1] * (len(x.shape) - 1) + [-1]) |
| 125 | elif data_format == 'channels_first': |
| 126 | mean = tf.reshape(mean, [1] + [-1] + [1] * (len(x.shape) - 2)) |
| 127 | variance = tf.reshape(variance, [1] + [-1] + [1] * (len(x.shape) - 2)) |
| 128 | offset = tf.reshape(offset, [1] + [-1] + [1] * (len(x.shape) - 2)) |
| 129 | scale = tf.reshape(scale, [1] + [-1] + [1] * (len(x.shape) - 2)) |
| 130 | else: |
| 131 | raise ValueError('invalid data_format: %s' % data_format) |
| 132 | |
| 133 | with ops.name_scope(name, 'batchnorm', [x, mean, variance, scale, offset]): |
| 134 | inv = math_ops.rsqrt(variance + variance_epsilon) |
| 135 | if scale is not None: |
| 136 | inv *= scale |
| 137 | |
| 138 | a = math_ops.cast(inv, x.dtype) |
| 139 | b = math_ops.cast(offset - mean * inv if offset is not None else -mean * inv, x.dtype) |
| 140 | |
| 141 | # Return a * x + b with customized data_format. |
| 142 | # Currently TF doesn't have bias_scale, and tensorRT has bug in converting tf.nn.bias_add |
| 143 | # So we reimplemted them to allow make the model work with tensorRT. |
| 144 | # See https://github.com/tensorlayer/openpose-plus/issues/75 for more details. |
| 145 | df = {'channels_first': 'NCHW', 'channels_last': 'NHWC'} |
| 146 | return _bias_add(_bias_scale(x, a, df[data_format]), b, df[data_format]) |
| 147 | |
| 148 | |
| 149 | class BatchNorm(Layer): |
no test coverage detected
searching dependent graphs…