forked from RubixML/ML
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPipeline.php
340 lines (299 loc) · 8.71 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<?php
namespace Rubix\ML;
use Rubix\ML\Datasets\Dataset;
use Rubix\ML\Transformers\Elastic;
use Rubix\ML\Other\Helpers\Params;
use Rubix\ML\Transformers\Stateful;
use Rubix\ML\Other\Traits\ScoresSingle;
use Rubix\ML\Transformers\Transformer;
use Rubix\ML\Other\Traits\ProbaSingle;
use Rubix\ML\Other\Traits\LoggerAware;
use Rubix\ML\Other\Traits\PredictsSingle;
use Psr\Log\LoggerInterface;
use InvalidArgumentException;
use RuntimeException;
use Stringable;
/**
* Pipeline
*
* Pipeline is a meta-estimator capable of transforming an input dataset by applying a
* series of Transformer *middleware*. Under the hood, Pipeline will automatically fit the
* training set and transform any Dataset object supplied as an argument to one of the base
* estimator's methods before hitting the method context. With *elastic* mode enabled,
* Pipeline will update the fitting of Elastic transformers during partial training.
*
* > **Note:** Since transformations are applied to dataset objects in-place (without making a
* copy of the data), using a dataset in a program after it has been run through Pipeline may
* have unexpected results. If you need to keep a *clean* dataset in memory then you can clone
* the dataset object before calling the method on Pipeline that consumes it.
*
* @category Machine Learning
* @package Rubix/ML
* @author Andrew DalPino
*/
class Pipeline implements Online, Wrapper, Probabilistic, Ranking, Verbose, Persistable, Stringable
{
use PredictsSingle, ProbaSingle, ScoresSingle, LoggerAware;
/**
* A list of transformers to be applied in order.
*
* @var \Rubix\ML\Transformers\Transformer[]
*/
protected $transformers = [
//
];
/**
* An instance of a base estimator to receive the transformed data.
*
* @var \Rubix\ML\Estimator
*/
protected $base;
/**
* Should we update the elastic transformers during partial train?
*
* @var bool
*/
protected $elastic;
/**
* The PSR-3 logger instance.
*
* @var \Psr\Log\LoggerInterface|null
*/
protected $logger;
/**
* Whether or not the transformer pipeline has been fitted.
*
* @var bool
*/
protected $fitted;
/**
* @param \Rubix\ML\Transformers\Transformer[] $transformers
* @param \Rubix\ML\Estimator $base
* @param bool $elastic
* @throws \InvalidArgumentException
*/
public function __construct(array $transformers, Estimator $base, bool $elastic = true)
{
foreach ($transformers as $transformer) {
if (!$transformer instanceof Transformer) {
throw new InvalidArgumentException('Transformer must'
. ' implement the Transformer interface.');
}
}
$this->transformers = $transformers;
$this->base = $base;
$this->elastic = $elastic;
}
/**
* Return the estimator type.
*
* @internal
*
* @return \Rubix\ML\EstimatorType
*/
public function type() : EstimatorType
{
return $this->base->type();
}
/**
* Return the data types that the estimator is compatible with.
*
* @internal
*
* @return list<\Rubix\ML\DataType>
*/
public function compatibility() : array
{
return $this->base->compatibility();
}
/**
* Return the settings of the hyper-parameters in an associative array.
*
* @internal
*
* @return mixed[]
*/
public function params() : array
{
return [
'transformers' => $this->transformers,
'estimator' => $this->base,
'elastic' => $this->elastic,
];
}
/**
* Sets a logger instance on the object.
*
* @param \Psr\Log\LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger) : void
{
if ($this->base instanceof Verbose) {
$this->base->setLogger($logger);
}
$this->logger = $logger;
}
/**
* Has the learner been trained?
*
* @return bool
*/
public function trained() : bool
{
return $this->base instanceof Learner
? $this->base->trained()
: true;
}
/**
* Return the base estimator instance.
*
* @return \Rubix\ML\Estimator
*/
public function base() : Estimator
{
return $this->base;
}
/**
* Run the training dataset through all transformers in order and use the
* transformed dataset to train the estimator.
*
* @param \Rubix\ML\Datasets\Dataset $dataset
*/
public function train(Dataset $dataset) : void
{
foreach ($this->transformers as $transformer) {
if ($transformer instanceof Stateful) {
$transformer->fit($dataset);
if ($this->logger) {
$this->logger->info("Fitted $transformer");
}
}
$dataset->apply($transformer);
if ($this->logger) {
$this->logger->info("Applied $transformer");
}
}
if ($this->base instanceof Learner) {
$this->base->train($dataset);
}
}
/**
* Perform a partial train.
*
* @param \Rubix\ML\Datasets\Dataset $dataset
*/
public function partial(Dataset $dataset) : void
{
if ($this->elastic) {
foreach ($this->transformers as $transformer) {
if ($transformer instanceof Elastic) {
$transformer->update($dataset);
if ($this->logger) {
$this->logger->info("Updated $transformer");
}
}
$dataset->apply($transformer);
if ($this->logger) {
$this->logger->info("Applied $transformer");
}
}
} else {
$this->preprocess($dataset);
}
if ($this->base instanceof Online) {
$this->base->partial($dataset);
}
}
/**
* Preprocess the dataset and return predictions from the estimator.
*
* @param \Rubix\ML\Datasets\Dataset $dataset
* @return mixed[]
*/
public function predict(Dataset $dataset) : array
{
$this->preprocess($dataset);
return $this->base->predict($dataset);
}
/**
* Estimate the joint probabilities for each possible outcome.
*
* @param \Rubix\ML\Datasets\Dataset $dataset
* @throws \RuntimeException
* @return array[]
*/
public function proba(Dataset $dataset) : array
{
$this->preprocess($dataset);
if (!$this->base instanceof Probabilistic) {
throw new RuntimeException('Base Estimator must'
. ' implement the Probabilistic interface.');
}
return $this->base->proba($dataset);
}
/**
* Return the anomaly scores assigned to the samples in a dataset.
*
* @param \Rubix\ML\Datasets\Dataset $dataset
* @throws \RuntimeException
* @return float[]
*/
public function score(Dataset $dataset) : array
{
$this->preprocess($dataset);
if (!$this->base instanceof Ranking) {
throw new RuntimeException('Base Estimator must'
. ' implement the Ranking interface.');
}
return $this->base->score($dataset);
}
/**
* Return the anomaly scores assigned to the samples in a dataset.
*
* @deprecated
*
* @param \Rubix\ML\Datasets\Dataset $dataset
* @return float[]
*/
public function rank(Dataset $dataset) : array
{
trigger_error('Deprecated, use score() instead.', E_USER_DEPRECATED);
return $this->score($dataset);
}
/**
* Apply the transformer stack to a dataset.
*
* @param \Rubix\ML\Datasets\Dataset $dataset
*/
protected function preprocess(Dataset $dataset) : void
{
foreach ($this->transformers as $transformer) {
$dataset->apply($transformer);
}
}
/**
* Allow methods to be called on the estimator from the wrapper.
*
* @param string $name
* @param mixed[] $arguments
* @return mixed
*/
public function __call(string $name, array $arguments)
{
foreach ($arguments as $argument) {
if ($argument instanceof Dataset) {
$this->preprocess($argument);
}
}
return $this->base->$name(...$arguments);
}
/**
* Return the string representation of the object.
*
* @return string
*/
public function __toString() : string
{
return 'Pipeline (' . Params::stringify($this->params()) . ')';
}
}