Skip to content

Commit

Permalink
Add tensorflow-like slice in numpy backend (keras-team#11682)
Browse files Browse the repository at this point in the history
* tensorflow-like slice in numpy backend

* tiny commit

* fix pep8

* Fix test_slice using pytest.parametreized

* Simplify test_slice function

* Simplify test_slice function
  • Loading branch information
kouml authored and gabrieldemarmiesse committed Dec 9, 2018
1 parent c05ef1f commit e90e170
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
8 changes: 8 additions & 0 deletions keras/backend/numpy_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,14 @@ def reverse(x, axes):
return np.flip(x, axes)


py_slice = slice


def slice(x, start, size):
slices = [py_slice(i, i + j) for i, j in zip(start, size)]
return x[tuple(slices)]


def variable(value, dtype=None, name=None, constraint=None):
if constraint is not None:
raise TypeError("Constraint must be None when "
Expand Down
2 changes: 2 additions & 0 deletions keras/backend/tensorflow_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -2564,6 +2564,8 @@ def slice(x, start, size):
```python
new_x = x[start[0]: start[0] + size[0], ..., start[-1]: start[-1] + size[-1]]
```
{{np_implementation}}
"""
return tf.slice(x, start, size)

Expand Down
18 changes: 18 additions & 0 deletions tests/keras/backend/backend_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1731,6 +1731,24 @@ def test_ctc_decode_greedy(self):
assert np.alltrue(decode_pred_np == decode_pred)
assert np.allclose(log_prob_pred_np, log_prob_pred)

@pytest.mark.skipif(K.backend() != 'tensorflow',
reason='tensorflow-way slice is '
'only supported in tensorflow.')
@pytest.mark.parametrize('x_size', [
[1, 1, 3],
[1, 2, 3],
[2, 1, 3]
])
def test_slice(self, x_size):
npt = np.array([[[1, 1, 1], [2, 2, 2]],
[[3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6]]])
x_start = [1, 0, 0]
tft = K.constant(npt)
test_input = K.eval(K.slice(tft, x_start, x_size))
expected = KNP.slice(npt, x_start, x_size)
assert np.allclose(test_input, expected)

@pytest.mark.skipif(K.backend() != 'tensorflow',
reason='Beam search is only implemented with '
'the TensorFlow backend.')
Expand Down

0 comments on commit e90e170

Please sign in to comment.