-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathDense.php
330 lines (282 loc) · 7.76 KB
/
Dense.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
<?php
namespace Rubix\ML\NeuralNet\Layers;
use Tensor\Matrix;
use Rubix\ML\Deferred;
use Rubix\ML\Helpers\Params;
use Rubix\ML\NeuralNet\Parameter;
use Rubix\ML\NeuralNet\Initializers\He;
use Rubix\ML\NeuralNet\Optimizers\Optimizer;
use Rubix\ML\NeuralNet\Initializers\Constant;
use Rubix\ML\NeuralNet\Initializers\Initializer;
use Rubix\ML\Exceptions\InvalidArgumentException;
use Rubix\ML\Exceptions\RuntimeException;
use Generator;
/**
* Dense
*
* Dense (or *fully connected*) hidden layers are layers of neurons that connect to each node
* in the previous layer by a parameterized synapse. They perform a linear transformation on
* their input and are usually followed by an Activation layer. The majority of the trainable
* parameters in a standard feed-forward neural network are contained within Dense hidden layers.
*
* @category Machine Learning
* @package Rubix/ML
* @author Andrew DalPino
*/
class Dense implements Hidden, Parametric
{
/**
* The number of nodes in the layer.
*
* @var positive-int
*/
protected int $neurons;
/**
* The amount of L2 regularization applied to the weights.
*
* @var float
*/
protected float $l2Penalty;
/**
* Should the layer include a bias parameter?
*
* @var bool
*/
protected bool $bias;
/**
* The weight initializer.
*
* @var Initializer
*/
protected Initializer $weightInitializer;
/**
* The bias initializer.
*
* @var Initializer
*/
protected Initializer $biasInitializer;
/**
* The weights.
*
* @var Parameter|null
*/
protected ?Parameter $weights = null;
/**
* The biases.
*
* @var Parameter|null
*/
protected ?Parameter $biases = null;
/**
* The memorized inputs to the layer.
*
* @var Matrix|null
*/
protected ?Matrix $input = null;
/**
* @param int $neurons
* @param float $l2Penalty
* @param bool $bias
* @param Initializer|null $weightInitializer
* @param Initializer|null $biasInitializer
* @throws InvalidArgumentException
*/
public function __construct(
int $neurons,
float $l2Penalty = 0.0,
bool $bias = true,
?Initializer $weightInitializer = null,
?Initializer $biasInitializer = null
) {
if ($neurons < 1) {
throw new InvalidArgumentException('Number of neurons'
. " must be greater than 0, $neurons given.");
}
if ($l2Penalty < 0.0) {
throw new InvalidArgumentException('L2 Penalty must be'
. " greater than 0, $l2Penalty given.");
}
$this->neurons = $neurons;
$this->l2Penalty = $l2Penalty;
$this->bias = $bias;
$this->weightInitializer = $weightInitializer ?? new He();
$this->biasInitializer = $biasInitializer ?? new Constant(0.0);
}
/**
* Return the width of the layer.
*
* @internal
*
* @return positive-int
*/
public function width() : int
{
return $this->neurons;
}
/**
* Return the weight matrix.
*
* @internal
*
* @throws RuntimeException
* @return Matrix
*/
public function weights() : Matrix
{
if (!$this->weights) {
throw new RuntimeException('Layer is not initialized');
}
return $this->weights->param();
}
/**
* Initialize the layer with the fan in from the previous layer and return
* the fan out for this layer.
*
* @internal
*
* @param positive-int $fanIn
* @return positive-int
*/
public function initialize(int $fanIn) : int
{
$fanOut = $this->neurons;
$weights = $this->weightInitializer->initialize($fanIn, $fanOut);
$this->weights = new Parameter($weights);
if ($this->bias) {
$biases = $this->biasInitializer->initialize(1, $fanOut)->columnAsVector(0);
$this->biases = new Parameter($biases);
}
return $fanOut;
}
/**
* Compute a forward pass through the layer.
*
* @internal
*
* @param Matrix $input
* @throws RuntimeException
* @return Matrix
*/
public function forward(Matrix $input) : Matrix
{
if (!$this->weights) {
throw new RuntimeException('Layer is not initialized');
}
$output = $this->weights->param()->matmul($input);
if ($this->biases) {
$output = $output->add($this->biases->param());
}
$this->input = $input;
return $output;
}
/**
* Compute an inference pass through the layer.
*
* @internal
*
* @param Matrix $input
* @throws RuntimeException
* @return Matrix
*/
public function infer(Matrix $input) : Matrix
{
if (!$this->weights) {
throw new RuntimeException('Layer is not initialized');
}
$output = $this->weights->param()->matmul($input);
if ($this->biases) {
$output = $output->add($this->biases->param());
}
return $output;
}
/**
* Calculate the gradient and update the parameters of the layer.
*
* @internal
*
* @param Deferred $prevGradient
* @param Optimizer $optimizer
* @throws RuntimeException
* @return Deferred
*/
public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred
{
if (!$this->weights) {
throw new RuntimeException('Layer has not been initialized.');
}
if (!$this->input) {
throw new RuntimeException('Must perform forward pass'
. ' before backpropagating.');
}
$dOut = $prevGradient();
$dW = $dOut->matmul($this->input->transpose());
$weights = $this->weights->param();
if ($this->l2Penalty) {
$dW = $dW->add($weights->multiply($this->l2Penalty));
}
$this->weights->update($dW, $optimizer);
if ($this->biases) {
$dB = $dOut->sum();
$this->biases->update($dB, $optimizer);
}
$this->input = null;
return new Deferred([$this, 'gradient'], [$weights, $dOut]);
}
/**
* Calculate the gradient for the previous layer.
*
* @internal
*
* @param Matrix $weights
* @param Matrix $dOut
* @return Matrix
*/
public function gradient(Matrix $weights, Matrix $dOut) : Matrix
{
return $weights->transpose()->matmul($dOut);
}
/**
* Return the parameters of the layer.
*
* @internal
*
* @throws RuntimeException
* @return Generator<Parameter>
*/
public function parameters() : Generator
{
if (!$this->weights) {
throw new RuntimeException('Layer has not been initialized.');
}
yield 'weights' => $this->weights;
if ($this->biases) {
yield 'biases' => $this->biases;
}
}
/**
* Restore the parameters in the layer from an associative array.
*
* @internal
*
* @param Parameter[] $parameters
*/
public function restore(array $parameters) : void
{
$this->weights = $parameters['weights'];
$this->biases = $parameters['biases'] ?? null;
}
/**
* Return the string representation of the object.
*
* @internal
*
* @return string
*/
public function __toString() : string
{
return "Dense (neurons: {$this->neurons}, l2 penalty: {$this->l2Penalty},"
. ' bias: ' . Params::toString($this->bias) . ','
. " weight initializer: {$this->weightInitializer},"
. " bias initializer: {$this->biasInitializer})";
}
}