Skip to content

Commit

Permalink
Fix division by 0 error during normalization (#83)
Browse files Browse the repository at this point in the history
* Fix division by 0 error during normalization

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

* Expand std normalization test
  • Loading branch information
dmonllao authored and akondas committed Apr 24, 2017
1 parent a87859d commit 12b8b11
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Phpml/Preprocessing/Normalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,12 @@ private function normalizeL2(array &$sample)
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;
}
}
}
}
4 changes: 4 additions & 0 deletions tests/Phpml/Preprocessing/NormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ public function testStandardNorm()
for ($k=0; $k<3; $k++) {
$sample[$k] = rand(1, 100);
}
// Last feature's value shared across samples.
$sample[] = 1;

$samples[] = $sample;
}

Expand All @@ -126,6 +129,7 @@ function ($element) {
return $element < -3 || $element > 3;
});
$this->assertCount(0, $errors);
$this->assertEquals(0, $sample[3]);
}
}
}

0 comments on commit 12b8b11

Please sign in to comment.