吴恩达 深度学习 编程作业(1-2)- Python Basics with Numpy1

本文介绍了Python编程的基础知识及Numpy的应用,包括基本语法、数组操作、矩阵运算等内容,并通过实例展示了如何使用Numpy进行高效的数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import math
import numpy as np

#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:
#1、You will be using Python 3.
#2、Avoid using for-loops and while-loops, unless you are explicitly told to do so.
#3、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.
#4、After coding your function, run the cell right below it to check if your result is correct.
#After this assignment you will:
#1、Be able to use iPython Notebooks
#2、Be able to use numpy functions and numpy matrix/vector operations
#3、Understand the concept of "broadcasting"
#4、Be able to vectorize code

#1、输出test的值

### START CODE HERE ### (≈ 1 line of code)
test = "Hello World"
### END CODE HERE ###
print ("test: " + test)

#2、输出单个sigmod的值

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 + np.math.exp(-x))
    ### END CODE HERE ###

    return s

print("basic_sigmoid(3):",basic_sigmoid(3))
#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.

#3、输出3个元素的数组sigmod的值

#x = [1, 2, 3] #向量不能参与运算
#print("basic_sigmoid(x):",basic_sigmoid(x)) # you will see this give an error when you run it, because x is a vector.

#4、输出exp的值

# example of np.exp
x = np.array([1, 2, 3])
print("np.exp(x):",np.exp(x)) # result is (exp(1), exp(2), exp(3))
#np.exp(x):[  2.71828183   7.3890561   20.08553692]

#5、输出向量相加的结果

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

#6、 Implement the sigmoid function using numpy

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

x = np.array([1, 2, 3])
print("sigmoid(x):",sigmoid(x))
#sigmoid(x): [ 0.73105858  0.88079708  0.95257413]

#7、Sigmoid gradient

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

x = np.array([1, 2, 5])
print ("sigmoid_derivative(x) = " + str(sigmoid_derivative(x)))
#sigmoid_derivative(x) = [ 0.19661193  0.10499359  0.00664806]

#8、Reshaping arrays

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

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

# 9、Normalizing rows

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

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]]

#10、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]

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

    # Apply exp() element-wise to x. Use np.exp(...).
    x_exp = 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_exp, axis = 1, keepdims = True)

    # Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.
    s = x_exp / x_sum

    return s

x = np.array([
    [9, 2, 5, 0, 0],
    [7, 5, 0, 0 ,0]])
print("softmax(x) = " + str(softmax(x)))
#softmax(x) = [[  9.80897665e-01   8.94462891e-04   1.79657674e-02   1.21052389e-04  1.21052389e-04]
#              [8.78679856e-01   1.18916387e-01   8.01252314e-04   8.01252314e-04   8.01252314e-04]]

#- If you print the shapes of x_exp, x_sum and s above and rerun the assessment cell, you will
#see that x_sum is of shape (2,1)
#while x_exp and s are of shape (2,5). x_exp/x_sum works due to python broadcasting.
#What you need to remember:
#1、- np.exp(x) works for any np.array x and applies the exponential function to every coordinate
#2、- the sigmoid function and its gradient
#3、- image2vector is commonly used in deep learning
#4、- np.reshape is widely used. In the future, you’ll see that keeping your matrix/vector dimensions
#straight will go toward eliminating a lot of bugs.
#5、- numpy has efficient built-in functions
#6、broadcasting is extremely useful
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值