吴恩达 深度学习 编程作业(1-2)- Python Basics with Numpy & Logistic Regression with a Neural Network mindset

deeplearning.ai课程知识点整理 Neural Networks and Deep Learning Introduction to deep learning Neural Networks Basics Logistic Regression as a Neural Network Computation graph 神经网络的计算过程由正向传播(forward propagation )来进行前向计... 阅读详情

吴恩达Coursera课程 DeepLearning.ai 编程作业系列,本文为《神经网络与深度学习》部分的第二周“神经网络基础”的课程作业(做了无用部分的删减)。

另外,本节课程笔记在此:《吴恩达Coursera深度学习课程 DeepLearning.ai 提炼笔记(1-2)》,如有任何建议和问题,欢迎留言。


#Part 1:Python Basics with Numpy (optional assignment)

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

Exercise: Build a function that returns the sigmoid of a real number x. Use math.exp(x) for the exponential function.

Reminder:
s i g m o i d ( x ) = 1 1 + e − x sigmoid(x) = \frac{1}{1+e^{-x}} sigmoid(x)=1+e−x1​ 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().

# 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.0 / (1 + 1/ math.exp(x))
    ### END CODE HERE ###
    
    return s
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.

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

TypeError                                 Traceback (most recent call last)

<ipython-input-3-2e11097d6860> in <module>()
      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.


<ipython-input-1-65a96864f65f> in basic_sigmoid(x)
     15 
     16     ### START CODE HERE ### (≈ 1 line of code)
---> 17     s = 1.0 / (1 + 1/ math.exp(x))
     18     ### END CODE HERE ###
     19 


TypeError: a float is required

In fact, if $ x = (x_1, x_2, …, x_n)$ is a row vector then n p . e x p ( x ) np.exp(x) np.exp(x) will apply the exponential function to every element of x. The output will thus be: n p . e x p ( x ) = ( e x 1 , e x 2 , . . . , e x n ) np.exp(x) = (e^{x_1}, e^{x_2}, ..., e^{x_n}) np.exp(x)=(ex1​,ex2​,...,exn​)

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 + 3 s = x + 3 s=x+3 or s = 1 x s = \frac{1}{x} s=x1​ will output s as a vector of the same size as x.

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

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 ∈ R n ,  s i g m o i d ( x ) = s i g m o i d ( x 1 x 2 . . . x n ) = ( 1 1 + e − x 1 1 1 + e − x 2 . . . 1 1 + e − x n ) (1) \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} For x∈Rn, sigmoid(x)=sigmoid⎝⎜⎜⎛​x1​x2​...xn​​⎠⎟⎟⎞​=⎝⎜⎜⎛​1+e−x1​1​1+e−x2​1​...1+e−xn​1​​⎠⎟⎟⎞​(1)

# 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.0 / (1 + 1 / np.exp(x))
    ### END CODE HERE ###
    
    return s
x = np.array([1, 2, 3])
sigmoid(x)
array([ 0.73105858,  0.88079708,  0.95257413])

1.2 - Sigmoid gradient

Exercise: Implement the function sigmoid_grad() to compute the gradient of the sigmoid function with respect to its input x. The formula is: s i g m o i d _ d e r i v a t i v e ( x ) = σ ′ ( x ) = σ ( x ) ( 1 − σ ( x ) ) (2) sigmoid\_derivative(x) = \sigma'(x) = \sigma(x) (1 - \sigma(x))\tag{2} sigmoid_derivative(x)=σ′(x)=σ(x)(1−σ(x))(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 σ ′ ( x ) = s ( 1 − s ) \sigma'(x) = s(1-s) σ′(x)=s(1−s)
# 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.0 / (1 + 1 / np.exp(x))
    ds = s * (1 - s)
    ### END CODE HERE ###
    
    return ds
