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.

  1. ### START CODE HERE ### (≈ 1 line of code)
  2. test = 'Hello World'
  3. ### END CODE HERE ###
  1. print ("test: " + test)
  1. test: Hello World

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: Build a function that returns the sigmoid of a real number x. Use math.exp(x) for the exponential function.

Reminder:

\(sigmoid(x) = \frac{1}{1+e^{-x}}\) 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().

  1. # GRADED FUNCTION: basic_sigmoid
  2. import math
  3. def basic_sigmoid(x):
  4. """
  5. Compute sigmoid of x.
  6. Arguments:
  7. x -- A scalar
  8. Return:
  9. s -- sigmoid(x)
  10. """
  11. ### START CODE HERE ### (≈ 1 line of code)
  12. s = 1 / ( 1 + math.exp(-x))
  13. ### END CODE HERE ###
  14. return s
  1. basic_sigmoid(3)
  1. 0.9525741268224334

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.

  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.
  1. ---------------------------------------------------------------------------
  2. TypeError Traceback (most recent call last)
  3. <ipython-input-12-2e11097d6860> in <module>()
  4. 1 ### One reason why we use "numpy" instead of "math" in Deep Learning ###
  5. 2 x = [1, 2, 3]
  6. ----> 3 basic_sigmoid(x) # you will see this give an error when you run it, because x is a vector.
  7. <ipython-input-10-c0169f99e27b> in basic_sigmoid(x)
  8. 15
  9. 16 ### START CODE HERE ### (≈ 1 line of code)
  10. ---> 17 s = 1 / ( 1 + math.exp(-x))
  11. 18 ### END CODE HERE ###
  12. 19
  13. TypeError: bad operand type for unary -: 'list'

In fact, if $ x = (x_1, x_2, ..., x_n)$ 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})\)

  1. import numpy as np
  2. # example of np.exp
  3. x = np.array([1, 2, 3])
  4. print(np.exp(x)) # result is (exp(1), exp(2), exp(3))
  1. [ 2.71828183 7.3890561 20.08553692]

Furthermore, if x is a vector, then a Python operation such as \(s = x + 3\) or \(s = \frac{1}{x}\) will output s as a vector of the same size as x.

  1. # example of vector operation
  2. x = np.array([1, 2, 3])
  3. print (x + 3)
  1. [4 5 6]

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.

\[ \text{For } x \in \mathbb{R}^n \text{, } sigmoid(x) = sigmoid\begin{pmatrix}
x_1 \\
x_2 \\
... \\
x_n \\
\end{pmatrix} = \begin{pmatrix}
\frac{1}{1+e^{-x_1}} \\
\frac{1}{1+e^{-x_2}} \\
... \\
\frac{1}{1+e^{-x_n}} \\
\end{pmatrix}\tag{1} \]
  1. # GRADED FUNCTION: sigmoid
  2. import numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function()
  3. def sigmoid(x):
  4. """
  5. Compute the sigmoid of x
  6. Arguments:
  7. x -- A scalar or numpy array of any size
  8. Return:
  9. s -- sigmoid(x)
  10. """
  11. ### START CODE HERE ### (≈ 1 line of code)
  12. s = 1 / ( 1 + np.exp(-x))
  13. ### END CODE HERE ###
  14. return s
  1. x = np.array([1, 2, 3])
  2. sigmoid(x)
  1. array([ 0.73105858, 0.88079708, 0.95257413])

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: $$sigmoid_derivative(x) = \sigma'(x) = \sigma(x) (1 - \sigma(x))\tag{2}$$

