Prevent Division by zero error in classification report

This commit is contained in:
Arkadiusz Kondas 2016-11-20 22:49:26 +01:00
parent b226a561cb
commit bca2196b57
2 changed files with 19 additions and 0 deletions

View File

@ -113,6 +113,10 @@ class ClassificationReport
{
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);
}
}

View File

@ -67,4 +67,19 @@ class ClassificationReportTest extends \PHPUnit_Framework_TestCase
$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);
}
}