Wu deeplearning.ai C1W2 assignment2_1

1-Building basic function 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.

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

这边主要是比较了math.exp()于np.exp(),之间的区别。np.exp()具有boardcasting的功能,可以对向量矩阵进行运算。

Answer:

# 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

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.

                                                                           x\in \mathbb{R}^{n},sigmoid(x)=\begin{bmatrix} \frac{1}{1+e^{-x_{1}}}\\ \frac{1}{1+e^{-x_{2}}} \\ ... \\ \frac{1}{1+e^{-x_{n}}} \end{bmatrix}

Answer

# 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

1.2-sigmoid gradient

这边主要是简单对sigmoid函数求导计算没什么好说的,skip;

Answer

# 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 = sigmoid(x)
    ds=s*(1-s)
    ### END CODE HERE ###
    
    return ds

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. 

利用reshape来改变原来矩阵的维度,并且案例中给出的3by3by2的矩阵,第一个方括号里有三个矩阵,并且每个矩阵都是三行两列,最后都reshape成18行一列

Answer

# 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

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}{\left \| x \right \|}

for example,if

                                                                                      x=\begin{bmatrix} 0 & 3 &4 \\ 2 & 6 &4 \end{bmatrix}

then

                                               \left \| x \right \|=np.linalg.norm(x,axis=1,keepdims=True)=\begin{bmatrix} 5\\\sqrt{56} \end{bmatrix}

and x_normalized=\frac{x}{\left \| x \right \|}

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

这里的规范化,都是取的矩阵每行的二范数,范数运算函数,np.linalg.norm()。keepdims保持矩阵维度,然后完成除运算就可以了,这里的除利用了python中broadcasting性质。

Answer

# 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,axis=1,keepdims=True)
    
    # Divide x by its norm.
    x = x/x_norm
    ### END CODE HERE ###

    return x

1.5 - Broadcasting and the softmax function

这边详细讲了broadcasting,运算与1.4中差不多。具体函数表示就不打了,太长了。

Answer

# 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 (n, m).

    Argument:
    x -- A numpy matrix of shape (n,m)

    Returns:
    s -- A numpy matrix equal to the softmax of x, of shape (n,m)
    """
    
    ### START CODE HERE ### (≈ 3 lines of code)
    # Apply exp() element-wise to x. Use np.exp(...).
    x = np.exp(x)

    # Create a vector x_sum that sums each row of x_exp. Use np.sum(..., axis = 1, keepdims = True).
    x_sum = np.sum( x, axis=1, keepdims = True )
    
    # Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.
    s = x / x_sum

    ### END CODE HERE ###
    
    return s

 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.

向量化这部分主要就是,利用numpy package中函数的使用去避免代码中显示for-loop or while-loop。这样可以使代码更加高效,特别是数据量特别大的情况下,这种计算速度的优势就显得更加明显。这边主要给了np.dot,np.multiply,np.outer.这几种函数的比较。

2.1-Implement the L1 and L2 loss functions

L1.Exercise: Implement the numpy vectorized version of the L1 loss. You may find the function abs(x) (absolute value of x) useful.

L1.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:

                                                                             L_{1}(\hat{y},y)=\sum_{i=0}^{m}\left | y^{(i)}-\hat{y}^{(i)} \right |

L2.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 ?=[?1,?2,...,??]x=[x1,x2,...,xn], then np.dot(x,x) =  \sum_{j=0}^{n}x_{j}^{2}

L2 loss is defined as

                                                                             L_{2}(\hat{y},y)=\sum_{i=0}^{m}(y^{(i)}-\hat{y}^{(i)})^{2}

这边就是计算两个简单的损失函数,其中第二个损失函数可以用矩阵的内积(np.dot(x,x))去计算平方。

Answer

# 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
    """
    
    ### START CODE HERE ### (≈ 1 line of code)
    loss = np.sum(np.abs(y-yhat))
    ### END CODE 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
    """
    
    ### START CODE HERE ### (≈ 1 line of code)
    loss = np.dot(y-yhat,y-yhat)
    ### END CODE HERE ###
    
    return loss

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值