吳恩達深度學習筆記 第二章作業1

 2023-12-25 阅读 27 评论 0

摘要:coursea鏈接:https://www.coursera.org/learn/neural-networks-deep-learning/notebook/Zh0CU/python-basics-with-numpy-optionalhttps://www.coursera.org/learn/neural-networks-deep-learning/notebook/Zh0CU/python-basics-with-numpy-optional Python Basics with Nump

coursea鏈接:https://www.coursera.org/learn/neural-networks-deep-learning/notebook/Zh0CU/python-basics-with-numpy-optionalhttps://www.coursera.org/learn/neural-networks-deep-learning/notebook/Zh0CU/python-basics-with-numpy-optional

  • 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!

    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.

    In?[6]:
    ### START CODE HERE ### (≈ 1 line of code)
    test ="Hello World"
    ### END CODE HERE ###
    In?[7]:
    print ("test: " + test)
    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)=11+e?xsigmoid(x)=11+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().

    In?[8]:
    # GRADED FUNCTION: basic_sigmoid
    ?
    import math
    ?
    def basic_sigmoid(x):
        """
        Compute sigmoid of x.
    ?
        Arguments:
        x -- A scalar
     
        Return:
        s -- sigmoid(x)
        """
       
        ### START CODE HERE ### (≈ 1 line of code)
        s = 1/(1+math.exp(-x))
        ### END CODE HERE ###
        
        return s
    In?[9]:
    basic_sigmoid(3)
    Out[9]:
    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.

    In?[?]:
    ### One reason why we use "numpy" instead of "math" in Deep Learning ###
    x = [1, 2, 3]
    basic_sigmoid(x) # you will see this give an error when you run it, because x is a vector.

    In fact, if?x=(x1,x2,...,xn)x=(x1,x2,...,xn)?is a row vector then?np.exp(x)np.exp(x)?will apply the exponential function to every element of x. The output will thus be:?np.exp(x)=(ex1,ex2,...,exn)np.exp(x)=(ex1,ex2,...,exn)

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

    Furthermore, if x is a vector, then a Python operation such as?s=x+3s=x+3?or?s=1xs=1x?will output s as a vector of the same size as x.

    In?[47]:
    # example of vector operation
    x = np.array([1, 2, 3])
    print (x + 3)
    [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.

    For?x?n,?sigmoid(x)=sigmoidx1x2...xn=11+e?x111+e?x2...11+e?xn(1)(1)For?x∈Rn,?sigmoid(x)=sigmoid(x1x2...xn)=(11+e?x111+e?x2...11+e?xn)

    ?

    In?[4]:
    # GRADED FUNCTION: sigmoid
    ?
    import numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function()
    ?
    def sigmoid(x):
        """
        Compute the sigmoid of x
    ?
        Arguments:
        x -- A scalar or numpy array of any size
    ?
        Return:
        s -- sigmoid(x)
        """
        
        ### START CODE HERE ### (≈ 1 line of code)
        s = 1/(1+np.exp(-x))
        ### END CODE HERE ###
        
        return s
    In?[5]:
    x = np.array([1, 2, 3])
    sigmoid(x)
    print(sigmoid(x))
    [ 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)=σ(x)=σ(x)(1?σ(x))(2)(2)sigmoid_derivative(x)=σ′(x)=σ(x)(1?σ(x))
    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?σ(x)=s(1?s)σ′(x)=s(1?s)
    In?[6]:
    # 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.
        """
        
        ### START CODE HERE ### (≈ 2 lines of code)
        s =1/(1+np.exp(-x))
        ds =s*(1-s)
        ### END CODE HERE ###
        
        return ds
    In?[7]:
    ?
    x = np.array([1, 2, 3])
    print (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)(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)(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:

    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.
    In?[17]:
    # 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)
        """
        
        ### START CODE HERE ### (≈ 1 line of code)
        v = image.reshape((image.shape[0]*image.shape[1]*image.shape[2],1))
        ### END CODE HERE ###
        
        return v
    In?[18]:
    # 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
    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(image)))
    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]]
    

    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?xxx∥x∥?(dividing each row vector of x by its norm).

    For example, if

    x=[023644](3)(3)x=[034264]
    then
    x=np.linalg.norm(x,axis=1,keepdims=True)=[556????√](4)(4)∥x∥=np.linalg.norm(x,axis=1,keepdims=True)=[556]
    and
    x_normalized=xx=0256√35656√45456√(5)(5)x_normalized=x∥x∥=[03545256656456]
    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).

    In?[26]:
    # GRADED FUNCTION: normalizeRows
    ?
    def normalizeRows(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.
        """
        
        ### START CODE HERE ### (≈ 2 lines of code)
        # Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)
        x_norm = np.linalg.norm(x,ord=2,axis=1,keepdims=True)
        
        # Divide x by its norm.
        x = x/x_norm
        ### END CODE HERE ###
    ?
        return x
    In?[27]:
    x = np.array([
        [0, 3, 4],
        [1, 6, 4]])
    print("normalizeRows(x) = " + str(normalizeRows(x)))
    normalizeRows(x) = [[ 0.          0.6         0.8       ][ 0.13736056  0.82416338  0.54944226]]
    

    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:

    • for?x?1×n,?softmax(x)=softmax([x1x2...xn])=[ex1jexjex2jexj...exnjexj]for?x∈R1×n,?softmax(x)=softmax([x1x2...xn])=[ex1∑jexjex2∑jexj...exn∑jexj]

    • for a matrix?x?m×n,?xij?maps to the element in the?ith?row and?jth?column of?x, thus we have:?for a matrix?x∈Rm×n,?xij?maps to the element in the?ith?row and?jth?column of?x, thus we have:?

      softmax(x)=softmaxx11x21?xm1x12x22?xm2x13x23?xm3?x1nx2n?xmn=ex11jex1jex21jex2j?exm1jexmj

轉載于:https://www.cnblogs.com/Dar-/p/9345570.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/194949.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息