第四周编程作业(一)-Building your Deep Neural Network: Step by Step(二)

简介: 第四周编程作业(一)-Building your Deep Neural Network: Step by Step(二)

4 - Forward propagation module


4.1 - Linear Forward


Now that you have initialized your parameters, you will do the forward propagation module. You will start by implementing some basic functions that you will use later when implementing the model. You will complete three functions in this order:

  • LINEAR
  • LINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid.
  • [LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID (whole model)

The linear forward module (vectorized over all the examples) computes the following equations:

$$Z^{[l]} = W{[l]}A{[l-1]} +b^{[l]}\tag{4}$$

where $A^{[0]} = X$.


Exercise: Build the linear part of forward propagation.


Reminder:

The mathematical representation of this unit is $Z^{[l]} = W{[l]}A{[l-1]} +b^{[l]}$. You may also find np.dot() useful. If your dimensions don't match, printing W.shape may help.

# GRADED FUNCTION: linear_forward
def linear_forward(A, W, b):
    """
    Implement the linear part of a layer's forward propagation.
    Arguments:
    A -- activations from previous layer (or input data): (size of previous layer, number of examples)
    W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
    b -- bias vector, numpy array of shape (size of the current layer, 1)
    Returns:
    Z -- the input of the activation function, also called pre-activation parameter 
    cache -- a python dictionary containing "A", "W" and "b" ; stored for computing the backward pass efficiently
    """
    ### START CODE HERE ### (≈ 1 line of code)
    Z = np.dot(W,A)+b
    ### END CODE HERE ###
    assert(Z.shape == (W.shape[0], A.shape[1]))
    cache = (A, W, b)
    return Z, cache

A, W, b = linear_forward_test_case()
Z, linear_cache = linear_forward(A, W, b)
print("Z = " + str(Z))

Z = [[ 3.26295337 -1.23429987]]


Expected output:

<table style="width:35%">

<tr>

<td> Z </td>

<td> [[ 3.26295337 -1.23429987]] </td>

</tr>

</table>


4.2 - Linear-Activation Forward


In this notebook, you will use two activation functions:

  • Sigmoid: $\sigma(Z) = \sigma(W A + b) = \frac{1}{ 1 + e^{-(W A + b)}}$. We have provided you with the sigmoid function. This function returns two items: the activation value "a" and a "cache" that contains "Z" (it's what we will feed in to the corresponding backward function). To use it you could just call:

A, activation_cache = sigmoid(Z)


  • ReLU: The mathematical formula for ReLu is $A = RELU(Z) = max(0, Z)$. We have provided you with the relu function. This function returns two items: the activation value "A" and a "cache" that contains "Z" (it's what we will feed in to the corresponding backward function). To use it you could just call:

A, activation_cache = relu(Z)


For more convenience, you are going to group two functions (Linear and Activation) into one function (LINEAR->ACTIVATION). Hence, you will implement a function that does the LINEAR forward step followed by an ACTIVATION forward step.


Exercise: Implement the forward propagation of the LINEAR->ACTIVATION layer. Mathematical relation is: $A^{[l]} = g(Z^{[l]}) = g(W{[l]}A{[l-1]} +b^{[l]})$ where the activation "g" can be sigmoid() or relu(). Use linear_forward() and the correct activation function.

# GRADED FUNCTION: linear_activation_forward
def linear_activation_forward(A_prev, W, b, activation):
    """
    Implement the forward propagation for the LINEAR->ACTIVATION layer
    Arguments:
    A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)
    W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
    b -- bias vector, numpy array of shape (size of the current layer, 1)
    activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
    Returns:
    A -- the output of the activation function, also called the post-activation value 
    cache -- a python dictionary containing "linear_cache" and "activation_cache";
             stored for computing the backward pass efficiently
    """
    if activation == "sigmoid":
        # Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
        ### START CODE HERE ### (≈ 2 lines of code)
        Z, linear_cache = linear_forward(A_prev, W, b)
        A, activation_cache = A,activation_cache = sigmoid(Z)
        ### END CODE HERE ###
    elif activation == "relu":
        # Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
        ### START CODE HERE ### (≈ 2 lines of code)
        Z, linear_cache = linear_forward(A_prev, W, b)
        A, activation_cache = A,activation_cache = relu(Z)
        ### END CODE HERE ###
    assert (A.shape == (W.shape[0], A_prev.shape[1]))
    cache = (linear_cache, activation_cache)
    return A, cache

A_prev, W, b = linear_activation_forward_test_case()
A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "sigmoid")
print("With sigmoid: A = " + str(A))
A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "relu")
print("With ReLU: A = " + str(A))

With sigmoid: A = [[ 0.96890023  0.11013289]]
With ReLU: A = [[ 3.43896131  0.        ]]


Expected output:

<table style="width:35%">

<tr>

<td> **With sigmoid: A ** </td>

<td > [[ 0.96890023  0.11013289]]</td>

</tr>

<tr>

<td> **With ReLU: A ** </td>

<td > [[ 3.43896131  0.        ]]</td>

</tr>

</table>

Note: In deep learning, the "[LINEAR->ACTIVATION]" computation is counted as a single layer in the neural network, not two layers.


d) L-Layer Model


