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
|
|
|
* @param mixed $missingValue |
31
|
|
|
* @param Strategy $strategy |
32
|
|
|
* @param int $axis |
33
|
|
|
*/ |
34
|
|
|
public function __construct($missingValue = null, Strategy $strategy, int $axis = self::AXIS_COLUMN) |
35
|
|
|
{ |
36
|
|
|
$this->missingValue = $missingValue; |
37
|
|
|
$this->strategy = $strategy; |
38
|
|
|
$this->axis = $axis; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param array $samples |
43
|
|
|
*/ |
44
|
|
|
public function transform(array &$samples) |
45
|
|
|
{ |
46
|
|
|
foreach ($samples as &$sample) { |
47
|
|
|
$this->preprocessSample($sample, $samples); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param array $sample |
53
|
|
|
* @param array $samples |
54
|
|
|
*/ |
55
|
|
|
private function preprocessSample(array &$sample, array $samples) |
56
|
|
|
{ |
57
|
|
|
foreach ($sample as $column => &$value) { |
58
|
|
|
if ($value === $this->missingValue) { |
59
|
|
|
$value = $this->strategy->replaceValue($this->getAxis($column, $sample, $samples)); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @param int $column |
66
|
|
|
* @param array $currentSample |
67
|
|
|
* @param array $samples |
68
|
|
|
* |
69
|
|
|
* @return array |
70
|
|
|
*/ |
71
|
|
|
private function getAxis(int $column, array $currentSample, array $samples): array |
72
|
|
|
{ |
73
|
|
|
if (self::AXIS_ROW === $this->axis) { |
74
|
|
|
return array_diff($currentSample, [$this->missingValue]); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
$axis = []; |
78
|
|
|
foreach ($samples as $sample) { |
79
|
|
|
if ($sample[$column] !== $this->missingValue) { |
80
|
|
|
$axis[] = $sample[$column]; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return $axis; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|