You often code this function in two steps:

  1. Set s to be the sigmoid of x. You might find your sigmoid(x) function useful.
  2. Compute \(\sigma'(x) = s(1-s)\)
  1. # GRADED FUNCTION: sigmoid_derivative
  2. def sigmoid_derivative(x):
  3. """
  4. Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x.
  5. You can store the output of the sigmoid function into variables and then use it to calculate the gradient.
  6. Arguments:
  7. x -- A scalar or numpy array
  8. Return:
  9. ds -- Your computed gradient.
  10. """
  11. ### START CODE HERE ### (≈ 2 lines of code)
  12. s = sigmoid(x)
  13. ds = s * (1-s)
  14. ### END CODE HERE ###
  15. return ds
  1. x = np.array([1, 2, 3])
  2. print ("sigmoid_derivative(x) = " + str(sigmoid_derivative(x)))
  1. sigmoid_derivative(x) = [ 0.19661193 0.10499359 0.04517666]

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 \((length, height, depth = 3)\). However, when you read an image as the input of an algorithm you convert it to a vector of shape \((length*height*3, 1)\). 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:

  1. 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.
  1. # GRADED FUNCTION: image2vector
  2. def image2vector(image):
  3. """
  4. Argument:
  5. image -- a numpy array of shape (length, height, depth)
  6. Returns:
  7. v -- a vector of shape (length*height*depth, 1)
  8. """
  9. ### START CODE HERE ### (≈ 1 line of code)
  10. v = image.reshape((image.shape[0] * image.shape[1] * image.shape[2]), 1)
  11. ### END CODE HERE ###
  12. return v
  1. # 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
  2. image = np.array([[[ 0.67826139, 0.29380381],
  3. [ 0.90714982, 0.52835647],
  4. [ 0.4215251 , 0.45017551]],
  5. [[ 0.92814219, 0.96677647],
  6. [ 0.85304703, 0.52351845],
  7. [ 0.19981397, 0.27417313]],
  8. [[ 0.60659855, 0.00533165],
  9. [ 0.10820313, 0.49978937],
  10. [ 0.34144279, 0.94630077]]])
  11. print ("image2vector(image) = " + str(image2vector(image)))
  1. image2vector(image) = [[ 0.67826139]
  2. [ 0.29380381]
  3. [ 0.90714982]
  4. [ 0.52835647]
  5. [ 0.4215251 ]
  6. [ 0.45017551]
  7. [ 0.92814219]
  8. [ 0.96677647]
  9. [ 0.85304703]
  10. [ 0.52351845]
  11. [ 0.19981397]
  12. [ 0.27417313]
  13. [ 0.60659855]
  14. [ 0.00533165]
  15. [ 0.10820313]
  16. [ 0.49978937]
  17. [ 0.34144279]
  18. [ 0.94630077]]

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 $ \frac{x}{| x|} $ (dividing each row vector of x by its norm).

For example, if $$x =

\begin{bmatrix}

0 & 3 & 4 \

2 & 6 & 4 \

\end{bmatrix}\tag{3}$$ then $$| x| = np.linalg.norm(x, axis = 1, keepdims = True) = \begin{bmatrix}

5 \

\sqrt{56} \

\end{bmatrix}\tag{4} $$and $$ x_normalized = \frac{x}{| x|} = \begin{bmatrix}

0 & \frac{3}{5} & \frac{4}{5} \

\frac{2}{\sqrt{56}} & \frac{6}{\sqrt{56}} & \frac{4}{\sqrt{56}} \

\end{bmatrix}\tag{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.

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).

  1. # GRADED FUNCTION: normalizeRows
  2. def normalizeRows(x):
  3. """
  4. Implement a function that normalizes each row of the matrix x (to have unit length).
  5. Argument:
  6. x -- A numpy matrix of shape (n, m)
  7. Returns:
  8. x -- The normalized (by row) numpy matrix. You are allowed to modify x.
  9. """
  10. ### START CODE HERE ### (≈ 2 lines of code)
  11. # Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)
  12. x_norm = np.linalg.norm(x, axis = 1, keepdims = True)
  13. # Divide x by its norm.
  14. x = x / x_norm
  15. ### END CODE HERE ###
  16. return x
  1. x = np.array([
  2. [0, 3, 4],
  3. [1, 6, 4]])
  4. print("normalizeRows(x) = " + str(normalizeRows(x)))
  1. normalizeRows(x) = [[ 0. 0.6 0.8 ]
  2. [ 0.13736056 0.82416338 0.54944226]]

Expected Output:

  1. <tr>
  2. <td> **normalizeRows(x)** </td>
  3. <td> [[ 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:

  • $ \text{for } x \in \mathbb{R}^{1\times n} \text{, } softmax(x) = softmax(\begin{bmatrix}

    x_1 &&

    x_2 &&

    ... &&

    x_n

    \end{bmatrix}) = \begin{bmatrix}

    \frac{e{x_1}}{\sum_{j}e{x_j}} &&

    \frac{e{x_2}}{\sum_{j}e{x_j}} &&

    ... &&

    \frac{e{x_n}}{\sum_{j}e{x_j}}

    \end{bmatrix} $

  • $\text{for a matrix } x \in \mathbb{R}^{m \times n} \text{, \(x_{ij}\) maps to the element in the \(i^{th}\) row and \(j^{th}\) column of \(x\), thus we have: }$ $$softmax(x) = softmax\begin{bmatrix}

    x_{11} & x_{12} & x_{13} & \dots & x_{1n} \

    x_{21} & x_{22} & x_{23} & \dots & x_{2n} \

    \vdots & \vdots & \vdots & \ddots & \vdots \

    x_{m1} & x_{m2} & x_{m3} & \dots & x_{mn}

    \end{bmatrix} = \begin{bmatrix}

    \frac{e{x_{11}}}{\sum_{j}e{x_{1j}}} & \frac{e{x_{12}}}{\sum_{j}e{x_{1j}}} & \frac{e{x_{13}}}{\sum_{j}e{x_{1j}}} & \dots & \frac{e{x_{1n}}}{\sum_{j}e{x_{1j}}} \

    \frac{e{x_{21}}}{\sum_{j}e{x_{2j}}} & \frac{e{x_{22}}}{\sum_{j}e{x_{2j}}} & \frac{e{x_{23}}}{\sum_{j}e{x_{2j}}} & \dots & \frac{e{x_{2n}}}{\sum_{j}e{x_{2j}}} \

    \vdots & \vdots & \vdots & \ddots & \vdots \

    \frac{e{x_{m1}}}{\sum_{j}e{x_{mj}}} & \frac{e{x_{m2}}}{\sum_{j}e{x_{mj}}} & \frac{e{x_{m3}}}{\sum_{j}e{x_{mj}}} & \dots & \frac{e{x_{mn}}}{\sum_{j}e{x_{mj}}}

    \end{bmatrix} = \begin{pmatrix}

    softmax\text{(first row of x)} \

    softmax\text{(second row of x)} \

    ... \

    softmax\text{(last row of x)} \

    \end{pmatrix} $$

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 \(m \times n\)

where \(m\) is the number of rows and \(n\) is the number of columns.

  1. # GRADED FUNCTION: softmax
  2. def softmax(x):
  3. """Calculates the softmax for each row of the input x.
  4. Your code should work for a row vector and also for matrices of shape (m,n).
  5. Argument:
  6. x -- A numpy matrix of shape (m,n)
  7. Returns:
  8. s -- A numpy matrix equal to the softmax of x, of shape (m,n)
  9. """
  10. ### START CODE HERE ### (≈ 3 lines of code)
  11. # Apply exp() element-wise to x. Use np.exp(...).
  12. x_exp = np.exp(x)
  13. # Create a vector x_sum that sums each row of x_exp. Use np.sum(..., axis = 1, keepdims = True).
  14. x_sum = np.sum(x_exp, axis = 1, keepdims = True)
  15. # Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.
  16. s = x_exp / x_sum
  17. ### END CODE HERE ###
  18. return s
  1. x = np.array([
  2. [9, 2, 5, 0, 0],
  3. [7, 5, 0, 0 ,0]])
  4. print("softmax(x) = " + str(softmax(x)))
  1. softmax(x) = [[ 9.80897665e-01 8.94462891e-04 1.79657674e-02 1.21052389e-04
  2. 1.21052389e-04]
  3. [ 8.78679856e-01 1.18916387e-01 8.01252314e-04 8.01252314e-04
  4. 8.01252314e-04]]

Expected Output:

  1. <tr>
  2. <td> **softmax(x)** </td>
  3. <td> [[ 9.80897665e-01 8.94462891e-04 1.79657674e-02 1.21052389e-04
  4. 1.21052389e-04]

[ 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.

**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.

  1. import time
  2. x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]
  3. x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]
  4. ### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ###
  5. tic = time.process_time()
  6. dot = 0
  7. for i in range(len(x1)):
  8. dot+= x1[i]*x2[i]
  9. toc = time.process_time()
  10. print ("dot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
  11. ### CLASSIC OUTER PRODUCT IMPLEMENTATION ###
  12. tic = time.process_time()
  13. outer = np.zeros((len(x1),len(x2))) # we create a len(x1)*len(x2) matrix with only zeros
  14. for i in range(len(x1)):
  15. for j in range(len(x2)):
  16. outer[i,j] = x1[i]*x2[j]
  17. toc = time.process_time()
  18. print ("outer = " + str(outer) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
  19. ### CLASSIC ELEMENTWISE IMPLEMENTATION ###
  20. tic = time.process_time()
  21. mul = np.zeros(len(x1))
  22. for i in range(len(x1)):
  23. mul[i] = x1[i]*x2[i]
  24. toc = time.process_time()
  25. print ("elementwise multiplication = " + str(mul) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
  26. ### CLASSIC GENERAL DOT PRODUCT IMPLEMENTATION ###
  27. W = np.random.rand(3,len(x1)) # Random 3*len(x1) numpy array
  28. tic = time.process_time()
  29. gdot = np.zeros(W.shape[0])
  30. for i in range(W.shape[0]):
  31. for j in range(len(x1)):
  32. gdot[i] += W[i,j]*x1[j]
  33. toc = time.process_time()
  34. print ("gdot = " + str(gdot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
  1. dot = 278
  2. ----- Computation time = 0.08494100000011606ms
  3. outer = [[ 81. 18. 18. 81. 0. 81. 18. 45. 0. 0. 81. 18. 45. 0.
  4. 0.]
  5. [ 18. 4. 4. 18. 0. 18. 4. 10. 0. 0. 18. 4. 10. 0.
  6. 0.]
  7. [ 45. 10. 10. 45. 0. 45. 10. 25. 0. 0. 45. 10. 25. 0.
  8. 0.]
  9. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  10. 0.]
  11. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  12. 0.]
  13. [ 63. 14. 14. 63. 0. 63. 14. 35. 0. 0. 63. 14. 35. 0.
  14. 0.]
  15. [ 45. 10. 10. 45. 0. 45. 10. 25. 0. 0. 45. 10. 25. 0.
  16. 0.]
  17. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  18. 0.]
  19. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  20. 0.]
  21. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  22. 0.]
  23. [ 81. 18. 18. 81. 0. 81. 18. 45. 0. 0. 81. 18. 45. 0.
  24. 0.]
  25. [ 18. 4. 4. 18. 0. 18. 4. 10. 0. 0. 18. 4. 10. 0.
  26. 0.]
  27. [ 45. 10. 10. 45. 0. 45. 10. 25. 0. 0. 45. 10. 25. 0.
  28. 0.]
  29. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  30. 0.]
  31. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  32. 0.]]
  33. ----- Computation time = 0.3594250000000798ms
  34. elementwise multiplication = [ 81. 4. 10. 0. 0. 63. 10. 0. 0. 0. 81. 4. 25. 0. 0.]
  35. ----- Computation time = 0.10687999999992037ms
  36. gdot = [ 23.47038942 24.22704105 14.87247453]
  37. ----- Computation time = 0.14643100000011344ms
  1. x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]
  2. x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]
  3. ### VECTORIZED DOT PRODUCT OF VECTORS ###
  4. tic = time.process_time()
  5. dot = np.dot(x1,x2)
  6. toc = time.process_time()
  7. print ("dot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
  8. ### VECTORIZED OUTER PRODUCT ###
  9. tic = time.process_time()
  10. outer = np.outer(x1,x2)
  11. toc = time.process_time()
  12. print ("outer = " + str(outer) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
  13. ### VECTORIZED ELEMENTWISE MULTIPLICATION ###
  14. tic = time.process_time()
  15. mul = np.multiply(x1,x2)
  16. toc = time.process_time()
  17. print ("elementwise multiplication = " + str(mul) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
  18. ### VECTORIZED GENERAL DOT PRODUCT ###
  19. tic = time.process_time()
  20. dot = np.dot(W,x1)
  21. toc = time.process_time()
  22. print ("gdot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
  1. dot = 278
  2. ----- Computation time = 0.08206199999993835ms
  3. outer = [[81 18 18 81 0 81 18 45 0 0 81 18 45 0 0]
  4. [18 4 4 18 0 18 4 10 0 0 18 4 10 0 0]
  5. [45 10 10 45 0 45 10 25 0 0 45 10 25 0 0]
  6. [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  7. [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  8. [63 14 14 63 0 63 14 35 0 0 63 14 35 0 0]
  9. [45 10 10 45 0 45 10 25 0 0 45 10 25 0 0]
  10. [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  11. [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  12. [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  13. [81 18 18 81 0 81 18 45 0 0 81 18 45 0 0]
  14. [18 4 4 18 0 18 4 10 0 0 18 4 10 0 0]
  15. [45 10 10 45 0 45 10 25 0 0 45 10 25 0 0]
  16. [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  17. [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]
  18. ----- Computation time = 0.07873699999993988ms
  19. elementwise multiplication = [81 4 10 0 0 63 10 0 0 0 81 4 25 0 0]
  20. ----- Computation time = 0.06006600000008078ms
  21. gdot = [ 23.47038942 24.22704105 14.87247453]
  22. ----- Computation time = 0.6421670000000823ms

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 ($ \hat{y} \() are from the true values (\)y$). In deep learning, you use optimization algorithms like Gradient Descent to train your model and to minimize the cost.
  • L1 loss is defined as:
\[\begin{align*} & L_1(\hat{y}, y) = \sum_{i=0}^m|y^{(i)} - \hat{y}^{(i)}| \end{align*}\tag{6}
\]
  1. # GRADED FUNCTION: L1
  2. def L1(yhat, y):
  3. """
  4. Arguments:
  5. yhat -- vector of size m (predicted labels)
  6. y -- vector of size m (true labels)
  7. Returns:
  8. loss -- the value of the L1 loss function defined above
  9. """
  10. ### START CODE HERE ### (≈ 1 line of code)
  11. loss = np.sum(abs(yhat - y))
  12. ### END CODE HERE ###
  13. return loss
  1. yhat = np.array([.9, 0.2, 0.1, .4, .9])
  2. y = np.array([1, 0, 0, 1, 1])
  3. print("L1 = " + str(L1(yhat,y)))
  1. L1 = 1.1

Expected Output:

  1. <tr>
  2. <td> **L1** </td>
  3. <td> 1.1 </td>
  4. </tr>

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 \(x = [x_1, x_2, ..., x_n]\), then np.dot(x,x) = \(\sum_{j=0}^n x_j^{2}\).

  • L2 loss is defined as $$\begin{align} & L_2(\hat{y},y) = \sum_{i=0}m(y{(i)} - \hat{y}{(i)})2 \end{align}\tag{7}$$
  1. # GRADED FUNCTION: L2
  2. def L2(yhat, y):
  3. """
  4. Arguments:
  5. yhat -- vector of size m (predicted labels)
  6. y -- vector of size m (true labels)
  7. Returns:
  8. loss -- the value of the L2 loss function defined above
  9. """
  10. ### START CODE HERE ### (≈ 1 line of code)
  11. loss = np.dot(yhat - y, yhat - y)
  12. ### END CODE HERE ###
  13. return loss
  1. yhat = np.array([.9, 0.2, 0.1, .4, .9])
  2. y = np.array([1, 0, 0, 1, 1])
  3. print("L2 = " + str(L2(yhat,y)))
  1. L2 = 0.43

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!

**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...

Python Basics with numpy (optional)的更多相关文章

  1. 课程一(Neural Networks and Deep Learning),第二周(Basics of Neural Network programming)—— 3、Python Basics with numpy (optional)

    Python Basics with numpy (optional)Welcome to your first (Optional) programming exercise of the deep ...

  2. Python Basics with Numpy

    Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if yo ...

  3. 给深度学习入门者的Python快速教程 - numpy和Matplotlib篇

    始终无法有效把word排版好的粘贴过来,排版更佳版本请见知乎文章: https://zhuanlan.zhihu.com/p/24309547 实在搞不定博客园的排版,排版更佳的版本在: 给深度学习入 ...

  4. 利用Python进行数据分析——Numpy基础:数组和矢量计算

    利用Python进行数据分析--Numpy基础:数组和矢量计算 ndarry,一个具有矢量运算和复杂广播能力快速节省空间的多维数组 对整组数据进行快速运算的标准数学函数,无需for-loop 用于读写 ...

  5. python及pandas,numpy等知识点技巧点学习笔记

    python和java,.net,php web平台交互最好使用web通信方式,不要使用Jypython,IronPython,这样的好处是能够保持程序模块化,解耦性好 python允许使用'''.. ...

  6. Python笔记 #06# NumPy Basis & Subsetting NumPy Arrays

    原始的 Python list 虽然很好用,但是不具备能够“整体”进行数学运算的性质,并且速度也不够快(按照视频上的说法),而 Numpy.array 恰好可以弥补这些缺陷. 初步应用就是“整体数学运 ...

  7. Python中的Numpy、SciPy、MatPlotLib安装与配置

    Python安装完Numpy,SciPy和MatplotLib后,可以成为非常犀利的科研利器.网上关于这三个库的安装都写得非常不错,但是大部分人遇到的问题并不是如何安装,而是安装好后因为配置不当,在使 ...

  8. The Basics of Numpy

    在python语言中,Tensorflow中的tensor返回的是numpy ndarray对象. Numpy的主要对象是齐次多维数组,即一个元素表(通常是数字),所有的元素具有相同类型,可以通过有序 ...

  9. Python 机器学习库 NumPy 教程

    0 Numpy简单介绍 Numpy是Python的一个科学计算的库,提供了矩阵运算的功能,其一般与Scipy.matplotlib一起使用.其实,list已经提供了类似于矩阵的表示形式,不过numpy ...

随机推荐

  1. LeetCode392. 判断子序列

    原题链接 1 class Solution: 2 def isSubsequence(self, s: str, t: str) -> bool: 3 lens,lent = len(s),le ...

  2. 阿里巴巴Druid,轻松实现MySQL数据库连接加密!

    为什么要加密? 现在的开发习惯,无论是公司的项目还是个人的项目,都会选择将源码上传到 Git 服务器(GitHub.Gitee 或是自建服务器),但只要将源码提交到公网服务器就会存在源码泄漏的风险,而 ...

  3. 如何进BAT,有了这个篇面试秘籍,成功率高达80%!!(附资料)

    多年前自己刚来北京找工作的时候,面了一个星期 面了七八家公司才拿到一个offer.而上次跳槽面了不到10家公司基本全过而且都给到了期望的薪资,本来自己在面试前没想到能够这么顺利,回想起来还是自己准备的 ...

  4. 基于Hi3559AV100 RFCN实现细节解析-(1)VGS初介绍

    下面随笔系列将对Hi3559AV100 RFCN实现细节进行解析,因为RFCN用到了VGS加框,因此本篇随笔将给出VGS视频图像子系统的具体说明,便于后面RFCN的细节实现说明. VGS 是视频图形子 ...

  5. C语言相关的基础字符串函数

    C语言中没有专门的字符串类型,所以就用字符数组和字符指针形式表示 1 char arr[]="abcdef"; //字符数组表示的字符串 2 char*arr="abce ...

  6. C#无损压缩图片

    /// <summary> /// 根据指定尺寸得到按比例缩放的尺寸,返回true表示以更改尺寸 /// </summary> /// <param name=" ...

  7. java将数据生成csv文件

    1,httpRequest接口触发进程[或者可以换成其他方式触发] /** * 出入库生成CSV文件 * @param req * @param params * @return */@Request ...

  8. springmvc redis @Cacheable扩展(一)

    springmvc 中有自带的cache处理模块,可以是方法级别的缓存处理,那么在实际使用中,很可能自己造轮子,因为实际中永远会有更奇怪的需求点.比如: 1 清除缓存时候,能模糊的进行删除 2 针对不 ...

  9. 测试工程师Docker进阶

    学习整理来源 B站 狂神说Java https://space.bilibili.com/95256449/ 四.docker镜像 1.镜像是什么 镜像是一种轻量级.可执行的独立软件包,用来打包软件运 ...

  10. 前端性能监控之performance

    如果我们想要对一个网页进行性能监控,那么使用window.performance是一个比较好的选择. 我们通过window.performance可以获取到用户访问一个页面的每个阶段的精确时间,从而对 ...