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