本文节选自吴恩达老师《深度学习专项课程》编程作业,在此表示感谢。

课程链接:https://www.deeplearning.ai/deep-learning-specialization


目录

1 - Building basic functions with numpy

1.1 - np.exp(), sigmoid function

1.2 - Sigmoid gradient

1.3 - Reshaping arrays(常用)

1.4 - Normalizing rows(常用)

1.5 - Broadcasting and the softmax function(理解)

2 - Vectorization

2.1 - Implement the L1 and L2 loss functions

3 - 推荐阅读:


1 - Building basic functions with numpy

1.1 - np.exp(), sigmoid function

import numpy as npx = np.array([1, 2, 3])
print(np.exp(x))x = np.array([1, 2, 3])
print (x + 3)

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可能代表一个实数、向量或者矩阵。在numpy中使用数组来表示x的数据类型。

import numpy as np
def sigmoid(x):s = 1 / (1 + np.exp(-x))    return s

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:

实现sigmoid_grad()函数来计算sigmoid函数的梯度,sigmoid函数求导公式如下:

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 sigmoid gradient
def sigmoid_derivative(x):s = 1 / (1 + np.exp(-x))ds = s *(1-s)return dsx = np.array([1, 2, 3])
print ("sigmoid_derivative(x) = " + str(sigmoid_derivative(x)))

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 (length,height,depth=3). However, when you read an image as the input of an algorithm you convert it to a vector of shape (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:

def image2vector(image):v = image.reshape((image.shape[0] * image.shape[1] * image.shape[2], 1))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 (dividing each row vector of x by its norm).

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

def normalizeRows(x):"""Argument:x -- A numpy matrix of shape (n, m)Returns:x -- The normalized (by row) numpy matrix. """# Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)x_norm = np.linalg.norm(x, ord=2, axis=1, keepdims=True) # Divide x by its norm.x = x / x_normreturn x

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

Exercise: Implement a softmax function using numpy. You can think of softmax as a normalizing function used when your algorithm needs to classify two or more classes. You will learn more about softmax in the second course of this specialization.

Instructions:

def softmax(x):"""Argument:x -- A numpy matrix of shape (n,m)Returns:s -- A numpy matrix equal to the softmax of x, of shape (n,m)"""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)s = x_exp / x_sumreturn sx = np.array([[9, 2, 5, 0, 0],[7, 5, 0, 0 ,0]])
print("softmax(x) = " + str(softmax(x)))

**What you need to remember:** - np.exp(x) works for any np.array x and applies the exponential function to every coordinate - the sigmoid function and its gradient - image2vector is commonly used in deep learning - 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. - numpy has efficient built-in functions - broadcasting is extremely useful.

你需要记住的:

  • np.exp(x)对任意数组都有效并且对每个元素都进行指数计算;
  • sigmoid和其梯度函数以及image2vector函数以及np.reshape函数是深度学习中最常使用的函数;
  • numpy的广播机制是最常使用到的。

2 - Vectorization

2.1 - Implement the L1 and L2 loss functions

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

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:

def L1(yhat, y):loss = np.sum(abs(yhat-y))return lossyhat = np.array([.9, 0.2, 0.1, .4, .9])
y = np.array([1, 0, 0, 1, 1])
print("L1 = " + str(L1(yhat,y)))

L2 loss is defined as:

def L2(yhat, y):loss = np.dot((y-yhat),(y-yhat))  return lossyhat = np.array([.9, 0.2, 0.1, .4, .9])
y = np.array([1, 0, 0, 1, 1])
print("L2 = " + str(L2(yhat,y)))

**What to remember:** - Vectorization is very important in deep learning. It provides computational efficiency and clarity. - You have reviewed the L1 and L2 loss. - You are familiar with many numpy functions such as np.sum, np.dot, np.multiply, np.maximum, etc.

需要记住的:

  • 向量化是深度学习中最重要的,使得计算更加高效和清晰;
  • L1和 L2损失函数公式;
  • numpy中其它有用的函数:np.sum,np.dot,np.multiply,np.maximum。

3 - 推荐阅读:

  • Python之Numpy入门实战教程(1):基础篇
  • Python之Numpy入门实战教程(2):进阶篇之线性代数
  • numpy手册

