第二周编程作业 -Logistic Regression with a Neural Network mindset(二)

简介: 第二周编程作业 -Logistic Regression with a Neural Network mindset(二)

4 - Building the parts of our algorithm


The main steps for building a Neural Network are:

  1. Define the model structure (such as number of input features)
  2. Initialize the model's parameters
  3. Loop:
  • Calculate current loss (forward propagation)
  • Calculate current gradient (backward propagation)
  • Update parameters (gradient descent)

You often build 1-3 separately and integrate them into one function we call model().


4.1 - Helper functions


Exercise: Using your code from "Python Basics", implement sigmoid(). As you've seen in the figure above, you need to compute $sigmoid( w^T x + b) = \frac{1}{1 + e{-(wT x + b)}}$ to make predictions. Use np.exp().

# GRADED FUNCTION: sigmoid
def sigmoid(z):
    """
    Compute the sigmoid of z
    Arguments:
    z -- A scalar or numpy array of any size.
    Return:
    s -- sigmoid(z)
    """
    ### START CODE HERE ### (≈ 1 line of code)
    s = 1.0/(1+np.exp(-z))
    ### END CODE HERE ###
    return s

print ("sigmoid([0, 2]) = " + str(sigmoid(np.array([0,2]))))

sigmoid([0, 2]) = [ 0.5         0.88079708]


Expected Output:

<table>

<tr>

<td>sigmoid([0, 2])</td>

<td> [ 0.5         0.88079708]</td>

</tr>

</table>


4.2 - Initializing parameters


Exercise: Implement parameter initialization in the cell below. You have to initialize w as a vector of zeros. If you don't know what numpy function to use, look up np.zeros() in the Numpy library's documentation.

# GRADED FUNCTION: initialize_with_zeros
def initialize_with_zeros(dim):
    """
    This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.
    Argument:
    dim -- size of the w vector we want (or number of parameters in this case)
    Returns:
    w -- initialized vector of shape (dim, 1)
    b -- initialized scalar (corresponds to the bias)
    """
    ### START CODE HERE ### (≈ 1 line of code)
    w, b = np.zeros((dim,1)), 0
    ### END CODE HERE ###
    assert(w.shape == (dim, 1))
    assert(isinstance(b, float) or isinstance(b, int))
    return w, b

dim = 2
w, b = initialize_with_zeros(dim)
print ("w = " + str(w))
print ("b = " + str(b))

w = [[ 0.]
 [ 0.]]
b = 0


Expected Output:

<table style="width:15%">

<tr>

<td>  ** w **  </td>

<td> [[ 0.]

[ 0.]] </td>

</tr>

<tr>

<td>  ** b **  </td>

<td> 0 </td>

</tr>

</table>

For image inputs, w will be of shape (num_px $\times$ num_px $\times$ 3, 1).


4.3 - Forward and Backward propagation


Now that your parameters are initialized, you can do the "forward" and "backward" propagation steps for learning the parameters.


Exercise: Implement a function propagate() that computes the cost function and its gradient.


Hints:

Forward Propagation:

  • You get X
  • You compute $A = \sigma(w^T X + b) = (a^{(0)}, a^{(1)}, ..., a^{(m-1)}, a^{(m)})$
  • You calculate the cost function: $J = -\frac{1}{m}\sum_{i=1}{m}y{(i)}\log(a{(i)})+(1-y{(i)})\log(1-a^{(i)})$

Here are the two formulas you will be using:

$$ \frac{\partial J}{\partial w} = \frac{1}{m}X(A-Y)^T\tag{7}$$

$$ \frac{\partial J}{\partial b} = \frac{1}{m} \sum_{i=1}^m (a{(i)}-y{(i)})\tag{8}$$

# GRADED FUNCTION: propagate
def propagate(w, b, X, Y):
    """
    Implement the cost function and its gradient for the propagation explained above
    Arguments:
    w -- weights, a numpy array of size (num_px * num_px * 3, 1)
    b -- bias, a scalar
    X -- data of size (num_px * num_px * 3, number of examples)
    Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)
    Return:
    cost -- negative log-likelihood cost for logistic regression
    dw -- gradient of the loss with respect to w, thus same shape as w
    db -- gradient of the loss with respect to b, thus same shape as b
    Tips:
    - Write your code step by step for the propagation. np.log(), np.dot()
    """
    m = X.shape[1]
    # FORWARD PROPAGATION (FROM X TO COST)
    ### START CODE HERE ### (≈ 2 lines of code)
    A = sigmoid(np.dot(w.T,X)+b) # A
    cost = -(1/m)*np.sum(Y*np.log(A) + (1-Y)*np.log(1-A))                            # compute cost
    ### END CODE HERE ###
    # BACKWARD PROPAGATION (TO FIND GRAD)
    ### START CODE HERE ### (≈ 2 lines of code)
    dw = 1/m*np.dot(X,(A-Y).T)
    db = 1/m*np.sum(A-Y)
    ### END CODE HERE ###
    assert(dw.shape == w.shape)
    assert(db.dtype == float)
    cost = np.squeeze(cost)
    assert(cost.shape == ())
    grads = {"dw": dw,
             "db": db}
    return grads, cost

