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

Pipeline   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 3
dl 0
loc 79
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A getTransformers() 0 4 1
A getEstimator() 0 4 1
A train() 0 13 3
A predict() 0 10 2
A fit() 0 7 2
A transform() 0 6 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