php-ml/src/Phpml/Preprocessing/Imputer.php

84 lines
1.8 KiB
PHP
Raw Normal View History

<?php
2016-11-20 21:53:17 +00:00
declare(strict_types=1);
namespace Phpml\Preprocessing;
use Phpml\Preprocessing\Imputer\Strategy;
class Imputer implements Preprocessor
{
public const AXIS_COLUMN = 0;
public const AXIS_ROW = 1;
/**
* @var mixed
*/
private $missingValue;
/**
* @var Strategy
*/
private $strategy;
/**
* @var int
*/
private $axis;
2016-06-16 22:16:49 +00:00
/**
* @var mixed[]
2016-06-16 22:16:49 +00:00
*/
private $samples = [];
2016-06-16 22:16:49 +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-11-20 21:53:17 +00:00
public function __construct($missingValue, Strategy $strategy, int $axis = self::AXIS_COLUMN, array $samples = [])
{
$this->missingValue = $missingValue;
$this->strategy = $strategy;
$this->axis = $axis;
2016-06-16 22:16:49 +00:00
$this->samples = $samples;
}
public function fit(array $samples): void
{
2016-06-16 22:16:49 +00:00
$this->samples = $samples;
}
public function transform(array &$samples): void
{
foreach ($samples as &$sample) {
2016-06-16 22:16:49 +00:00
$this->preprocessSample($sample);
}
}
private function preprocessSample(array &$sample): void
{
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));
}
}
}
private function getAxis(int $column, array $currentSample): array
{
if ($this->axis === self::AXIS_ROW) {
return array_diff($currentSample, [$this->missingValue]);
}
$axis = [];
2016-06-16 22:16:49 +00:00
foreach ($this->samples as $sample) {
if ($sample[$column] !== $this->missingValue) {
$axis[] = $sample[$column];
}
}
return $axis;
}
}