-
-
Notifications
You must be signed in to change notification settings - Fork 193
Expand file tree
/
Copy pathSoftmaxClassifier.php
More file actions
459 lines (388 loc) · 11.5 KB
/
Copy pathSoftmaxClassifier.php
File metadata and controls
459 lines (388 loc) · 11.5 KB
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
<?php
namespace Rubix\ML\Classifiers;
use Rubix\ML\NeuralNet\FeedForward;
use Rubix\ML\Online;
use Rubix\ML\Learner;
use Rubix\ML\Verbose;
use Rubix\ML\DataType;
use Rubix\ML\Estimator;
use Rubix\ML\Persistable;
use Rubix\ML\Probabilistic;
use Rubix\ML\EstimatorType;
use Rubix\ML\Helpers\Params;
use Rubix\ML\Datasets\Dataset;
use Rubix\ML\Traits\LoggerAware;
use Rubix\ML\NeuralNet\Network;
use Rubix\ML\NeuralNet\Layers\Dense;
use Rubix\ML\Traits\AutotrackRevisions;
use Rubix\ML\NeuralNet\Optimizers\Adam;
use Rubix\ML\NeuralNet\Layers\Multiclass;
use Rubix\ML\NeuralNet\Layers\Placeholder1D;
use Rubix\ML\NeuralNet\Optimizers\Optimizer;
use Rubix\ML\NeuralNet\Initializers\XavierNormal;
use Rubix\ML\Specifications\DatasetIsLabeled;
use Rubix\ML\Specifications\DatasetIsNotEmpty;
use Rubix\ML\Specifications\SpecificationChain;
use Rubix\ML\NeuralNet\CostFunctions\CrossEntropy;
use Rubix\ML\Specifications\DatasetHasDimensionality;
use Rubix\ML\NeuralNet\CostFunctions\ClassificationLoss;
use Rubix\ML\Specifications\LabelsAreCompatibleWithLearner;
use Rubix\ML\Specifications\SamplesAreCompatibleWithEstimator;
use Rubix\ML\Exceptions\InvalidArgumentException;
use Rubix\ML\Exceptions\RuntimeException;
use Generator;
use function is_nan;
use function count;
use function get_object_vars;
use function number_format;
/**
* Softmax Classifier
*
* A multiclass generalization of Logistic Regression using a single layer neural network
* with a Softmax output layer.
*
* @category Machine Learning
* @package Rubix/ML
* @author Andrew DalPino
*/
class SoftmaxClassifier implements Estimator, Learner, Online, Probabilistic, Verbose, Persistable
{
use AutotrackRevisions, LoggerAware;
/**
* The number of training samples to process at a time.
*
* @var positive-int
*/
protected int $batchSize;
/**
* The gradient descent optimizer used to update the network parameters.
*
* @var Optimizer
*/
protected Optimizer $optimizer;
/**
* The amount of L2 regularization applied to the weights of the output layer.
*
* @var float
*/
protected float $l2Penalty;
/**
* The maximum number of training epochs. i.e. the number of times to iterate before terminating.
*
* @var int<0,max>
*/
protected int $epochs;
/**
* The minimum change in the training loss necessary to continue training.
*
* @var float
*/
protected float $minChange;
/**
* The number of epochs without improvement in the training loss to wait before considering an early stop.
*
* @var positive-int
*/
protected int $window;
/**
* The function that computes the loss associated with an erroneous activation during training.
*
* @var ClassificationLoss
*/
protected ClassificationLoss $costFn;
/**
* The underlying neural network instance.
*
* @var FeedForward|null
*/
protected ?FeedForward $network = null;
/**
* The unique class labels.
*
* @var string[]|null
*/
protected ?array $classes = null;
/**
* The loss at each epoch from the last training session.
*
* @var float[]|null
*/
protected ?array $losses = null;
/**
* @param int $batchSize
* @param Optimizer|null $optimizer
* @param float $l2Penalty
* @param int $epochs
* @param float $minChange
* @param int $window
* @param ClassificationLoss|null $costFn
* @throws InvalidArgumentException
*/
public function __construct(
int $batchSize = 128,
?Optimizer $optimizer = null,
float $l2Penalty = 1e-4,
int $epochs = 1000,
float $minChange = 1e-4,
int $window = 5,
?ClassificationLoss $costFn = null
) {
if ($batchSize < 1) {
throw new InvalidArgumentException('Batch size must be'
. " greater than 0, $batchSize given.");
}
if ($l2Penalty < 0.0) {
throw new InvalidArgumentException('L2 Penalty must be'
. " greater than 0, $l2Penalty given.");
}
if ($epochs < 0) {
throw new InvalidArgumentException('Number of epochs'
. " must be greater than 0, $epochs given.");
}
if ($minChange < 0.0) {
throw new InvalidArgumentException('Minimum change must be'
. " greater than 0, $minChange given.");
}
if ($window < 1) {
throw new InvalidArgumentException('Window must be'
. " greater than 0, $window given.");
}
$this->batchSize = $batchSize;
$this->optimizer = $optimizer ?? new Adam();
$this->l2Penalty = $l2Penalty;
$this->epochs = $epochs;
$this->minChange = $minChange;
$this->window = $window;
$this->costFn = $costFn ?? new CrossEntropy();
}
/**
* Return the estimator type.
*
* @internal
*
* @return EstimatorType
*/
public function type() : EstimatorType
{
return EstimatorType::classifier();
}
/**
* Return the data types that the estimator is compatible with.
*
* @internal
*
* @return list<DataType>
*/
public function compatibility() : array
{
return [
DataType::continuous(),
];
}
/**
* Return the settings of the hyper-parameters in an associative array.
*
* @internal
*
* @return mixed[]
*/
public function params() : array
{
return [
'batch size' => $this->batchSize,
'optimizer' => $this->optimizer,
'l2 penalty' => $this->l2Penalty,
'epochs' => $this->epochs,
'min change' => $this->minChange,
'window' => $this->window,
'cost fn' => $this->costFn,
];
}
/**
* Has the learner been trained?
*
* @return bool
*/
public function trained() : bool
{
return $this->network and $this->classes;
}
/**
* Return an iterable progress table with the steps from the last training session.
*
* @return Generator<mixed[]>
*/
public function steps() : Generator
{
if (!$this->losses) {
return;
}
foreach ($this->losses as $epoch => $loss) {
yield [
'epoch' => $epoch,
'loss' => $loss,
];
}
}
/**
* Return the loss for each epoch of the last training session.
*
* @return float[]|null
*/
public function losses() : ?array
{
return $this->losses;
}
/**
* Return the underlying neural network instance or null if not trained.
*
* @return Network|null
*/
public function network() : ?Network
{
return $this->network;
}
/**
* Train the learner with a dataset.
*
* @param \Rubix\ML\Datasets\Labeled $dataset
*/
public function train(Dataset $dataset) : void
{
SpecificationChain::with([
new DatasetIsLabeled($dataset),
new DatasetIsNotEmpty($dataset),
new LabelsAreCompatibleWithLearner($dataset, $this),
])->check();
$classes = $dataset->possibleOutcomes();
$this->network = new FeedForward(
new Placeholder1D($dataset->numFeatures()),
[new Dense(count($classes), $this->l2Penalty, true, new XavierNormal())],
new Multiclass($classes, $this->costFn),
$this->optimizer
);
$this->network->initialize();
$this->classes = $classes;
$this->partial($dataset);
}
/**
* Perform a partial train on the learner.
*
* @param \Rubix\ML\Datasets\Labeled $dataset
*/
public function partial(Dataset $dataset) : void
{
if ($this->network == null) {
$this->train($dataset);
return;
}
SpecificationChain::with([
new DatasetIsLabeled($dataset),
new DatasetIsNotEmpty($dataset),
new SamplesAreCompatibleWithEstimator($dataset, $this),
new LabelsAreCompatibleWithLearner($dataset, $this),
])->check();
if ($this->logger) {
$this->logger->info("Training $this");
$numParams = number_format($this->network->numParams());
$this->logger->info("{$numParams} trainable parameters");
}
$prevLoss = $bestLoss = INF;
$numWorseEpochs = 0;
$this->losses = [];
for ($epoch = 1; $epoch <= $this->epochs; ++$epoch) {
$batches = $dataset->randomize()->batch($this->batchSize);
$loss = 0.0;
foreach ($batches as $batch) {
$loss += $this->network->roundtrip($batch);
}
$loss /= count($batches);
$lossChange = abs($prevLoss - $loss);
$this->losses[$epoch] = $loss;
if ($this->logger) {
$lossDirection = $loss < $prevLoss ? '↓' : '↑';
$message = "Epoch: $epoch, "
. "{$this->costFn}: $loss, "
. "Loss Change: {$lossDirection}{$lossChange}";
$this->logger->info($message);
}
if (is_nan($loss)) {
if ($this->logger) {
$this->logger->warning('Numerical instability detected');
}
break;
}
if ($loss <= 0.0) {
break;
}
if ($lossChange < $this->minChange) {
break;
}
if ($loss < $bestLoss) {
$bestLoss = $loss;
$numWorseEpochs = 0;
} else {
++$numWorseEpochs;
}
if ($numWorseEpochs >= $this->window) {
break;
}
$prevLoss = $loss;
}
if ($this->logger) {
$this->logger->info('Training complete');
}
}
/**
* Make predictions from a dataset.
*
* @param Dataset $dataset
* @return list<string>
*/
public function predict(Dataset $dataset) : array
{
return array_map('Rubix\ML\argmax', $this->proba($dataset));
}
/**
* Estimate the joint probabilities for each possible outcome.
*
* @param Dataset $dataset
* @throws RuntimeException
* @return list<array<string,float>>
*/
public function proba(Dataset $dataset) : array
{
if (!$this->network or !$this->classes) {
throw new RuntimeException('Estimator has not been trained.');
}
DatasetHasDimensionality::with($dataset, $this->network->input()->width())->check();
$activations = $this->network->infer($dataset);
$probabilities = [];
foreach ($activations->asArray() as $dist) {
$probabilities[] = array_combine($this->classes, $dist) ?: [];
}
return $probabilities;
}
/**
* Return an associative array containing the data used to serialize the object.
*
* @return mixed[]
*/
public function __serialize() : array
{
$properties = get_object_vars($this);
unset($properties['losses'], $properties['logger']);
return $properties;
}
/**
* Return the string representation of the object.
*
* @internal
*
* @return string
*/
public function __toString() : string
{
return 'Softmax Classifier (' . Params::stringify($this->params()) . ')';
}
}