Skip to content
Closed
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
- Add numerical stability to logsumexp function
- Fix Mean Shift delta hyper-parameter
- Fix MAPE calculation in Error Analysis report
- Fix Cross Entropy loss missing (1−t)·log(1−p) term
- Fix SiLU derivative at zero
- Remove spurious +1 in Relative Entropy gradient
- SoftPlus derivative expressed in terms of input
Expand Down
9 changes: 7 additions & 2 deletions src/NeuralNet/CostFunctions/CrossEntropy.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,14 @@ class CrossEntropy implements ClassificationLoss
*/
public function compute(Matrix $output, Matrix $target) : float
{
$entropy = $output->clipLower(EPSILON)->log();
$output = $output->clip(EPSILON, 1.0 - EPSILON);

return $target->negate()->multiply($entropy)->mean()->mean();
$ones = Matrix::ones(...$output->shape());

$entropy = $output->log()->multiply($target)
->add($ones->subtract($output)->log()->multiply($ones->subtract($target)));

return $entropy->negate()->mean()->mean();
Comment on lines +36 to +43
}

/**
Expand Down
8 changes: 4 additions & 4 deletions tests/NeuralNet/CostFunctions/CrossEntropyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public function computeProvider() : Generator
Matrix::quick([
[1.0, 0.0, 0.0],
]),
0.00335011195116715,
0.006700227235667666,
];

yield [
Expand All @@ -73,7 +73,7 @@ public function computeProvider() : Generator
Matrix::quick([
[0.0, 1.0, 0.0],
]),
0.3054302439580517,
0.5500866356514519,
];

yield [
Expand All @@ -83,7 +83,7 @@ public function computeProvider() : Generator
Matrix::quick([
[1.0, 0.0, 0.0],
]),
6.140226914650789,
6.94287545086808,
];

yield [
Expand All @@ -97,7 +97,7 @@ public function computeProvider() : Generator
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
]),
0.10809567592917217,
0.20764012617655228,
];
Comment on lines 89 to 101
}

Expand Down
Loading