w, b, X, Y = np.array([[1],[2]]), 2, np.array([[1,2],[3,4]]), np.array([[1,0]])
grads, cost = propagate(w, b, X, Y)
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
print ("cost = " + str(cost))

dw = [[ 0.99993216]
 [ 1.99980262]]
db = 0.499935230625
cost = 6.00006477319


Expected Output:

<table style="width:50%">

<tr>

<td>  ** dw **  </td>

<td> [[ 0.99993216]

[ 1.99980262]]</td>

</tr>

<tr>

<td>  ** db **  </td>

<td> 0.499935230625 </td>

</tr>

<tr>

<td>  ** cost **  </td>

<td> 6.000064773192205</td>

</tr>

</table>


d) Optimization


  • You have initialized your parameters.
  • You are also able to compute a cost function and its gradient.
  • Now, you want to update the parameters using gradient descent.

Exercise: Write down the optimization function. The goal is to learn $w$ and $b$ by minimizing the cost function $J$. For a parameter $\theta$, the update rule is $ \theta = \theta - \alpha \text{ } d\theta$, where $\alpha$ is the learning rate.

# GRADED FUNCTION: optimize
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
    """
    This function optimizes w and b by running a gradient descent algorithm
    Arguments:
    w -- weights, a numpy array of size (num_px * num_px * 3, 1)
    b -- bias, a scalar
    X -- data of shape (num_px * num_px * 3, number of examples)
    Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)
    num_iterations -- number of iterations of the optimization loop
    learning_rate -- learning rate of the gradient descent update rule
    print_cost -- True to print the loss every 100 steps
    Returns:
    params -- dictionary containing the weights w and bias b
    grads -- dictionary containing the gradients of the weights and bias with respect to the cost function
    costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve.
    Tips:
    You basically need to write down two steps and iterate through them:
        1) Calculate the cost and the gradient for the current parameters. Use propagate().
        2) Update the parameters using gradient descent rule for w and b.
    """
    costs = []
    for i in range(num_iterations):
        # Cost and gradient calculation (≈ 1-4 lines of code)
        ### START CODE HERE ### 
        grads, cost = propagate(w, b, X, Y)
        costs.append(cost)
        ### END CODE HERE ###
        # Retrieve derivatives from grads
        dw = grads["dw"]
        db = grads["db"]
        # update rule (≈ 2 lines of code)
        ### START CODE HERE ###
        w = w - learning_rate*dw
        b = b - learning_rate*db
        ### END CODE HERE ###
        # Record the costs
        if i % 100 == 0:
            costs.append(cost)
        # Print the cost every 100 training examples
        if print_cost and i % 100 == 0:
            print ("Cost after iteration %i: %f" %(i, cost))
    params = {"w": w,
              "b": b}
    grads = {"dw": dw,
             "db": db}
    return params, grads, costs

params, grads, costs = optimize(w, b, X, Y, num_iterations= 100, learning_rate = 0.009, print_cost = False)
print ("w = " + str(params["w"]))
print ("b = " + str(params["b"]))
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))

w = [[ 0.1124579 ]
 [ 0.23106775]]
b = 1.55930492484
dw = [[ 0.90158428]
 [ 1.76250842]]
db = 0.430462071679


Expected Output:

<table style="width:40%">

<tr>

<td> w </td>

<td>[[ 0.1124579 ]

[ 0.23106775]] </td>

</tr>

<tr>
   <td> **b** </td>
   <td> 1.55930492484 </td>
</tr>
<tr>
   <td> **dw** </td>
   <td> [[ 0.90158428]


[ 1.76250842]] </td>

</tr>

<tr>

<td> db </td>

<td> 0.430462071679 </td>

</tr>

</table>


Exercise: The previous function will output the learned w and b. We are able to use w and b to predict the labels for a dataset X. Implement the predict() function. There is two steps to computing predictions:

  1. Calculate $\hat{Y} = A = \sigma(w^T X + b)$
  2. Convert the entries of a into 0 (if activation <= 0.5) or 1 (if activation > 0.5), stores the predictions in a vector Y_prediction. If you wish, you can use an if/else statement in a for loop (though there is also a way to vectorize this).

# GRADED FUNCTION: predict
def predict(w, b, X):
    '''
    Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
    Arguments:
    w -- weights, a numpy array of size (num_px * num_px * 3, 1)
    b -- bias, a scalar
    X -- data of size (num_px * num_px * 3, number of examples)
    Returns:
    Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X
    '''
    m = X.shape[1]
    Y_prediction = np.zeros((1,m))
    w = w.reshape(X.shape[0], 1)
    # Compute vector "A" predicting the probabilities of a cat being present in the picture
    ### START CODE HERE ### (≈ 1 line of code)
    A =sigmoid(np.dot(w.T,X)+b)
    ### END CODE HERE ###
    for i in range(A.shape[1]):
        # Convert probabilities A[0,i] to actual predictions p[0,i]
        ### START CODE HERE ### (≈ 4 lines of code)
        if A[0,i]<=0.5:
            Y_prediction[0,i] = 0
        else:
            Y_prediction[0,i] = 1
        ### END CODE HERE ###
    assert(Y_prediction.shape == (1, m))
    return Y_prediction

