forked from jorgecasas/php-ml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImputer.php
87 lines (70 loc) · 1.94 KB
/
Imputer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
declare(strict_types=1);
namespace Phpml\Preprocessing;
use Phpml\Exception\InvalidOperationException;
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;
/**
* @var mixed[]
*/
private $samples = [];
/**
* @param mixed $missingValue
*/
public function __construct($missingValue, Strategy $strategy, int $axis = self::AXIS_COLUMN, array $samples = [])
{
$this->missingValue = $missingValue;
$this->strategy = $strategy;
$this->axis = $axis;
$this->samples = $samples;
}
public function fit(array $samples, ?array $targets = null): void
{
$this->samples = $samples;
}
public function transform(array &$samples, ?array &$targets = null): void
{
if ($this->samples === []) {
throw new InvalidOperationException('Missing training samples for Imputer.');
}
foreach ($samples as &$sample) {
$this->preprocessSample($sample);
}
}
private function preprocessSample(array &$sample): void
{
foreach ($sample as $column => &$value) {
if ($value === $this->missingValue) {
$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 = [];
foreach ($this->samples as $sample) {
if ($sample[$column] !== $this->missingValue) {
$axis[] = $sample[$column];
}
}
return $axis;
}
}