Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/C1 - Neural Networks and Deep Learning/Week 2/Python Basics with Numpy/Python_Basics_With_Numpy_v3a.ipynb
Views: 4804
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 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.
Do not modify the (# GRADED FUNCTION [function name]) comment in some cells. Your work would not be graded if you change this. Each cell containing that comment should only contain one function.
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!
Updates to Assignment
This is version 3a of the notebook.
If you were working on a previous version
If you were already working on version "3", you'll find your original work in the file directory.
To reach the file directory, click on the "Coursera" icon in the top left of this notebook.
Please still use the most recent notebook to submit your assignment.
List of Updates
softmax section has a comment to clarify the use of "m" later in the course
softmax function specifies (m,n) matrix dimensions to match the notation in the preceding diagram (instead of n,m)
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 ### START CODE HERE ### and ### END CODE HERE ### comments. 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: Set test to "Hello World"
in the cell below to print "Hello World" and run the two cells below.
Expected output: test: Hello World
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: Build a function that returns the sigmoid of a real number x. Use math.exp(x) for the exponential function.
Reminder: 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().
Expected Output:
** basic_sigmoid(3) ** | 0.9525741268224334 |
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.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-8ccefa5bf989> in <module>
1 ### One reason why we use "numpy" instead of "math" in Deep Learning ###
2 x = [1, 2, 3]
----> 3 basic_sigmoid(x) # you will see this give an error when you run it, because x is a vector.
<ipython-input-5-a94180fb1694> in basic_sigmoid(x)
15
16 ### START CODE HERE ### (≈ 1 line of code)
---> 17 s = 1/(1+math.exp(-x))
18 ### END CODE HERE ###
19
TypeError: bad operand type for unary -: 'list'
In fact, if is a row vector then will apply the exponential function to every element of x. The output will thus be:
Furthermore, if x is a vector, then a Python operation such as or will output s as a vector of the same size as x.
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: 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.
Expected Output:
**sigmoid([1,2,3])** | array([ 0.73105858, 0.88079708, 0.95257413]) |
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: Implement the function sigmoid_grad() to compute the gradient of the sigmoid function with respect to its input x. The formula is: 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
Expected Output:
**sigmoid_derivative([1,2,3])** | [ 0.19661193 0.10499359 0.04517666] |
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 . However, when you read an image as the input of an algorithm you convert it to a vector of shape . In other words, you "unroll", or reshape, the 3D array into a 1D vector.
Exercise: 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:
Please don't hardcode the dimensions of image as a constant. Instead look up the quantities you need with
image.shape[0]
, etc.
Expected Output:
**image2vector(image)** | [[ 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]] |
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 then and 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.
Exercise: 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).
Expected Output:
**normalizeRows(x)** | [[ 0. 0.6 0.8 ] [ 0.13736056 0.82416338 0.54944226]] |
Note: In normalizeRows(), 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!
1.5 - Broadcasting and the softmax function
A very important concept to understand in numpy is "broadcasting". It is very useful for performing mathematical operations between arrays of different shapes. For the full details on broadcasting, you can read the official broadcasting documentation.
Exercise: 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:
ParseError: KaTeX parse error: Unexpected end of input in a macro argument, expected '}' at end of input: …es n} \text{, x_{ij}i^{th}j^{th}xParseError: KaTeX parse error: Expected 'EOF', got '}' at position 17: … thus we have: }̲
Note
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.
Expected Output:
[ 8.78679856e-01 1.18916387e-01 8.01252314e-04 8.01252314e-04 8.01252314e-04]]
Note:
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.
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.
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: 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:
Expected Output:
**L1** | 1.1 |
Exercise: 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 , then np.dot(x,x)
= .
L2 loss is defined as
Expected Output:
**L2** | 0.43 |
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!