Skip to content

Commit

Permalink
Prevent Division by zero error in classification report
Browse files Browse the repository at this point in the history
akondas committed Nov 20, 2016
1 parent b226a56 commit bca2196
Showing 2 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Phpml/Metric/ClassificationReport.php
Original file line number Diff line number Diff line change
@@ -113,6 +113,10 @@ private function computeAverage()
{
foreach (['precision', 'recall', 'f1score'] as $metric) {
$values = array_filter($this->$metric);
if(0==count($values)) {
$this->average[$metric] = 0.0;
continue;
}
$this->average[$metric] = array_sum($values) / count($values);
}
}
15 changes: 15 additions & 0 deletions tests/Phpml/Metric/ClassificationReportTest.php
Original file line number Diff line number Diff line change
@@ -67,4 +67,19 @@ public function testPreventDivideByZeroWhenTruePositiveAndFalseNegativeSumEquals

$this->assertEquals([1 => 0.0, 2 => 1, 3 => 0], $report->getPrecision(), '', 0.01);
}

public function testPreventDividedByZeroWhenPredictedLabelsAllNotMatch()
{
$labels = [1,2,3,4,5];
$predicted = [2,3,4,5,6];

$report = new ClassificationReport($labels, $predicted);

$this->assertEquals([
'precision' => 0,
'recall' => 0,
'f1score' => 0
], $report->getAverage(), '', 0.01);
}

}

0 comments on commit bca2196

Please sign in to comment.