Fix division by 0 error during normalization (#83)

* Fix division by 0 error during normalization

std is 0 when a feature has the same value in samples.

* Expand std normalization test
This commit is contained in:
David Monllaó 2017-04-24 17:47:30 +08:00 committed by Arkadiusz Kondas
parent a87859dd97
commit 12b8b118dd
2 changed files with 10 additions and 1 deletions

View File

@ -134,7 +134,12 @@ class Normalizer implements Preprocessor
private function normalizeSTD(array &$sample)
{
foreach ($sample as $i => $val) {
$sample[$i] = ($sample[$i] - $this->mean[$i]) / $this->std[$i];
if ($this->std[$i] != 0) {
$sample[$i] = ($sample[$i] - $this->mean[$i]) / $this->std[$i];
} else {
// Same value for all samples.
$sample[$i] = 0;
}
}
}
}

View File

@ -111,6 +111,9 @@ class NormalizerTest extends TestCase
for ($k=0; $k<3; $k++) {
$sample[$k] = rand(1, 100);
}
// Last feature's value shared across samples.
$sample[] = 1;
$samples[] = $sample;
}
@ -126,6 +129,7 @@ class NormalizerTest extends TestCase
return $element < -3 || $element > 3;
});
$this->assertCount(0, $errors);
$this->assertEquals(0, $sample[3]);
}
}
}