x = np.array([1, 2, 3])
print ("sigmoid_derivative(x) = " + str(sigmoid_derivative(x)))
sigmoid_derivative(x) = [ 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 ( l e n g t h , h e i g h t , d e p t h = 3 ) (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 ( l e n g t h ∗ h e i g h t ∗ 3 , 1 ) (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.
# 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
# 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]]

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 = [ 0 3 4 2 6 4 ] (3) x = \begin{bmatrix} 0 & 3 & 4 \\ 2 & 6 & 4 \\ \end{bmatrix}\tag{3} x=[02​36​44​](3) then ∥ x ∥ = n p . l i n a l g . n o r m ( x , a x i s = 1 , k e e p d i m s = T r u e ) = [ 5 56 ] (4) \| x\| = np.linalg.norm(x, axis = 1, keepdims = True) = \begin{bmatrix} 5 \\ \sqrt{56} \\ \end{bmatrix}\tag{4} ∥x∥=np.linalg.norm(x,axis=1,keepdims=True)=[556 ​​](4)and x _ n o r m a l i z e d = x ∥ x ∥ = [ 0 3 5 4 5 2 56 6 56 4 56 ] (5) 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} x_normalized=∥x∥x​=[

吴恩达DeepLearning.AI官方课程系列——Pretraining LLMs 机智流后续会继续跟进解读吴恩达DeepLearning.AI官方课程系列——Pretraining LLMs课程,欢迎小伙伴们在留言区积极互动转发分享,你们的支持是我们更新最大的动力~ 阅读详情

相关推荐

机器学习(吴恩达)week2编程作业

机器学习(吴恩达)week2编程作业

嵌入式设备的switch 以及PHY 芯片调试和选型 (1)

越来越的设备需要多网口的需求,于是需求搭配一个交换机实现网口的扩展。但是很多软件或是硬件工程师在实际选型和应用中经常会遇到一些问题。这里总结一下,避免大家采坑。 几个概念: MAC(介质访问控制),可以理解成数据链路层即可 PHY(物理性),简单理解层转成物理层的连接组件即可 控制接口(MDC/DMIO,I2C,...

睿峰的博客 1万+

从零到一:R与RStudio的安装与配置全攻略

本文提供了R与RStudio的完整安装与配置指南,涵盖Windows、Mac和Linux三大操作系统。从基础环境搭建到高级性能优化,详细介绍了R语言安装、RStudio配置、项目管理和实用技巧,帮助数据科学初学者快速搭建高效的分析工作环境。

weixin_29062671的博客 420

立创开源桌面激光雕刻机DIY全解析:从悬臂结构、Arduino主控到Marlin固件

本文详细解析了基于立创开源平台的桌面激光雕刻机DIY全过程。重点介绍了悬臂式机械结构的设计与优化,阐述了采用Arduino Mega 2560主控与RAMPS 1.4扩展板的经典控制方案,并深入讲解了Marlin固件的关键配置步骤,包括电机步数计算与激光功能启用,为创客和电子爱好者提供了一套完整的从硬件搭建到软件调试的实战指南。

weixin_42510201的博客 385

CAN接受和发送失败的原因有哪些---之前调试MCP2515驱动时,数据一直发不出去,三个发送邮箱都被占满.至今未解决,读寄存器-总线错误

0.CAN总线错误分析与解决–讲的最精辟的放在最前面 我们知道CAN总线上的每个节点往总线上发送数据的同时会同时读取总线上的数据,并与自己发送的数据作对比。—CAN仲裁??? CAN总线错误分别有发送和接收错误计数,计数达到一定的累计以后就会产生CAN BUS OFF, 这说明CAN总线上出现了严重的错误。如下图CAN总线产生错误后的状态转换机制 如果出现了BUS OFF,总线上的节点需要做一些动作,例如重启CAN控制器或是重新上电,但是这些都只是一些补救措施,最根本的还是需要找到引起BUS OFF的根源

dianqicyuyan的博客 2万+

新手也能搞定的ANPC三电平逆变器Simulink仿真:从SPWM调制到开关损耗优化

本文详细介绍了如何在Simulink中搭建ANPC三电平逆变器仿真模型,从SPWM调制基础到开关损耗优化技巧。通过分层设计思路和实用代码示例,帮助新手快速掌握ANPC拓扑的核心功能,包括中点平衡控制和性能指标分析,为电力电子系统设计提供实践指导。

weixin_30335575的博客 408

PCL K4PCS算法实现点云粗配准【2026最新版】

K4PCS算法实现点云粗配准。博客长期更新,本文最近一次更新时间为:2026年5月4日。

点云侠的博客 42万+

【思考模型框架】MECE原则,确保分析时,考虑到的所有因素,既不重叠又无遗漏

MECE原则,是Mutually Exclusive and Collectively Exhaustive的缩写,中文译为“相互独立、完全穷尽”。MECE原则,这是一种逻辑思维和组织信息的方法,旨在确保分析时既没有遗漏也没有重复。MECE原则,相互独立、完全穷尽(Mutually Exclusive,Collectively Exhaustive)的原则MECE原则,确保分析时考虑到的所有因素既不重叠又无遗漏。

奶爸的编程之路,也就一周冷个三天 2752

2024-12月js逆向案例-sensor-data之vmp字段之akamai_2/3.0-(下)

akamai2/3的vmp字段逆向分析

十一姐的博客 3146

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

上一篇: 吴恩达Coursera深度学习课程 DeepLearning.ai 提炼笔记(1-2)-- 神经网络基础
下一篇: 吴恩达Coursera深度学习课程 DeepLearning.ai 提炼笔记(1-3)-- 浅层神经网络
大树先生的博客
博客等级 码龄9年 2692粉丝 200原创
评论 89
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值