Skip to content

Commit

Permalink
Fix compiled crossentropy (#18975)
Browse files Browse the repository at this point in the history
* Fix compiled crossentropy

* Update test case naming
  • Loading branch information
james77777778 authored Dec 20, 2023
1 parent 4a4a139 commit 30ca195
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
2 changes: 2 additions & 0 deletions keras/trainers/compile_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,8 @@ def build(self, y_true, y_pred):
"must be a callable. "
f"Received instead:\nloss={loss} of type {type(loss)}"
)
if isinstance(y_pred, list) and len(y_pred) == 1:
y_pred = y_pred[0]

if is_function_like(loss) and tree.is_nested(y_pred):
# The model has multiple outputs but only one loss fn
Expand Down
15 changes: 15 additions & 0 deletions keras/trainers/compile_utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,21 @@ def test_single_output_case(self):
value = compile_loss(y_true, y_pred)
self.assertAllClose(value, 0.068333, atol=1e-5)

def test_single_output_case_with_crossentropy_loss(self):
compile_loss = CompileLoss(loss="crossentropy")

# Test symbolic build
y_true, y_pred = backend.KerasTensor((3, 4)), backend.KerasTensor(
(3, 4)
)
compile_loss.build(y_true, y_pred)
# Test eager build
y_true = np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]])
y_pred = np.array([[0.4, 0.1], [0.2, 0.6], [0.6, 0.1]])
compile_loss.build(y_true, y_pred)
value = compile_loss(y_true, y_pred)
self.assertAllClose(value, 0.706595, atol=1e-5)

@parameterized.parameters(True, False)
def test_list_output_case(self, broadcast):
if broadcast:
Expand Down

0 comments on commit 30ca195

Please sign in to comment.