-
Notifications
You must be signed in to change notification settings - Fork 0
/
layers.py
454 lines (359 loc) · 14.4 KB
/
layers.py
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
import numpy as np
import pdb
"""
This code was originally written for CS 231n at Stanford University
(cs231n.stanford.edu). It has been modified in various areas for use in the
ECE 239AS class at UCLA. This includes the descriptions of what code to
implement as well as some slight potential changes in variable names to be
consistent with class nomenclature. We thank Justin Johnson & Serena Yeung for
permission to use this code. To see the original version, please visit
cs231n.stanford.edu.
"""
def affine_forward(x, w, b):
"""
Computes the forward pass for an affine (fully-connected) layer.
The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N
examples, where each example x[i] has shape (d_1, ..., d_k). We will
reshape each input into a vector of dimension D = d_1 * ... * d_k, and
then transform it to an output vector of dimension M.
Inputs:
- x: A numpy array containing input data, of shape (N, d_1, ..., d_k)
- w: A numpy array of weights, of shape (D, M)
- b: A numpy array of biases, of shape (M,)
Returns a tuple of:
- out: output, of shape (N, M)
- cache: (x, w, b)
"""
# ================================================================ #
# YOUR CODE HERE:
# Calculate the output of the forward pass. Notice the dimensions
# of w are D x M, which is the transpose of what we did in earlier
# assignments.
# ================================================================ #
xx=x.reshape(x.shape[0], -1)
out = xx.dot(w)+b.T
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
cache = (x, w, b)
return out, cache
def affine_backward(dout, cache):
"""
Computes the backward pass for an affine layer.
Inputs:
- dout: Upstream derivative, of shape (N, M)
- cache: Tuple of:
- x: Input data, of shape (N, d_1, ... d_k)
- w: Weights, of shape (D, M)
Returns a tuple of:
- dx: Gradient with respect to x, of shape (N, d1, ..., d_k)
- dw: Gradient with respect to w, of shape (D, M)
- db: Gradient with respect to b, of shape (M,)
"""
x, w, b = cache
dx, dw, db = None, None, None
# ================================================================ #
# YOUR CODE HERE:
# Calculate the gradients for the backward pass.
# ================================================================ #
xx = x.reshape(x.shape[0], -1)
dw = np.dot(xx.T,dout) #DxM
dxdx = dout.dot(w.T)
dx = np.reshape(dxdx,x.shape) #Nxd1xd2...
db = np.ones(x.shape[0]).dot(dout)#Mx1
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return dx, dw, db
def relu_forward(x):
"""
Computes the forward pass for a layer of rectified linear units (ReLUs).
Input:
- x: Inputs, of any shape
Returns a tuple of:
- out: Output, of the same shape as x
- cache: x
"""
# ================================================================ #
# YOUR CODE HERE:
# Implement the ReLU forward pass.
# ================================================================ #
f = lambda x : np.maximum(0,x) #ReLu
out = f(x)
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
cache = x
return out, cache
def relu_backward(dout, cache):
"""
Computes the backward pass for a layer of rectified linear units (ReLUs).
Input:
- dout: Upstream derivatives, of any shape
- cache: Input x, of same shape as dout
Returns:
- dx: Gradient with respect to x
"""
x = cache
# ================================================================ #
# YOUR CODE HERE:
# Implement the ReLU backward pass
# ================================================================ #
dx = dout
dx[x<0] = 0
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return dx
def batchnorm_forward(x, gamma, beta, bn_param):
"""
Forward pass for batch normalization.
During training the sample mean and (uncorrected) sample variance are
computed from minibatch statistics and used to normalize the incoming data.
During training we also keep an exponentially decaying running mean of the mean
and variance of each feature, and these averages are used to normalize data
at test-time.
At each timestep we update the running averages for mean and variance using
an exponential decay based on the momentum parameter:
running_mean = momentum * running_mean + (1 - momentum) * sample_mean
running_var = momentum * running_var + (1 - momentum) * sample_var
Note that the batch normalization paper suggests a different test-time
behavior: they compute sample mean and variance for each feature using a
large number of training images rather than using a running average. For
this implementation we have chosen to use running averages instead since
they do not require an additional estimation step; the torch7 implementation
of batch normalization also uses running averages.
Input:
- x: Data of shape (N, D)
- gamma: Scale parameter of shape (D,)
- beta: Shift paremeter of shape (D,)
- bn_param: Dictionary with the following keys:
- mode: 'train' or 'test'; required
- eps: Constant for numeric stability
- momentum: Constant for running mean / variance.
- running_mean: Array of shape (D,) giving running mean of features
- running_var Array of shape (D,) giving running variance of features
Returns a tuple of:
- out: of shape (N, D)
- cache: A tuple of values needed in the backward pass
"""
mode = bn_param['mode']
eps = bn_param.get('eps', 1e-5)
momentum = bn_param.get('momentum', 0.9)
N, D = x.shape
running_mean = bn_param.get('running_mean', np.zeros(D, dtype=x.dtype))
running_var = bn_param.get('running_var', np.zeros(D, dtype=x.dtype))
out, cache = None, None
if mode == 'train':
# ================================================================ #
# YOUR CODE HERE:
# A few steps here:
# (1) Calculate the running mean and variance of the minibatch.
# (2) Normalize the activations with the running mean and variance.
# (3) Scale and shift the normalized activations. Store this
# as the variable 'out'
# (4) Store any variables you may need for the backward pass in
# the 'cache' variable.
# ================================================================ #
cache={}
mean = np.mean(x, axis = 0)
var = np.var(x, axis = 0)
rm = running_mean
rv = running_var
mo = momentum
rm = mo*rm+(1-mo)*mean
rv = mo*rv+(1-mo)*var
xhat=(x-mean)/(np.sqrt(eps+var))
y=gamma*xhat+beta
out=y
cache['sample_mean']=mean
cache['sample_var']=var
cache['xhat']=xhat
cache['x']=x
cache['eps']=eps
cache['gamma']=gamma
cache['beta']=beta
running_mean=rm
running_var=rv
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
elif mode == 'test':
# ================================================================ #
# YOUR CODE HERE:
# Calculate the testing time normalized activation. Normalize using
# the running mean and variance, and then scale and shift appropriately.
# Store the output as 'out'.
# ================================================================ #
cache={}
rm = running_mean
rv = running_var
xhat=(x-rm)/(np.sqrt(eps+rv))
y=gamma*xhat+beta
out=y
running_mean = rm
running_var = rv
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
else:
raise ValueError('Invalid forward batchnorm mode "%s"' % mode)
# Store the updated running means back into bn_param
bn_param['running_mean'] = running_mean
bn_param['running_var'] = running_var
return out, cache
def batchnorm_backward(dout, cache):
"""
Backward pass for batch normalization.
For this implementation, you should write out a computation graph for
batch normalization on paper and propagate gradients backward through
intermediate nodes.
Inputs:
- dout: Upstream derivatives, of shape (N, D)
- cache: Variable of intermediates from batchnorm_forward.
Returns a tuple of:
- dx: Gradient with respect to inputs x, of shape (N, D)
- dgamma: Gradient with respect to scale parameter gamma, of shape (D,)
- dbeta: Gradient with respect to shift parameter beta, of shape (D,)
"""
dx, dgamma, dbeta = None, None, None
# ================================================================ #
# YOUR CODE HERE:
# Implement the batchnorm backward pass, calculating dx, dgamma, and dbeta.
# ================================================================ #
mean = cache['sample_mean']
var = cache['sample_var']
xhat = cache['xhat']
gamma = cache['gamma']
beta = cache['beta']
eps = cache['eps']
x = cache['x']
m = dout.shape[0]
dbeta = np.sum(dout,axis = 0)
dgamma = np.sum(dout*xhat, axis = 0)
dxhat = dout*gamma
dsigma2 = np.sum(-0.5*(dxhat)*(x-mean)*(1/((var+eps)**1.5)),axis=0)
dmean = np.sum((dxhat)*(-1/np.sqrt(var+eps)),axis=0)-dsigma2*(np.sum(2*(x-mean)))/m
dx=(dxhat)*(1/np.sqrt(eps+var)) + (dsigma2)*(2*(x-mean)/m) + (dmean)*(1/m)
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return dx, dgamma, dbeta
def dropout_forward(x, dropout_param):
"""
Performs the forward pass for (inverted) dropout.
Inputs:
- x: Input data, of any shape
- dropout_param: A dictionary with the following keys:
- p: Dropout parameter. We drop each neuron output with probability p.
- mode: 'test' or 'train'. If the mode is train, then perform dropout;
if the mode is test, then just return the input.
- seed: Seed for the random number generator. Passing seed makes this
function deterministic, which is needed for gradient checking but not in
real networks.
Outputs:
- out: Array of the same shape as x.
- cache: A tuple (dropout_param, mask). In training mode, mask is the dropout
mask that was used to multiply the input; in test mode, mask is None.
"""
p, mode = dropout_param['p'], dropout_param['mode']
if 'seed' in dropout_param:
np.random.seed(dropout_param['seed'])
mask = None
out = None
if mode == 'train':
# ================================================================ #
# YOUR CODE HERE:
# Implement the inverted dropout forward pass during training time.
# Store the masked and scaled activations in out, and store the
# dropout mask as the variable mask.
# ================================================================ #
mask = (np.random.rand(*x.shape)<p)/p
out = x*mask
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
elif mode == 'test':
# ================================================================ #
# YOUR CODE HERE:
# Implement the inverted dropout forward pass during test time.
# ================================================================ #
out=x
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
cache = (dropout_param, mask)
out = out.astype(x.dtype, copy=False)
return out, cache
def dropout_backward(dout, cache):
"""
Perform the backward pass for (inverted) dropout.
Inputs:
- dout: Upstream derivatives, of any shape
- cache: (dropout_param, mask) from dropout_forward.
"""
dropout_param, mask = cache
mode = dropout_param['mode']
dx = None
if mode == 'train':
# ================================================================ #
# YOUR CODE HERE:
# Implement the inverted dropout backward pass during training time.
# ================================================================ #
dx=dout*mask
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
elif mode == 'test':
# ================================================================ #
# YOUR CODE HERE:
# Implement the inverted dropout backward pass during test time.
# ================================================================ #
pass
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return dx
def svm_loss(x, y):
"""
Computes the loss and gradient using for multiclass SVM classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
N = x.shape[0]
correct_class_scores = x[np.arange(N), y]
margins = np.maximum(0, x - correct_class_scores[:, np.newaxis] + 1.0)
margins[np.arange(N), y] = 0
loss = np.sum(margins) / N
num_pos = np.sum(margins > 0, axis=1)
dx = np.zeros_like(x)
dx[margins > 0] = 1
dx[np.arange(N), y] -= num_pos
dx /= N
return loss, dx
def softmax_loss(x, y):
"""
Computes the loss and gradient for softmax classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
probs = np.exp(x - np.max(x, axis=1, keepdims=True))
probs /= np.sum(probs, axis=1, keepdims=True)
N = x.shape[0]
loss = -np.sum(np.log(probs[np.arange(N), y])) / N
dx = probs.copy()
dx[np.arange(N), y] -= 1
dx /= N
return loss, dx