Test Setup Failed
Push — master ( ff118e...b500f0 )
by Arkadiusz
02:36
created

Pipeline::transform()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml;
6
7
use Phpml\Exception\InvalidOperationException;
8
9
class Pipeline implements Estimator, Transformer
10
{
11
    /**
12
     * @var Transformer[]
13
     */
14
    private $transformers = [];
15
16
    /**
17
     * @var Estimator|null
18
     */
19
    private $estimator;
20
21
    /**
22
     * @param Transformer[] $transformers
23
     */
24
    public function __construct(array $transformers, ?Estimator $estimator = null)
25
    {
26
        $this->transformers = array_map(static function (Transformer $transformer): Transformer {
27
            return $transformer;
28
        }, $transformers);
29
        $this->estimator = $estimator;
30
    }
31
32
    /**
33
     * @return Transformer[]
34
     */
35
    public function getTransformers(): array
36
    {
37
        return $this->transformers;
38
    }
39
40
    public function getEstimator(): ?Estimator
41
    {
42
        return $this->estimator;
43
    }
44
45
    public function train(array $samples, array $targets): void
46
    {
47
        if ($this->estimator === null) {
48
            throw new InvalidOperationException('Pipeline without estimator can\'t use train method');
49
        }
50
51
        foreach ($this->transformers as $transformer) {
52
            $transformer->fit($samples, $targets);
53
            $transformer->transform($samples, $targets);
54
        }
55
56
        $this->estimator->train($samples, $targets);
57
    }
58
59
    /**
60
     * @return mixed
61
     */
62
    public function predict(array $samples)
63
    {
64
        if ($this->estimator === null) {
65
            throw new InvalidOperationException('Pipeline without estimator can\'t use predict method');
66
        }
67
68
        $this->transform($samples);
69
70
        return $this->estimator->predict($samples);
71
    }
72
73
    public function fit(array $samples, ?array $targets = null): void
74
    {
75
        foreach ($this->transformers as $transformer) {
76
            $transformer->fit($samples, $targets);
77
            $transformer->transform($samples, $targets);
78
        }
79
    }
80
81
    public function transform(array &$samples, ?array &$targets = null): void
82
    {
83
        foreach ($this->transformers as $transformer) {
84
            $transformer->transform($samples, $targets);
85
        }
86
    }
87
}
88