1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare (strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Phpml\Preprocessing; |
6
|
|
|
|
7
|
|
|
use Phpml\Preprocessing\Imputer\Strategy; |
8
|
|
|
|
9
|
|
|
class Imputer implements Preprocessor |
10
|
|
|
{ |
11
|
|
|
const AXIS_COLUMN = 0; |
12
|
|
|
const AXIS_ROW = 1; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var mixed |
16
|
|
|
*/ |
17
|
|
|
private $missingValue; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var Strategy |
21
|
|
|
*/ |
22
|
|
|
private $strategy; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var int |
26
|
|
|
*/ |
27
|
|
|
private $axis; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var |
31
|
|
|
*/ |
32
|
|
|
private $samples; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param mixed $missingValue |
36
|
|
|
* @param Strategy $strategy |
37
|
|
|
* @param int $axis |
38
|
|
|
* @param array|null $samples |
39
|
|
|
*/ |
40
|
|
|
public function __construct($missingValue = null, Strategy $strategy, int $axis = self::AXIS_COLUMN, array $samples = []) |
41
|
|
|
{ |
42
|
|
|
$this->missingValue = $missingValue; |
43
|
|
|
$this->strategy = $strategy; |
44
|
|
|
$this->axis = $axis; |
45
|
|
|
$this->samples = $samples; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param array $samples |
50
|
|
|
*/ |
51
|
|
|
public function fit(array $samples) |
52
|
|
|
{ |
53
|
|
|
$this->samples = $samples; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param array $samples |
58
|
|
|
*/ |
59
|
|
|
public function transform(array &$samples) |
60
|
|
|
{ |
61
|
|
|
foreach ($samples as &$sample) { |
62
|
|
|
$this->preprocessSample($sample); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param array $sample |
68
|
|
|
*/ |
69
|
|
|
private function preprocessSample(array &$sample) |
70
|
|
|
{ |
71
|
|
|
foreach ($sample as $column => &$value) { |
72
|
|
|
if ($value === $this->missingValue) { |
73
|
|
|
$value = $this->strategy->replaceValue($this->getAxis($column, $sample)); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @param int $column |
80
|
|
|
* @param array $currentSample |
81
|
|
|
* |
82
|
|
|
* @return array |
83
|
|
|
*/ |
84
|
|
|
private function getAxis(int $column, array $currentSample): array |
85
|
|
|
{ |
86
|
|
|
if (self::AXIS_ROW === $this->axis) { |
87
|
|
|
return array_diff($currentSample, [$this->missingValue]); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
$axis = []; |
91
|
|
|
foreach ($this->samples as $sample) { |
92
|
|
|
if ($sample[$column] !== $this->missingValue) { |
93
|
|
|
$axis[] = $sample[$column]; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
return $axis; |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|