博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python Numpy Tutorial——CS231n
阅读量:2032 次
发布时间:2019-04-28

本文共 5499 字,大约阅读时间需要 18 分钟。

开始学习CS231n,在Notes里面看到关于Numpy等内容的预备知识,现翻译一下此教程里,个人认为比较重要的内容

在开始前,此教程的地址为:. 有需要的同学可以直接查阅。

Numpy

Numpy是Python用于科学计算的核心库。它提供了高性能的多维度数组对象及操作数据的工具。如果你已对MATLAB比较熟悉了,那么这个教程对你开始使用Numpy会很有益处。

Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. If you are already familiar with MATLAB, you might find this tutorial useful to get started with Numpy.

Arrays

数组是一系列数,索引为非负整数. 我们用Python的List来初始化Numpy.Array,并用[](方括号)来获取对应的元素:

这里写图片描述

Numpy提供了很多的函数来创建数组(比如zeros(用于创建元素都为0的数组), ones(用于创建元素都为1的数组),full(用于创建元素为用户自定义的数组)等):

这里写图片描述

你可以自行查询其它的构造数组的方法.

1. Array indexing

Numpy 提供了一些用于数组索引的方法。

① Slicing(切片): 跟Python的列表相似,Numpy的数组也可以使用切片的功能。由于数组可以是多维度的,你必须指定数组中每个维度的切片。

Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array:

这里写图片描述

b[:2, 1:3] 为取前两行(0,1)和第2、3列,注意这里修改了b,但是对应a也改变了,这里b = a[:2, 1:3]默认为浅拷贝。

如果你想使得b和a完全独立,请使用b = copy.deepcopy(a[:2, 1:3])

当然,你也可以将整数索引和切片索引联用。然而,如果这样做,会导致数组维度的不一致,这跟MATLAB中有一些差别。

You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array. Note that this is quite different from the way that MATLAB handles array slicing:

这里写图片描述

以row_r1和row_r2为例,发现其实这两个数组内容是一样的,可是r2比r1多了一个维度[]。这里需要注意哦!

2. Integer array indexing(整数索引)

当你使用切片索引的时候,返回值通常为原数组的子数组形式。而当你使用整数索引,可以允许你从其它数组中构造任意的数组。

When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array. Here is an example:

这里写图片描述

索引的新方式:现有数组a = array([[1, 2], [3, 4], [5, 6]]),取a[[0, 0], [1, 2]]表示取a[0, 1]和a[0, 2]并把结果放入一个数组中。
这里写图片描述

One useful trick with integer array indexing is selecting or mutating one element from each row of a matrix:

这里写图片描述

如上,a[np.arange(4), [0, 2, 0, 1]] 等价于 np.array([a[0, 0], a[1, 2], a[2, 0], a[3, 1]])

3. Boolean array indexing(布尔索引)

布尔索引使得你可以从数组中挑出满足自定义条件(判别条件)的元素。

Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition. Here is an example:

这里写图片描述

需要注意的是,这里a[a > 2]返回的依然是数组,而不是List。
这里是简单的说明,关于Numpy数组的索引详细内容,请查看。

Datatypes

每个Numpy的数组都是由同一数据类型的数据组成。Numpy提供了大量的数值类型供你选择。Numpy默认会做推断类型的工作,但是我们构造一些数组的时候,有时也会指定数据类型。

Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. Here is an example:

这里写图片描述
这里,dtype就是data type的缩写。详细说明可查看

Array math

基本的数学函数在数组上的操作是以按照单元为基本粒度进行操作的,这些函数以numpy的函数操作符重载的形式存在。

Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module:

这里写图片描述

红色框框起来的表示两个操作的效果相同。注意,以乘法为例, 代表elementwise multiplication而不是矩阵乘法,矩阵乘法要使用
dot
:
这里写图片描述
其中,① 是向量相乘, ② 是矩阵和向量相乘, ③ 是矩阵乘法。(都是使用dot)。此外,Numpy还提供了很多数组级别(Arraywise)的运算操作函数(Numpy provides many useful functions for performing computations on arrays; one of the most useful is sum)
这里写图片描述
axis = 0表示按列, axis = 1表示按行,详细说明可查看

除了对数组进行计算意外,实际使用过程中,需要频繁的对数据进行reshape等操作。其中最简单的就是矩阵的转置(使用.T即可):

