Skip to content
This repository was archived by the owner on Oct 13, 2021. It is now read-only.

Handle 2D input for BatchNormalization #104

Merged
merged 7 commits into from
Jun 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions keras2onnx/ke2onnx/batch_norm.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

def convert_keras_batch_normalization(scope, operator, container):
op = operator.raw_operator
if op.axis != 3 and op.axis != -1:
if (op.axis != 3 and op.axis != -1) or len(op.input_shape) == 2:
adjusted_input_name = operator.inputs[0].full_name
else:
adjusted_input_name = scope.get_unique_variable_name(operator.inputs[0].full_name + '_transposed')
Expand Down Expand Up @@ -49,7 +49,7 @@ def convert_keras_batch_normalization(scope, operator, container):
momentum = op.momentum
spatial = 1

if op.axis != 3 and op.axis != -1:
if (op.axis != 3 and op.axis != -1) or len(op.input_shape) == 2:
# If no transpose is required, we can simply use the output of ONNX BatchNorm as the final outcome
apply_batch_norm(scope, input_tensor_names, operator.output_full_names, container,
operator_name=operator.full_name, epsilon=epsilon, is_test=is_test,
Expand Down
13 changes: 13 additions & 0 deletions tests/test_layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,19 @@ def test_batch_normalization(self):
self._batch_norm_helper(data, 'ones', 'ones', True, False, 1)
self._batch_norm_helper(data, 'zeros', 'zeros', False, True, 1)

def test_batch_normalization_2(self):
# test batch normalization on 2D input
input_dim = 10
batch_size = 4
model = keras.models.Sequential()
model.add(keras.layers.InputLayer(input_shape=(input_dim,)))
model.add(keras.layers.BatchNormalization(axis=-1))
model.add(keras.layers.Dense(5))
data = np.random.randn(batch_size, input_dim).astype(np.float32)
onnx_model = keras2onnx.convert_keras(model)
expected = model.predict(data)
self.assertTrue(self.run_onnx_runtime('test_batch_normalization_2', onnx_model, [data], expected))

def test_simpleRNN(self):
inputs1 = keras.Input(shape=(3, 1))
cls = keras.layers.SimpleRNN(2, return_state=False, return_sequences=True)
Expand Down