-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirst_excercice
More file actions
530 lines (438 loc) · 21.5 KB
/
first_excercice
File metadata and controls
530 lines (438 loc) · 21.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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
Python Basics with Numpy (optional assignment)
Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help familiarize you with the functions we'll need.
Instructions:
You will be using Python 3.
Avoid using for-loops and while-loops, unless you are explicitly told to do so.
After coding your function, run the cell right below it to check if your result is correct.
After this assignment you will:
Be able to use iPython Notebooks
Be able to use numpy functions and numpy matrix/vector operations
Understand the concept of "broadcasting"
Be able to vectorize code
Let's get started!
Table of Contents
About iPython Notebooks
Exercise 1
1 - Building basic functions with numpy
1.1 - sigmoid function, np.exp()
Exercise 2 - basic_sigmoid
Exercise 3 - sigmoid
1.2 - Sigmoid Gradient
Exercise 4 - sigmoid_derivative
1.3 - Reshaping arrays
Exercise 5 - image2vector
1.4 - Normalizing rows
Exercise 6 - normalize_rows
Exercise 7 - softmax
2 - Vectorization
2.1 Implement the L1 and L2 loss functions
Exercise 8 - L1
Exercise 9 - L2
About iPython Notebooks
iPython Notebooks are interactive coding environments embedded in a webpage. You will be using iPython notebooks in this class. You only need to write code between the # your code here comment. After writing your code, you can run the cell by either pressing "SHIFT"+"ENTER" or by clicking on "Run Cell" (denoted by a play symbol) in the upper bar of the notebook.
We will often specify "(≈ X lines of code)" in the comments to tell you about how much code you need to write. It is just a rough estimate, so don't feel bad if your code is longer or shorter.
Exercise 1
Set test to "Hello World" in the cell below to print "Hello World" and run the two cells below.
# (≈ 1 line of code)
# test =
# YOUR CODE STARTS HERE
test = "Hello World"
# YOUR CODE ENDS HERE
print ("test: " + test)
Expected output: test: Hello World
What you need to remember :
Run your cells using SHIFT+ENTER (or "Run cell")
Write code in the designated areas using Python 3 only
Do not modify the code outside of the designated areas
1 - Building basic functions with numpy
Numpy is the main package for scientific computing in Python. It is maintained by a large community (www.numpy.org). In this exercise you will learn several key numpy functions such as np.exp, np.log, and np.reshape. You will need to know how to use these functions for future assignments.
1.1 - sigmoid function, np.exp()
Before using np.exp(), you will use math.exp() to implement the sigmoid function. You will then see why np.exp() is preferable to math.exp().
Exercise 2 - basic_sigmoid
Build a function that returns the sigmoid of a real number x. Use math.exp(x) for the exponential function.
Reminder: 𝑠𝑖𝑔𝑚𝑜𝑖𝑑(𝑥)=11+𝑒−𝑥 is sometimes also known as the logistic function. It is a non-linear function used not only in Machine Learning (Logistic Regression), but also in Deep Learning.
To refer to a function belonging to a specific package you could call it using package_name.function(). Run the code below to see an example with math.exp().
import math
from public_tests import *
# GRADED FUNCTION: basic_sigmoid
def basic_sigmoid(x):
"""
Compute sigmoid of x.
Arguments:
x -- A scalar
Return:
s -- sigmoid(x)
"""
# (≈ 1 line of code)
# s =
# YOUR CODE STARTS HERE
s = 1 / (1 + math.exp(-x))
# YOUR CODE ENDS HERE
return s
print("basic_sigmoid(1) = " + str(basic_sigmoid(1)))
basic_sigmoid_test(basic_sigmoid)
Actually, we rarely use the "math" library in deep learning because the inputs of the functions are real numbers. In deep learning we mostly use matrices and vectors. This is why numpy is more useful.
### One reason why we use "numpy" instead of "math" in Deep Learning ###
x = [1, 2, 3] # x becomes a python list object
basic_sigmoid(x) # you will see this give an error when you run it, because x is a vector.
In fact, if 𝑥=(𝑥1,𝑥2,...,𝑥𝑛) is a row vector then np.exp(x) will apply the exponential function to every element of x. The output will thus be: np.exp(x) = (e^{x_1}, e^{x_2}, ..., e^{x_n})
import numpy as np
# example of np.exp
t_x = np.array([1, 2, 3])
print(np.exp(t_x)) # result is (exp(1), exp(2), exp(3))
Furthermore, if x is a vector, then a Python operation such as 𝑠=𝑥+3 or 𝑠=1𝑥 will output s as a vector of the same size as x.
# example of vector operation
t_x = np.array([1, 2, 3])
print (t_x + 3)
Any time you need more info on a numpy function, we encourage you to look at the official documentation.
You can also create a new cell in the notebook and write np.exp? (for example) to get quick access to the documentation.
Exercise 3 - sigmoid
Implement the sigmoid function using numpy.
Instructions: x could now be either a real number, a vector, or a matrix. The data structures we use in numpy to represent these shapes (vectors, matrices...) are called numpy arrays. You don't need to know more for now.
For 𝑥∈ℝ𝑛, 𝑠𝑖𝑔𝑚𝑜𝑖𝑑(𝑥)=𝑠𝑖𝑔𝑚𝑜𝑖𝑑𝑥1𝑥2...𝑥𝑛=11+𝑒−𝑥111+𝑒−𝑥2...11+𝑒−𝑥𝑛(1)
# GRADED FUNCTION: sigmoid
def sigmoid(x):
"""
Compute the sigmoid of x
Arguments:
x -- A scalar or numpy array of any size
Return:
s -- sigmoid(x)
"""
# (≈ 1 line of code)
# s =
# YOUR CODE STARTS HERE
s = 1 / (1 + np.exp(-x))
# YOUR CODE ENDS HERE
return s
t_x = np.array([1, 2, 3])
print("sigmoid(t_x) = " + str(sigmoid(t_x)))
sigmoid_test(sigmoid)
1.2 - Sigmoid Gradient
As you've seen in lecture, you will need to compute gradients to optimize loss functions using backpropagation. Let's code your first gradient function.
Exercise 4 - sigmoid_derivative
Implement the function sigmoid_grad() to compute the gradient of the sigmoid function with respect to its input x. The formula is:
𝑠𝑖𝑔𝑚𝑜𝑖𝑑_𝑑𝑒𝑟𝑖𝑣𝑎𝑡𝑖𝑣𝑒(𝑥)=𝜎′(𝑥)=𝜎(𝑥)(1−𝜎(𝑥))(2)
You often code this function in two steps:
Set s to be the sigmoid of x. You might find your sigmoid(x) function useful.
Compute 𝜎′(𝑥)=𝑠(1−𝑠)
# GRADED FUNCTION: sigmoid_derivative
def sigmoid_derivative(x):
"""
Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x.
You can store the output of the sigmoid function into variables and then use it to calculate the gradient.
Arguments:
x -- A scalar or numpy array
Return:
ds -- Your computed gradient.
"""
#(≈ 2 lines of code)
# s =
# ds =
# YOUR CODE STARTS HERE
s = 1 / (1 + np.exp(-x))
ds = s * (1 - s)
# YOUR CODE ENDS HERE
return ds
t_x = np.array([1, 2, 3])
print ("sigmoid_derivative(t_x) = " + str(sigmoid_derivative(t_x)))
sigmoid_derivative_test(sigmoid_derivative)
1.3 - Reshaping arrays
Two common numpy functions used in deep learning are np.shape and np.reshape().
X.shape is used to get the shape (dimension) of a matrix/vector X.
X.reshape(...) is used to reshape X into some other dimension.
For example, in computer science, an image is represented by a 3D array of shape (𝑙𝑒𝑛𝑔𝑡ℎ,ℎ𝑒𝑖𝑔ℎ𝑡,𝑑𝑒𝑝𝑡ℎ=3). However, when you read an image as the input of an algorithm you convert it to a vector of shape (𝑙𝑒𝑛𝑔𝑡ℎ∗ℎ𝑒𝑖𝑔ℎ𝑡∗3,1). In other words, you "unroll", or reshape, the 3D array into a 1D vector.
Exercise 5 - image2vector
Implement image2vector() that takes an input of shape (length, height, 3) and returns a vector of shape (length*height*3, 1). For example, if you would like to reshape an array v of shape (a, b, c) into a vector of shape (a*b,c) you would do:
v = v.reshape((v.shape[0] * v.shape[1], v.shape[2])) # v.shape[0] = a ; v.shape[1] = b ; v.shape[2] = c
Please don't hardcode the dimensions of image as a constant. Instead look up the quantities you need with image.shape[0], etc.
You can use v = v.reshape(-1, 1). Just make sure you understand why it works.
# GRADED FUNCTION:image2vector
def image2vector(image):
"""
Argument:
image -- a numpy array of shape (length, height, depth)
Returns:
v -- a vector of shape (length*height*depth, 1)
"""
# (≈ 1 line of code)
# v =
# YOUR CODE STARTS HERE
v = image.reshape((image.shape[2] * image.shape[1] * image.shape[0], 1))
# YOUR CODE ENDS HERE
return v
# This is a 3 by 3 by 2 array, typically images will be (num_px_x, num_px_y,3) where 3 represents the RGB values
t_image = np.array([[[ 0.67826139, 0.29380381],
[ 0.90714982, 0.52835647],
[ 0.4215251 , 0.45017551]],
[[ 0.92814219, 0.96677647],
[ 0.85304703, 0.52351845],
[ 0.19981397, 0.27417313]],
[[ 0.60659855, 0.00533165],
[ 0.10820313, 0.49978937],
[ 0.34144279, 0.94630077]]])
print ("image2vector(image) = " + str(image2vector(t_image)))
image2vector_test(image2vector)
1.4 - Normalizing rows
Another common technique we use in Machine Learning and Deep Learning is to normalize our data. It often leads to a better performance because gradient descent converges faster after normalization. Here, by normalization we mean changing x to 𝑥‖𝑥‖ (dividing each row vector of x by its norm).
For example, if
𝑥=[023644](3)
then
‖𝑥‖=np.linalg.norm(x, axis=1, keepdims=True)=[556⎯⎯⎯⎯√](4)
and
𝑥_𝑛𝑜𝑟𝑚𝑎𝑙𝑖𝑧𝑒𝑑=𝑥‖𝑥‖=0256√35656√45456√(5)
Note that you can divide matrices of different sizes and it works fine: this is called broadcasting and you're going to learn about it in part 5.
With keepdims=True the result will broadcast correctly against the original x.
axis=1 means you are going to get the norm in a row-wise manner. If you need the norm in a column-wise way, you would need to set axis=0.
numpy.linalg.norm has another parameter ord where we specify the type of normalization to be done (in the exercise below you'll do 2-norm). To get familiar with the types of normalization you can visit numpy.linalg.norm
Exercise 6 - normalize_rows
Implement normalizeRows() to normalize the rows of a matrix. After applying this function to an input matrix x, each row of x should be a vector of unit length (meaning length 1).
Note: Don't try to use x /= x_norm. For the matrix division numpy must broadcast the x_norm, which is not supported by the operant /=
# GRADED FUNCTION: normalize_rows
def normalize_rows(x):
"""
Implement a function that normalizes each row of the matrix x (to have unit length).
Argument:
x -- A numpy matrix of shape (n, m)
Returns:
x -- The normalized (by row) numpy matrix. You are allowed to modify x.
"""
#(≈ 2 lines of code)
# Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)
# x_norm =
# Divide x by its norm.
# x =
# YOUR CODE STARTS HERE
x_norm = np.linalg.norm(x,ord = 2,axis=1,keepdims=True)
x = x/x_norm
# YOUR CODE ENDS HERE
return x
x = np.array([[0, 3, 4],
[1, 6, 4]])
print("normalizeRows(x) = " + str(normalize_rows(x)))
normalizeRows_test(normalize_rows)
Note: In normalize_rows(), you can try to print the shapes of x_norm and x, and then rerun the assessment. You'll find out that they have different shapes. This is normal given that x_norm takes the norm of each row of x. So x_norm has the same number of rows but only 1 column. So how did it work when you divided x by x_norm? This is called broadcasting and we'll talk about it now!
Exercise 7 - softmax
Implement a softmax function using numpy. You can think of softmax as a normalizing function used when your algorithm needs to classify two or more classes. You will learn more about softmax in the second course of this specialization.
Instructions:
for 𝑥∈ℝ1×𝑛,
𝑠𝑜𝑓𝑡𝑚𝑎𝑥(𝑥)=𝑠𝑜𝑓𝑡𝑚𝑎𝑥([𝑥1𝑥2...𝑥𝑛])=[𝑒𝑥1∑𝑗𝑒𝑥𝑗𝑒𝑥2∑𝑗𝑒𝑥𝑗...𝑒𝑥𝑛∑𝑗𝑒𝑥𝑗]
for a matrix 𝑥∈ℝ𝑚×𝑛, 𝑥𝑖𝑗 maps to the element in the 𝑖𝑡ℎ row and 𝑗𝑡ℎ column of 𝑥, thus we have:
𝑠𝑜𝑓𝑡𝑚𝑎𝑥(𝑥)=𝑠𝑜𝑓𝑡𝑚𝑎𝑥𝑥11𝑥21⋮𝑥𝑚1𝑥12𝑥22⋮𝑥𝑚2𝑥13𝑥23⋮𝑥𝑚3……⋱…𝑥1𝑛𝑥2𝑛⋮𝑥𝑚𝑛=𝑒𝑥11∑𝑗𝑒𝑥1𝑗𝑒𝑥21∑𝑗𝑒𝑥2𝑗⋮𝑒𝑥𝑚1∑𝑗𝑒𝑥𝑚𝑗𝑒𝑥12∑𝑗𝑒𝑥1𝑗𝑒𝑥22∑𝑗𝑒𝑥2𝑗⋮𝑒𝑥𝑚2∑𝑗𝑒𝑥𝑚𝑗𝑒𝑥13∑𝑗𝑒𝑥1𝑗𝑒𝑥23∑𝑗𝑒𝑥2𝑗⋮𝑒𝑥𝑚3∑𝑗𝑒𝑥𝑚𝑗……⋱…𝑒𝑥1𝑛∑𝑗𝑒𝑥1𝑗𝑒𝑥2𝑛∑𝑗𝑒𝑥2𝑗⋮𝑒𝑥𝑚𝑛∑𝑗𝑒𝑥𝑚𝑗=𝑠𝑜𝑓𝑡𝑚𝑎𝑥(first row of x)𝑠𝑜𝑓𝑡𝑚𝑎𝑥(second row of x)⋮𝑠𝑜𝑓𝑡𝑚𝑎𝑥(last row of x)
Notes: Note that later in the course, you'll see "m" used to represent the "number of training examples", and each training example is in its own column of the matrix. Also, each feature will be in its own row (each row has data for the same feature).
Softmax should be performed for all features of each training example, so softmax would be performed on the columns (once we switch to that representation later in this course).
However, in this coding practice, we're just focusing on getting familiar with Python, so we're using the common math notation 𝑚×𝑛
where 𝑚 is the number of rows and 𝑛 is the number of columns.
# GRADED FUNCTION: softmax
def softmax(x):
"""Calculates the softmax for each row of the input x.
Your code should work for a row vector and also for matrices of shape (m,n).
Argument:
x -- A numpy matrix of shape (m,n)
Returns:
s -- A numpy matrix equal to the softmax of x, of shape (m,n)
"""
#(≈ 3 lines of code)
# Apply exp() element-wise to x. Use np.exp(...).
# x_exp = ...
# Create a vector x_sum that sums each row of x_exp. Use np.sum(..., axis = 1, keepdims = True).
# x_sum = ...
# Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.
# s = ...
# YOUR CODE STARTS HERE
x_exp = np.exp(x)
x_sum = np.sum(x_exp, axis = 1, keepdims = True)
s = x_exp/x_sum
# YOUR CODE ENDS HERE
return s
t_x = np.array([[9, 2, 5, 0, 0],
[7, 5, 0, 0 ,0]])
print("softmax(x) = " + str(softmax(t_x)))
softmax_test(softmax)
Notes
If you print the shapes of x_exp, x_sum and s above and rerun the assessment cell, you will see that x_sum is of shape (2,1) while x_exp and s are of shape (2,5). x_exp/x_sum works due to python broadcasting.
Congratulations! You now have a pretty good understanding of python numpy and have implemented a few useful functions that you will be using in deep learning.
What you need to remember:
np.exp(x) works for any np.array x and applies the exponential function to every coordinate
the sigmoid function and its gradient
image2vector is commonly used in deep learning
np.reshape is widely used. In the future, you'll see that keeping your matrix/vector dimensions straight will go toward eliminating a lot of bugs.
numpy has efficient built-in functions
broadcasting is extremely useful
2 - Vectorization
In deep learning, you deal with very large datasets. Hence, a non-computationally-optimal function can become a huge bottleneck in your algorithm and can result in a model that takes ages to run. To make sure that your code is computationally efficient, you will use vectorization. For example, try to tell the difference between the following implementations of the dot/outer/elementwise product.
import time
x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]
x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]
### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ###
tic = time.process_time()
dot = 0
for i in range(len(x1)):
dot += x1[i] * x2[i]
toc = time.process_time()
print ("dot = " + str(dot) + "\n ----- Computation time = " + str(1000 * (toc - tic)) + "ms")
### CLASSIC OUTER PRODUCT IMPLEMENTATION ###
tic = time.process_time()
outer = np.zeros((len(x1), len(x2))) # we create a len(x1)*len(x2) matrix with only zeros
for i in range(len(x1)):
for j in range(len(x2)):
outer[i,j] = x1[i] * x2[j]
toc = time.process_time()
print ("outer = " + str(outer) + "\n ----- Computation time = " + str(1000 * (toc - tic)) + "ms")
### CLASSIC ELEMENTWISE IMPLEMENTATION ###
tic = time.process_time()
mul = np.zeros(len(x1))
for i in range(len(x1)):
mul[i] = x1[i] * x2[i]
toc = time.process_time()
print ("elementwise multiplication = " + str(mul) + "\n ----- Computation time = " + str(1000 * (toc - tic)) + "ms")
### CLASSIC GENERAL DOT PRODUCT IMPLEMENTATION ###
W = np.random.rand(3,len(x1)) # Random 3*len(x1) numpy array
tic = time.process_time()
gdot = np.zeros(W.shape[0])
for i in range(W.shape[0]):
for j in range(len(x1)):
gdot[i] += W[i,j] * x1[j]
toc = time.process_time()
print ("gdot = " + str(gdot) + "\n ----- Computation time = " + str(1000 * (toc - tic)) + "ms")
x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]
x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]
### VECTORIZED DOT PRODUCT OF VECTORS ###
tic = time.process_time()
dot = np.dot(x1,x2)
toc = time.process_time()
print ("dot = " + str(dot) + "\n ----- Computation time = " + str(1000 * (toc - tic)) + "ms")
### VECTORIZED OUTER PRODUCT ###
tic = time.process_time()
outer = np.outer(x1,x2)
toc = time.process_time()
print ("outer = " + str(outer) + "\n ----- Computation time = " + str(1000 * (toc - tic)) + "ms")
### VECTORIZED ELEMENTWISE MULTIPLICATION ###
tic = time.process_time()
mul = np.multiply(x1,x2)
toc = time.process_time()
print ("elementwise multiplication = " + str(mul) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
### VECTORIZED GENERAL DOT PRODUCT ###
tic = time.process_time()
dot = np.dot(W,x1)
toc = time.process_time()
print ("gdot = " + str(dot) + "\n ----- Computation time = " + str(1000 * (toc - tic)) + "ms")
As you may have noticed, the vectorized implementation is much cleaner and more efficient. For bigger vectors/matrices, the differences in running time become even bigger.
Note that np.dot() performs a matrix-matrix or matrix-vector multiplication. This is different from np.multiply() and the * operator (which is equivalent to .* in Matlab/Octave), which performs an element-wise multiplication.
2.1 Implement the L1 and L2 loss functions
Exercise 8 - L1
Implement the numpy vectorized version of the L1 loss. You may find the function abs(x) (absolute value of x) useful.
Reminder:
The loss is used to evaluate the performance of your model. The bigger your loss is, the more different your predictions (𝑦̂ ) are from the true values (𝑦). In deep learning, you use optimization algorithms like Gradient Descent to train your model and to minimize the cost.
L1 loss is defined as:
𝐿1(𝑦̂ ,𝑦)=∑𝑖=0𝑚−1|𝑦(𝑖)−𝑦̂ (𝑖)|(6)
# GRADED FUNCTION: L1
def L1(yhat, y):
"""
Arguments:
yhat -- vector of size m (predicted labels)
y -- vector of size m (true labels)
Returns:
loss -- the value of the L1 loss function defined above
"""
#(≈ 1 line of code)
# loss =
# YOUR CODE STARTS HERE
loss = sum(abs(y-yhat))
# YOUR CODE ENDS HERE
return loss
yhat = np.array([.9, 0.2, 0.1, .4, .9])
y = np.array([1, 0, 0, 1, 1])
print("L1 = " + str(L1(yhat, y)))
L1_test(L1)
Exercise 9 - L2
Implement the numpy vectorized version of the L2 loss. There are several way of implementing the L2 loss but you may find the function np.dot() useful. As a reminder, if 𝑥=[𝑥1,𝑥2,...,𝑥𝑛], then np.dot(x,x) = ∑𝑛𝑗=0𝑥2𝑗.
L2 loss is defined as
𝐿2(𝑦̂ ,𝑦)=∑𝑖=0𝑚−1(𝑦(𝑖)−𝑦̂ (𝑖))2(7)
# GRADED FUNCTION: L2
def L2(yhat, y):
"""
Arguments:
yhat -- vector of size m (predicted labels)
y -- vector of size m (true labels)
Returns:
loss -- the value of the L2 loss function defined above
"""
#(≈ 1 line of code)
# loss = ...
# YOUR CODE STARTS HERE
loss = sum((y-yhat)**2)
# YOUR CODE ENDS HERE
return loss
# GRADED FUNCTION: L2
def L2(yhat, y):
"""
Arguments:
yhat -- vector of size m (predicted labels)
y -- vector of size m (true labels)
Returns:
loss -- the value of the L2 loss function defined above
"""
#(≈ 1 line of code)
# loss = ...
# YOUR CODE STARTS HERE
loss = sum((y-yhat)**2)
# YOUR CODE ENDS HERE
return loss
yhat = np.array([.9, 0.2, 0.1, .4, .9])
y = np.array([1, 0, 0, 1, 1])
print("L2 = " + str(L2(yhat, y)))
L2_test(L2)
Congratulations on completing this assignment. We hope that this little warm-up exercise helps you in the future assignments, which will be more exciting and interesting!
What to remember:
Vectorization is very important in deep learning. It provides computational efficiency and clarity.
You have reviewed the L1 and L2 loss.
You are familiar with many numpy functions such as np.sum, np.dot, np.multiply, np.maximum, etc...