mirror of
https://github.com/Llewellynvdm/php-ml.git
synced 2025-01-10 00:37:55 +00:00
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:
parent
a87859dd97
commit
12b8b118dd
@ -134,7 +134,12 @@ class Normalizer implements Preprocessor
|
|||||||
private function normalizeSTD(array &$sample)
|
private function normalizeSTD(array &$sample)
|
||||||
{
|
{
|
||||||
foreach ($sample as $i => $val) {
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -111,6 +111,9 @@ class NormalizerTest extends TestCase
|
|||||||
for ($k=0; $k<3; $k++) {
|
for ($k=0; $k<3; $k++) {
|
||||||
$sample[$k] = rand(1, 100);
|
$sample[$k] = rand(1, 100);
|
||||||
}
|
}
|
||||||
|
// Last feature's value shared across samples.
|
||||||
|
$sample[] = 1;
|
||||||
|
|
||||||
$samples[] = $sample;
|
$samples[] = $sample;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -126,6 +129,7 @@ class NormalizerTest extends TestCase
|
|||||||
return $element < -3 || $element > 3;
|
return $element < -3 || $element > 3;
|
||||||
});
|
});
|
||||||
$this->assertCount(0, $errors);
|
$this->assertCount(0, $errors);
|
||||||
|
$this->assertEquals(0, $sample[3]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user