这里写图片描述

Broadcasting

Broadingcasting 是使得Numpy在不同shape的数组中进行算术操作的机制。常见的情况下,我们有小的数组和大的数组,我们希望将小的数组加、减…到大的数组中去

Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.

以下面的例子进行说明(将一个固定的向量加入到矩阵的每一行中)


第一种方法

这里写图片描述

这样虽然可以,不过有几点麻烦:① 如果x很大,用for循环会很慢 ②需要预先知道x的dimension

所以,我们还可以使用一种效率更高的方法来完成这种类型的操作:np.tile,np.tile(v, (4, 1))的含义是stacking multiple copies of v vertically

第二种方法

这里写图片描述

Numpy的broadcasting机制允许我们完成上面的操作,而不需要创建额外的vv:

这里写图片描述
这里写图片描述

Broadcasting两个数组需要遵循下面的原则:

  • If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.
  • The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.
  • The arrays can be broadcast together if they are compatible in all dimensions.
  • After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.
  • In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension

ps:读不太懂没关系,看下面的例子

这里写图片描述
Broadcasting 机制会使得你的代码更加简洁和快速,所以你应该尽可能努力的学习使用它。

SciPy

相较于Numpy, SciPy是基于Numpy并提供了很多作用于Numpy数组上的大量函数(useful for different types of scientific and engineering applications)。

熟悉Scipy的最好方式就是浏览其文档,在这里我们只强调一下我们在CS231n课上可能会用到的内容。

Image operations(不过一般很多人用opencv或者matplotlib做图片读取、resize等操作)

SciPy提供了一系列基本的数据读取操作。 比如, SciPy有一系列函数可以从磁盘中读取图片为Numpy数组的形式,也提供了将Numpy数组存入磁盘作为图片和resize图片的API。

这里写图片描述

MATLAB files

之前在airdoc实习的时候就遇到过需要读取的格式为mat的文件

函数 scipy.io.loadmatscipy.io.savemat 允许你读取Matlab文件。详细资料可以查看

Distance between points(点的距离)

Scipy 定义了一系列用于计算点集距离的函数。函数 scipy.spatial.distance.pdist 计算给定点集的所有对的距离。

The function scipy.spatial.distance.pdist computes the distance between all pairs of points in a given set:

这里写图片描述

Euclidean distance:欧氏距离
计算下图的欧式距离:是每一行代表的向量跟剩下几行所对应的向量求距离。
这里写图片描述
第一行从左到右分别表示x的第一行和第一行、第二行、第三行的距离;
第二行从左到右分别表示x的第二行和第一行、第二行、第三行的距离;

一个跟此函数类似的函数 :scipy.spatial.distance.cdist 用于计算两个点集之间所有可能的对的距离,可以阅读进行查看。

你可能感兴趣的文章
【Mybatis】【5】Oralce in 语句中当in(1,2,3...) 条件数量大于1000将会报错
查看>>
【JS】【14】判断对象是否为{}
查看>>
【Java】【18】去掉字符串的最后一个字符
查看>>
【Java】【22】读写properties文件
查看>>
【Maven】【2】遇到的问题
查看>>
【其他】【EditPlus】【1】操作使用
查看>>
【其他】【远程控制】【1】安装VNC
查看>>
【实战问题】【9】service层接口无法被注入调用
查看>>
【其他】【freemarker】【1】遇到的问题
查看>>
【Mybatis】【7】order by 使用动态参数时需要注意,用${}而不是#{}
查看>>
【Spring】【1】mybatis spring的自动扫描配置
查看>>
【JS】【19】使用Jquery判断是电脑或手机或微信浏览器访问
查看>>
【JS】【18】当前时间加减一天和格式化时间格式
查看>>
【Java】【23】汉字转拼音
查看>>
【Oracle】【17】表创建后,对表进行操作(添加字段,删除主键约束等)
查看>>
【JS】【20】点击页面判断是否安装app并打开,否则跳转下载的方法
查看>>
【Spring】【2】使用注解@Scheduled执行定时任务
查看>>
【JS】【22】标签的background-image属性
查看>>
【JS】【21】换行
查看>>
【Word&Excel】【3】Excel替换某一行/列的内容
查看>>