print ("predictions = " + str(predict(w, b, X)))

predictions = [[ 1.  1.]]


Expected Output:

<table style="width:30%">

<tr>

<td>


predictions

</td>

<td>

[[ 1.  1.]]

</td>

</tr>

</table>

<font color='blue'>


What to remember:

You've implemented several functions that:

  • Initialize (w,b)
  • Optimize the loss iteratively to learn parameters (w,b):
  • computing the cost and its gradient
  • updating the parameters using gradient descent
  • Use the learned (w,b) to predict the labels for a given set of examples
相关文章
|
Linux iOS开发 UED
Linux简介和比较:开源操作系统的优势与差异
Linux简介和比较:开源操作系统的优势与差异
1377 0
|
11月前
|
存储 弹性计算 Linux
2026阿里云购买云服务器流程及注意事项(新用户指南)
在数字化场景中,个人和企业部署网站、APP 常需要服务器支撑。相比逐渐淘汰的虚拟主机和成本较高的独立服务器,云服务器凭借弹性扩展、性价比高的优势成为主流。阿里云 ECS(弹性计算服务)地域节点多、配置灵活,但新手容易在地域、实例规格等选择上困惑。下面结合最新信息,梳理阿里云服务器的购买流程和配置要点,帮新手高效完成选购。
|
6月前
|
存储 人工智能 API
阿里云Token Plan 团队版支持使用优惠券吗?亲测可叠加优惠券,高级坐席可减30元,尊享坐席可减50元
阿里云百炼Token Plan团队版是一款以Credits统一计量的AI大模型订阅服务,支持文本与图像生成,兼容主流AI编程及智能体工具,提供标准(98元/坐席/月)、高级(698元/坐席/月)、尊享(1398元/坐席/月)三档坐席,额度从2.5万到25万Credits不等,并支持共享用量包弹性抵扣。用户可叠加使用618 AI加速季优惠券(个人最高减150元、企业最高减800元)及百炼"先用后返"券(最高返200元),企业迁云还可申请算力补贴,大幅降低团队AI应用落地成本。
|
6月前
|
SQL 关系型数据库 MySQL
【第一阶段总结】MySQL基础20天 —— 知识地图与避坑复盘
本文是MySQL基础20天学习的系统复盘,涵盖架构、索引、SQL优化、事务、锁五大模块,提炼核心知识地图与高频避坑点(如无索引导致全表锁、RR下快照读与当前读差异等),并附面试考点与自测清单,助力夯实底层原理,平稳进阶。(239字)
396 1
|
9月前
|
自然语言处理 搜索推荐 BI
企业级 Agent 解决方案
瓴羊企业级Agent解决方案以AgentOne为智能中枢,打通数据孤岛、工具链断裂与业务闭环缺失三大痛点,构建“感知-决策-执行-反馈”全链路数智闭环。集成Quick Service、智能小Q、Quick Audience及Dataphin四大专业智能体,实现服务、分析、营销与数据治理的全域协同。(239字)
|
9月前
|
Python
使用 Python 实现 Word 文档文本格式化全解析
周一早九点,领导催改50页合同格式?别再手动滚动了!用Python+python-docx库,2秒自动完成公司名加粗红色、段落对齐、标题样式等批量排版。掌握Document-Paragraph-Run三层结构,轻松搞定Word自动化,解放双手,专注真正重要的事。(239字)
943 0
|
机器学习/深度学习 运维 自然语言处理
AIOps在美团的探索与实践——事件管理篇
本文介绍了美团AIOps在事件管理领域的探索与实践,涵盖事前预防、事中处理和事后运营三大阶段。通过智能变更检测、多模态故障诊断、相似事件推荐等技术,提升故障发现效率与准确性,助力运维智能化升级。
|
12月前
|
测试技术
金丝雀发布
金丝雀发布(Canary)是一种渐进式发布策略,类似灰度发布。不同于蓝绿部署需两套完整环境切换,金丝雀是在一套系统中逐步替换旧版本,适用于大规模服务器场景。例如,线上有一万台Web服务器时,可先更新10台并观察,确认无误后逐步推广。通过流量切分控制新版本请求比例,降低发布风险。而单台服务器场景则适合蓝绿部署,不适用金丝雀。两种策略各有适用场景,需根据实际架构选择。
|
JSON API 数据格式
微店商品列表API接口文档
微店商品列表API(micro.item_search)支持通过关键词、分页和筛选条件获取商品信息,返回含ID、名称、价格、库存、图片等JSON数据。适用于电商工具、竞品分析等场景,具备分页灵活、数据实时等优势。
|
机器学习/深度学习 存储 人工智能
大模型微调:从理论到实践的全面指南
🌟蒋星熠Jaxonic:AI探索者,专注大模型微调技术。从LoRA到RLHF,实践医疗、法律等垂直领域模型优化,分享深度学习的科学与艺术,共赴二进制星河的极客征程。
1048 0
大模型微调:从理论到实践的全面指南