2016-05-08 12:47:17 +00:00
|
|
|
<?php
|
|
|
|
|
2016-11-20 21:53:17 +00:00
|
|
|
declare(strict_types=1);
|
2016-05-08 12:47:17 +00:00
|
|
|
|
|
|
|
namespace Phpml\Preprocessing;
|
|
|
|
|
|
|
|
use Phpml\Preprocessing\Imputer\Strategy;
|
|
|
|
|
|
|
|
class Imputer implements Preprocessor
|
|
|
|
{
|
2017-11-14 20:21:23 +00:00
|
|
|
public const AXIS_COLUMN = 0;
|
|
|
|
public const AXIS_ROW = 1;
|
2016-05-08 12:47:17 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @var mixed
|
|
|
|
*/
|
|
|
|
private $missingValue;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var Strategy
|
|
|
|
*/
|
|
|
|
private $strategy;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var int
|
|
|
|
*/
|
|
|
|
private $axis;
|
|
|
|
|
2016-06-16 22:16:49 +00:00
|
|
|
/**
|
2016-06-16 22:34:15 +00:00
|
|
|
* @var
|
2016-06-16 22:16:49 +00:00
|
|
|
*/
|
|
|
|
private $samples;
|
|
|
|
|
2016-05-08 12:47:17 +00:00
|
|
|
/**
|
2016-06-16 22:34:15 +00:00
|
|
|
* @param mixed $missingValue
|
2016-06-16 22:16:49 +00:00
|
|
|
* @param array|null $samples
|
2016-05-08 12:47:17 +00:00
|
|
|
*/
|
2016-11-20 21:53:17 +00:00
|
|
|
public function __construct($missingValue, Strategy $strategy, int $axis = self::AXIS_COLUMN, array $samples = [])
|
2016-05-08 12:47:17 +00:00
|
|
|
{
|
|
|
|
$this->missingValue = $missingValue;
|
|
|
|
$this->strategy = $strategy;
|
|
|
|
$this->axis = $axis;
|
2016-06-16 22:16:49 +00:00
|
|
|
$this->samples = $samples;
|
2016-05-08 12:47:17 +00:00
|
|
|
}
|
|
|
|
|
2017-11-14 20:21:23 +00:00
|
|
|
public function fit(array $samples): void
|
2016-06-16 22:08:10 +00:00
|
|
|
{
|
2016-06-16 22:16:49 +00:00
|
|
|
$this->samples = $samples;
|
2016-06-16 22:08:10 +00:00
|
|
|
}
|
|
|
|
|
2017-11-14 20:21:23 +00:00
|
|
|
public function transform(array &$samples): void
|
2016-05-08 12:47:17 +00:00
|
|
|
{
|
|
|
|
foreach ($samples as &$sample) {
|
2016-06-16 22:16:49 +00:00
|
|
|
$this->preprocessSample($sample);
|
2016-05-08 12:47:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-14 20:21:23 +00:00
|
|
|
private function preprocessSample(array &$sample): void
|
2016-05-08 12:47:17 +00:00
|
|
|
{
|
|
|
|
foreach ($sample as $column => &$value) {
|
|
|
|
if ($value === $this->missingValue) {
|
2016-06-16 22:16:49 +00:00
|
|
|
$value = $this->strategy->replaceValue($this->getAxis($column, $sample));
|
2016-05-08 12:47:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-06 07:56:37 +00:00
|
|
|
private function getAxis(int $column, array $currentSample) : array
|
2016-05-08 12:47:17 +00:00
|
|
|
{
|
|
|
|
if (self::AXIS_ROW === $this->axis) {
|
|
|
|
return array_diff($currentSample, [$this->missingValue]);
|
|
|
|
}
|
|
|
|
|
|
|
|
$axis = [];
|
2016-06-16 22:16:49 +00:00
|
|
|
foreach ($this->samples as $sample) {
|
2016-05-08 12:47:17 +00:00
|
|
|
if ($sample[$column] !== $this->missingValue) {
|
|
|
|
$axis[] = $sample[$column];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $axis;
|
|
|
|
}
|
|
|
|
}
|