Skip to content

Commit

Permalink
Fix sparse_categorical_crossentropy argument and add value test for it (
Browse files Browse the repository at this point in the history
#7513) (#7524)

* Add value test for sparse_categorical_crossentropy (#7513)

* Swap sparse_categorical_crossentropy's target for output
  • Loading branch information
nzw0301 authored and fchollet committed Aug 4, 2017
1 parent c78fbc4 commit 281bc58
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion keras/backend/cntk_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -1629,7 +1629,7 @@ def categorical_crossentropy(target, output, from_logits=False):
def sparse_categorical_crossentropy(target, output, from_logits=False):
target = C.one_hot(target, output.shape[-1])
target = C.reshape(target, output.shape)
return categorical_crossentropy(output, target, from_logits)
return categorical_crossentropy(target, output, from_logits)


class Function(object):
Expand Down
9 changes: 9 additions & 0 deletions tests/keras/losses_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,14 @@ def test_categorical_hinge():
assert np.isclose(expected_loss, np.mean(loss))


def test_sparse_categorical_crossentropy():
y_pred = K.variable(np.array([[0.3, 0.6, 0.1],
[0.1, 0.2, 0.7]]))
y_true = K.variable(np.array([1, 2]))
expected_loss = - (np.log(0.6) + np.log(0.7)) / 2
loss = K.eval(losses.sparse_categorical_crossentropy(y_true, y_pred))
assert np.isclose(expected_loss, np.mean(loss))


if __name__ == '__main__':
pytest.main([__file__])

0 comments on commit 281bc58

Please sign in to comment.