1.深度学习练习:Python Basics with Numpy(选修)相关推荐

  1. 吴恩达 深度学习 编程作业(1-2.1)- Python Basics with Numpy

    Python Basics with Numpy (optional assignment) Welcome to your first assignment. This exercise gives ...

  2. opencv 计数后不动了 训练模型时_用OpenCV,深度学习和Python进行年龄识别

    (给Python编程开发加星标,提升编程技能.) 在本教程中,您将学习如何使用OpenCV,深度学习和Python执行年龄的自动识别/预测. 学完本教程后,您将能够以相当高的精确度去自动预测静态图像文 ...

  3. 图像处理神经网络python_深度学习使用Python进行卷积神经网络的图像分类教程

    深度学习使用Python进行卷积神经网络的图像分类教程 好的,这次我将使用python编写如何使用卷积神经网络(CNN)进行图像分类.我希望你事先已经阅读并理解了卷积神经网络(CNN)的基本概念,这里 ...

  4. 深度学习常用python库学习笔记

    深度学习常用python库学习笔记 常用的4个库 一.Numpy库 1.数组的创建 (1)np.array() (2)np.zeros() (3)np.ones() (4)np.empty() (5) ...

  5. 深度学习入门之Python小白逆袭大神系列(三)—深度学习常用Python库

    深度学习常用Python库介绍 目录 深度学习常用Python库介绍 简介 Numpy库 padas库 PIL库 Matplotlib库 简介 Python被大量应用在数据挖掘和深度学习领域,其中使用 ...

  6. 零基础实践深度学习之Python基础

    零基础实践深度学习之Python基础 Python数据结构 数字 字符串 列表 元组 字典 Python面向对象 Python JSON Python异常处理 Python文件操作 常见Linux命令 ...

  7. 【Python深度学习前传】用NumPy创建多维数组

    目录 1.  NumPy开发环境搭建 2. 第一个NumPy程序 3. 创建多维数组 Python之所以能成为深度学习领域最受宠的编程语言,其中Python三剑客的NumPy.Pandas和Matpl ...

  8. 自学python要到什么程度-学好深度学习,Python 得达到什么程度?

    如今,网络上的Python机器学习资源纷繁复杂,使得刚入门的小白们眼花缭乱.究竟从哪里开始?如何进行?云栖君给你推荐以下内容,相信读完你就会有自己的答案. "开始",是一个令人激动 ...

  9. 深度学习(Python)-- 神经网络的数学构建块

    本章包括 1.一个神经网络的例子 2.张量和张量操作 3.神经网络如何通过反向传播和梯度下降来学习 一.一个神经网络的例子 GitHub链接   使用Python库Keras学习对手写数字进行分类的神 ...

最新文章

  1. 新东方php工程,这几个游学项目介绍,了解一下
  2. python3爬虫入门教程-Python3爬虫教程基础篇之一:什么是爬虫
  3. 机房收费--组合查询
  4. websocket与socket.io
  5. 今週木曜日までの日程表
  6. kafka Failed to send messages after 3 tries 问题解决
  7. 天涯明夜刀手游微信第一服务器,天涯明月刀手游微信哪个区人多 微信一区选哪个好[多图]...
  8. linux 获取本机的所有IP地址
  9. [可视化-tableau]tableau的学习实践入门篇
  10. ElasticSearch的初级安装
  11. 问题:自定义Appender输出DCMTK的oflog
  12. 2008年度最佳开源CMS大奖赛开幕
  13. igzo屏幕优点与缺点_手机贴膜怎么选?选对了可以省个屏幕钱
  14. SpringMVC之安全性(一)
  15. Tomcat运行时报 cannot be cast to javax.servlet.Servlet
  16. Win10的Flash不能运行,报错——“暴力”解法
  17. 一元二次方程求根计算机的代码,[C算法]一元二次方程求根
  18. linux下安装python3出现无configure_Linux下安装Python3.9.0
  19. centos英文版下如何安装中文语言包
  20. 如何在电脑上保存微信公众号文章封面图片?

热门文章

  1. android 9格式吗,Android Studio中关于9-patch格式图片的编译错误
  2. 使用 IPsec 与组策略隔离服务器和域-第 7 章 IPsec 疑难解答
  3. 计算机科学与导论期末论文,计算机科学与导论论文3
  4. 伺服怎么接单相220伏_乐利网带你认识伺服电机及工作原理
  5. threejs精灵(Sprite)
  6. 计算机如果算积分排名,超级电脑预测英超积分榜:蓝军守住第4 曼联无缘欧冠...
  7. [UE4]C++静态加载问题:ConstructorHelpers::FClassFinder()和FObjectFinder()
  8. 简述TCP/IP四层体系结构及每层作用
  9. 交通与计算机杂志社,交通信息与安全
  10. python安装后cmd找不到_关于Python3.6环境中,virtualenv找不到命令的解决方法