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

2023-11-18

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

课程链接: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 np

x = 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函数求导公式如下:

sigmoid\_derivative(x) = \sigma'(x) = \sigma(x) (1 - \sigma(x))

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 ds

x = 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 \frac{x}{\| x\|} (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_norm

    return 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_sum
   
    return s

x = 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:

\begin{align*} & L_1(\hat{y}, y) = \sum_{i=0}^m|y^{(i)} - \hat{y}^{(i)}| \end{align*}

def L1(yhat, y):
  
    loss = np.sum(abs(yhat-y))
    return loss

yhat = 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:

L_2(\hat{y},y) = \sum_{i=0}^m(y^{(i)} - \hat{y}^{(i)})^2

def L2(yhat, y):
  
    loss = np.dot((y-yhat),(y-yhat))  
    return loss

yhat = 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 - 推荐阅读:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

1.深度学习练习:Python Basics with Numpy(选修) 的相关文章

  • 出现异常时进行截图

    嘿 有没有一种方法可以在异常 任何异常 时捕获屏幕截图 我的 失败 解决方案位于BaseTestCase unittest TestCase子类 class BaseTestCase unittest TestCase classmetho
  • 在numpy中,[:,None]选择有什么作用?

    我正在学习 Udacity 的深度学习课程 我遇到了以下代码 def reformat dataset labels dataset dataset reshape 1 image size image size astype np flo
  • 如何分组显示argparse子命令?

    对于具有许多子命令的程序 我想在 help 输出中显示它们按逻辑分组 Python argparse 有一个add argument group http docs python org library argparse html argp
  • pandas 系列值之间的过滤

    If s is a pandas Series http pandas pydata org pandas docs stable dsintro html series 我知道我可以这样做 b s lt 4 or b s gt 0 但我做
  • 为什么 Python 中的无分支函数和内置函数速度较慢?

    我发现了 2 个无分支函数 它们可以在 python 中查找两个数字的最大值 并将它们与 if 语句和内置 max 函数进行比较 我认为无分支或内置函数将是最快的 但最快的是 if 语句函数 有人知道这是为什么吗 以下是功能 If 语句 2
  • Visual Studio Code 调试控制台中的 pydevd 警告

    我已经搜索了一段时间但找不到任何相关问题 当使用 Visual Studio Code 和 Python 扩展来调试大型元素时 计算表示或获取属性可能需要一些时间 在这些情况下 会出现如下警告 pydevd 警告 计算 DataFrame
  • Python 中字典的合并层次结构

    我有两本词典 而我想做的事情有点奇怪 基本上 我想合并它们 这很简单 但它们是字典的层次结构 我想以这样的方式合并它们 如果字典中的项目本身就是字典并且存在于两者中 我也想合并这些字典 如果它不是字典 我希望第二个字典中的值覆盖第一个字典中
  • Python 2.7从非默认目录打开多个文件(对于opencv)

    我在 64 位 win7 上使用 python 2 7 并拥有 opencv 2 4 x 当我写 cv2 imread pic 时 它会在我的默认 python 路径中打开 pic 即C Users Myname 但是我如何设法浏览不同的目
  • Pandas系列矢量化文本处理

    我想使用矢量化操作改进我的 Pandas 代码 假设我有一个简单的 DataFrame 其中有一个文本列 其中可能包含 url Column1 0 hello http www google com 1 bye www mail com w
  • 如何获取一个类的所有实例

    我是一名初学者 正在学习 Python 我想创建一个课程Person 在构造函数中 我想将我创建的每个实例放入一个名为 实例 的集合中 然后我希望实例 方法返回所有实例 我怎样才能做到这一点 class Person Type annota
  • 字典键中的通配符

    假设我有一本字典 rank dict V 1 A 2 V 3 A 4 正如您所看到的 我在一个 V 的末尾添加了一个 虽然 3 可能只是 V 的值 但我想要 V1 V2 V2234432 等的另一个密钥 我想检查它 checker V30
  • 使用 ruamel.yaml,如何使带有 NEWLINE 的变量成为不带引号的多行

    我正在生成用作协议的 YAML 其中包含一些生成的 JSON import json from ruamel import yaml jsonsample id 123 type customer account other myyamel
  • Python 请求包含有值的参数和没有值的参数

    我正在为 API 编写一个 Python 包装器 该 API 支持具有值的查询参数 例如param1如下 和查询参数do not有价值观 例如param2如下 即 https example com service param1 value
  • 如何从张量流数据集迭代器返回同一批次两次?

    我正在转换一些旧代码以使用数据集 API 此代码使用feed dict将一批数据送入列车运行 实际上是三次 然后重新计算损失以供显示使用同一批 所以我需要一个迭代器来返回完全相同的批次两次 或多次 不幸的是 我似乎找不到一种使用张量流数据集
  • 如何在 django-rest-framework 查询集响应中添加注释数据?

    我正在为查询集中的每个项目生成聚合 def get queryset self from django db models import Count queryset Book objects annotate Count authors
  • 如何导入 boto3 ssm ParameterNotFound 异常?

    我想import the exception当一个boto3 ssm找不到参数get parameter 我正在尝试添加一些额外的内容ssm的功能moto图书馆 但我现在很困惑 gt gt gt import boto3 gt gt gt
  • 通过 Selenium 和 python 切换到 iframe

    我如何在硒中切换到这个 iframe 只知道 您可以使用 XPath 来定位 iframe driver find element by xpath iframe name Dialogue Window Then switch to th
  • 忽略稀疏矩阵中的重复条目

    我尝试过初始化csc matrix and csr matrix从列表中 data rows cols 值如文档所示 sparse csc matrix data rows cols shape n n 问题是 我实际上拥有的生成方法dat
  • Pandas 数据透视表同时包含多列

    我怀疑是否pandas pivot table可以一次接受两列并单独处理它们 而不是分层处理 假设我有以下数据框 id date day val 101 11 1 1 1 2 1 101 11 1 2 2 2 2 101 11 1 3 3
  • 捕获 subprocess.run() 的输入

    我在 Windows 上有一个交互式命令行 exe 文件 是由其他人编写的 当程序出现异常时 它会终止 并且我对程序的所有输入都会丢失 所以我正在编写一个 python 程序 它调用一个阻塞子进程subprocess run 并捕获所有输入

随机推荐

  • Oracle表空间详细介绍

    表空间概述 Oracle的表空间属于Oracle中的存储结构 是一种用于存储数据库对象 如 数据文件 的逻辑空间 是Oracle中信息存储的最大逻辑单元 其下还包含有段 区 数据块等逻辑数据类型 表空间是在数据库中开辟的一个空间 用于存放数
  • 小白入门angular(一)

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 操作系统 window 10 IDE webstorm 步骤一 安装nodeJS 链接为https nodejs org en 选择对应的node版本 安装node时会自动
  • Python基础知识第四篇:方法重写+文件处理+异常处理,冒死上传

    Python基础知识第四篇 基础知识第一话 基础知识第二话 基础知识第三话 今天给大家分享的是第四篇 前面几篇我都放在上面了 小伙伴可以自己领取巩固复习 方法重写 Python学习交流Q群 906715085 print 方法重写 codi
  • MATLAB滤波算法和LabVIEW心电图诊断系统

    心电图的生理 我们的目标是构建一个心电图 ECG 它不仅可以自动计算心率 还可以检测其他心脏异常 这需要对 ECG 信号进行更高级的分析 为了实现这一目标 需要完成几个步骤 如下面的流程图所示 在我们详细介绍如何构建 ECG 之前 了解 E
  • Stata学习笔记

    目录 数据的三种类型 在stata中以颜色区分 类型转化 1 destring 红转黑 限于第一种红色 2 tostring 黑转红 3 encode 红转蓝 限于第二种红色 4 label define label value 黑转蓝 5
  • rk3568 nvme硬盘分区,格式化,挂载测试

    前言 环境介绍 1 编译环境 Ubuntu 18 04 5 LTS 2 SDK rk356x linux 3 单板 迅为itop 3568开发板 自制底板 一 查看硬盘 插上硬盘上电 进入系统后通过命令lspci查看nvme硬盘识别情况 r
  • 容灾备份

    欢迎关注 全栈工程师修炼指南 公众号 点击 下方卡片 即可关注我哟 设为 星标 每天带你 基础入门 到 进阶实践 再到 放弃学习 涉及 企业运维 网络安全 应用开发 物联网 人工智能 大数据 学习知识 花开堪折直须折 莫待无花空折枝 作者主
  • 使用UE4插件SimpleHTTP的技巧

    UE4插件名 SimpleHTTP 版本 1 1 目录 前置工作 上传资源 下载资源 删除资源 SimpleHTTP源码接口 哈喽大家好 我叫人宅 这节课我们来讲解一下SimpleHTTP使用技巧 该插件目前提供了对web服务器进行上传下载
  • 软件测试的一点心得体会

    在学习软件测试之前 我们先要知道什么是软件测试 只有知道了软件测试是做什么的 我们才能更深入的去理解它 在我的印象里 软件测试就是通过人工或者自动化的方式对软件进行检测 并发现软件的缺陷的一个过程 而软件测试工程师就相当于质检员的角色 在软
  • 深度学习:Keras入门(一)之基础篇

    1 关于Keras 1 简介 Keras是由纯python编写的基于theano tensorflow的深度学习框架 Keras是一个高层神经网络API 支持快速实验 能够把你的idea迅速转换为结果 如果有如下需求 可以优先选择Keras
  • python 指定值的位置_python数组查找某个值的位置

    python如何返回数组中某值在数组的位置 python3里这样 gt gt gt a 1 2 3 gt gt gt b 2 gt gt gt b in a True 先判定b在a里 gt gt gt a index b 1 b在a的位置1
  • RKNPU2通用API和零拷贝API

    RKNPU2通用API 通用API接口按照异构编程规范 需要将数据拷贝到NPU运行时的内存空间 通用API部署流程 初始化上下文 需要先创建上下文对象和读取模型文件 rknn context ctx model load model mod
  • 微信小程序商城--隐私协议--模板参考

    本隐私政策与您所使用的XX 替换成软件名称 服务以及该服务所包括的各种业务功能 以下统称 我们的产品与 或服务 息息相关 希望您在使用我们的产品与 或服务前仔细阅读并确认您已经充分理解本隐私政策所写明的内容 并让您可以按照本隐私政策的指引做
  • Poi模板技术

    Poi模板技术导入导出Excel 在我们的工作中 也经常会用到Poi模板技术操作Excel文件数据 而且不同的应用场景对Excel表格的单元格格式和合并操作都需要写大量的代码调试 比较麻烦 通过模板技术将自定义格式的Excel文件模板存放在
  • 【云原生之Docker实战】使用docker部署PicUploader图床工具

    云原生之Docker实战 使用docker部署PicUploader图床工具 一 PicUploader介绍 1 PicUploader介绍 2 PicUploader特点 二 检查本地系统环境 1 检查系统版本 2 检查系统内核版本 三
  • 对聊天室的优化&常用参数配置

    优化处1 编码和解码 编码解码用的是JDK 对象与数组的转换 这种虽然简单 但是效率不高 现在需要支持更多的序列化算法 就需要改进 抽取一个接口 Serializer 用以支持 序列化和 反序列化 package com zhao prot
  • educoder答案-Python编程训练-顺序与选择结构-太原理工大学

    太原理工大学 educoder实训平台答案 Python编程基础 持续更新 以下均为太原理工大学廖丽娟老师的实训项目内容答案 各位校友自取 第一关 顺序结构 changeOne int input changeTwo int input p
  • input输入框自动去除空格

    1 只去除两端空格
  • 加密证书的三大好处 122.228.86.6

    SSL证书有什么特点 1 数据加密传输 采用HTTPS加密APP及网页通讯 防止数据在传送过程中被窃取 篡改 确保数据的完整性 防止运营商的流量劫持 网页植入广告现象 同时有效抵挡中间人的攻击 大大提升安全性 2 高兼容性 兼容性关系到用户
  • 1.深度学习练习:Python Basics with Numpy(选修)

    本文节选自吴恩达老师 深度学习专项课程 编程作业 在此表示感谢 课程链接 https www deeplearning ai deep learning specialization 目录 1 Building basic function