For even more convenience when implementing the $L$-layer Neural Net, you will need a function that replicates the previous one (linear_activation_forward with RELU) $L-1$ times, then follows that with one linear_activation_forward with SIGMOID.


<caption><center> Figure 2 : [LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID model</center></caption>


Exercise: Implement the forward propagation of the above model.


Instruction: In the code below, the variable AL will denote $A^{[L]} = \sigma(Z^{[L]}) = \sigma(W^{[L]} A^{[L-1]} + b^{[L]})$. (This is sometimes also called Yhat, i.e., this is $\hat{Y}$.)


Tips:

  • Use the functions you had previously written
  • Use a for loop to replicate [LINEAR->RELU] (L-1) times
  • Don't forget to keep track of the caches in the "caches" list. To add a new value c to a list, you can use list.append(c).

# GRADED FUNCTION: L_model_forward
def L_model_forward(X, parameters):
    """
    Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation
    Arguments:
    X -- data, numpy array of shape (input size, number of examples)
    parameters -- output of initialize_parameters_deep()
    Returns:
    AL -- last post-activation value
    caches -- list of caches containing:
                every cache of linear_relu_forward() (there are L-1 of them, indexed from 0 to L-2)
                the cache of linear_sigmoid_forward() (there is one, indexed L-1)
    """
    caches = []
    A = X
    L = len(parameters) // 2                  # number of layers in the neural network
    # Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list.
    for l in range(1, L):
        A_prev = A 
        ### START CODE HERE ### (≈ 2 lines of code)
        A, cache = linear_activation_forward(A_prev,parameters["W"+str(l)],parameters["b"+str(l)],activation="relu")
        caches.append(cache)
        ### END CODE HERE ###
    # Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list.
    ### START CODE HERE ### (≈ 2 lines of code)
    AL, cache = linear_activation_forward(A,parameters["W"+str(L)],parameters["b"+str(L)],activation="sigmoid")
    caches.append(cache)
    ### END CODE HERE ###
    assert(AL.shape == (1,X.shape[1]))
    return AL, caches

X, parameters = L_model_forward_test_case()
AL, caches = L_model_forward(X, parameters)
print("AL = " + str(AL))
print("Length of caches list = " + str(len(caches)))

AL = [[ 0.17007265  0.2524272 ]]
Length of caches list = 2


<table style="width:40%">

<tr>

<td> AL </td>

<td > [[ 0.17007265  0.2524272 ]]</td>

</tr>

<tr>

<td> **Length of caches list ** </td>

<td > 2</td>

</tr>

</table>

Great! Now you have a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predictions. It also records all intermediate values in "caches". Using $A^{[L]}$, you can compute the cost of your predictions.


5 - Cost function


Now you will implement forward and backward propagation. You need to compute the cost, because you want to check if your model is actually learning.

Exercise: Compute the cross-entropy cost $J$, using the following formula: $$-\frac{1}{m} \sum\limits_{i = 1}^{m} (y{(i)}\log\left(a{[L] (i)}\right) + (1-y^{(i)})\log\left(1- a^{L}\right)) \tag{7}$$

# GRADED FUNCTION: compute_cost
def compute_cost(AL, Y):
    """
    Implement the cost function defined by equation (7).
    Arguments:
    AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
    Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)
    Returns:
    cost -- cross-entropy cost
    """
    m = Y.shape[1]
    # Compute loss from aL and y.
    ### START CODE HERE ### (≈ 1 lines of code)
    cost = (-1/m)*np.sum(Y*np.log(AL)+(1-Y)*np.log(1-AL))
    ### END CODE HERE ###
    cost = np.squeeze(cost)      # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).
    assert(cost.shape == ())
    return cost

Y, AL = compute_cost_test_case()
print("cost = " + str(compute_cost(AL, Y)))

cost = 0.414931599615


Expected Output:

<table>

<tr>
<td>**cost** </td>
<td> 0.41493159961539694</td> 
</tr>


</table>

相关文章
|
索引
树莓派 Raspberry Pi (bullseye)更换阿里云源方法
树莓派 Raspberry Pi (bullseye)更换阿里云源方法
14639 2
|
7月前
|
人工智能 编解码 Java
Harness Engineering:耗时一周,我是如何将应用的AI Coding率提升至90%的
文章内容基于作者个人技术实践与独立思考,旨在分享经验,仅代表个人观点。
2099 8
|
人工智能 Java API
支持 40+ 插件,Spring AI Alibaba 简化智能体私有数据集成
通过使用社区官方提供的超过 20 种 RAG 数据源和 20 种 Tool Calling 接口,开发者可以轻松接入多种外部数据源(如 GitHub、飞书、云 OSS 等)以及调用各种工具(如天气预报、地图导航、翻译服务等)。这些默认实现大大简化了智能体的开发过程,使得开发者无需从零开始,便可以快速构建功能强大的智能体系统。通过这种方式,智能体不仅能够高效处理复杂任务,还能适应各种应用场景,提供更加智能、精准的服务。
2512 123
|
机器学习/深度学习 人工智能 JSON
知识蒸馏方法探究:Google Distilling Step-by-Step 论文深度分析
大型语言模型(LLM)的发展迅速,从简单对话系统进化到能执行复杂任务的先进模型。然而,这些模型的规模和计算需求呈指数级增长,给学术界和工业界带来了挑战。为解决这一问题,知识蒸馏技术应运而生,旨在将大型模型的知识转移给更小、更易管理的学生模型。Google Research 提出的“Distilling Step-by-Step”方法不仅减小了模型规模,还通过提取推理过程使学生模型在某些任务上超越教师模型。该方法通过多任务学习框架,训练学生模型同时预测标签和生成推理过程,从而实现更高效、更智能的小型化模型。这为资源有限的研究者和开发者提供了新的解决方案,推动了AI技术的普及与应用。
1093 19
知识蒸馏方法探究:Google Distilling Step-by-Step 论文深度分析
|
算法 Go 计算机视觉
YOLOv8结构解读
YOLOv8是Ultralytics团队开发的最新目标检测模型,基于YOLO系列的高效单阶段架构,进一步优化了精度与速度。相比YOLOv5,YOLOv8在Backbone中移除了Focus模块,优化了CSP结构;在Neck部分增强了特征融合能力;Head部分采用Anchor-Free与解耦头设计,提升检测精度。此外,YOLOv8引入了更先进的损失函数、自对抗训练和动态标签分配等策略,显著提高了模型性能与鲁棒性。
3783 0
打造高效团队:15个协作游戏,增强沟通与默契
公司团建怎么玩?15款适合团队的协作游戏包够玩的!
2423 8
打造高效团队:15个协作游戏,增强沟通与默契
|
Java 关系型数据库 MySQL
全网最实用的 IDEA Debug 调试技巧(超详细案例)
Debug 是程序员的开发神器,使用好了可以帮助我们非常高效的工作、学习、排查问题等。毫不客气的说,是决定我们进阶到更高层级的一个重要技能。 今天跟大家分享一下 IDEA 中 Debug 调试的各种奇技淫巧。
4999 0
全网最实用的 IDEA Debug 调试技巧(超详细案例)
|
JavaScript Java Linux
当Java虚拟机遇上Linux Arena内存池
故障案例一 系统环境: RHEL 6.8 64-bit(glibc 2.12)、Sun JDK 6u45 64-bit、WLS 10.3.6 故障现象: 这里引用一下客户当时发邮件时提出的问题描述吧。
14730 0
|
存储 IDE 开发工具
手把手教你做一款HID键盘
手把手教你做一款HID键盘
1236 1
手把手教你做一款HID键盘