Completed
Push — develop ( 7f4a0b...601ff8 )
by Arkadiusz
03:21
created

Imputer   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 11
c 0
b 0
f 0
lcom 1
cbo 1
dl 0
loc 91
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A fit() 0 4 1
A transform() 0 6 2
A preprocessSample() 0 8 3
A getAxis() 0 15 4
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