Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to reshape unknown tensors. #7960

Merged
merged 2 commits into from
Sep 27, 2017
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
25 changes: 9 additions & 16 deletions keras/layers/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,24 +372,17 @@ def _fix_unknown_dimension(self, input_shape, output_shape):
return tuple(output_shape)

def compute_output_shape(self, input_shape):
return (input_shape[0],) + self._fix_unknown_dimension(
input_shape[1:], self.target_shape)
if None in input_shape[1:]:
# input shape (partially) unknown? replace -1's with None's
return ((input_shape[0],) +
tuple(s if s != -1 else None for s in self.target_shape))
else:
# input shape known? then we can compute the output shape
return (input_shape[0],) + self._fix_unknown_dimension(
input_shape[1:], self.target_shape)

def call(self, inputs):
# In case the target shape is not fully defined,
# we need access to the shape of `inputs`.
# solution: rely on `K.int_shape`.
target_shape = self.target_shape
if -1 in target_shape:
# Target shape not fully defined.
input_shape = None
try:
input_shape = K.int_shape(inputs)
except TypeError:
pass
if input_shape is not None:
target_shape = self.compute_output_shape(input_shape)[1:]
return K.reshape(inputs, (-1,) + target_shape)
return K.reshape(inputs, (K.shape(inputs)[0],) + self.target_shape)

def get_config(self):
config = {'target_shape': self.target_shape}
Expand Down
4 changes: 4 additions & 0 deletions tests/keras/layers/core_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ def test_reshape():
kwargs={'target_shape': (1, -1)},
input_shape=(3, 2, 4))

layer_test(layers.Reshape,
kwargs={'target_shape': (-1, 1)},
input_shape=(None, None, 4))


@keras_test
def test_permute():
Expand Down