当前位置: 澳门新濠3559 > 编程 > 正文

澳门新濠3559Numpy中的维度称为称为axes,轴的个数

时间:2019-11-09 19:36来源:编程
原文:  NumPy's main object is the homogeneous multidimensional array. It is atable of elements (usually numbers), all of the same type, indexed by atuple of positive integers. In NumPy dimensions are called axes. Thenumber of axes is r

原文: 

NumPy's main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In NumPy dimensions are called axes. The number of axes is rank.

The Basics

NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy dimensions are called axes. The number of axes is rank.

Numpy的主要对象是同类的多维数组。Numpy是一个具有相同类型数值的表,表的内容可以通过一个tuple来索引。Numpy中的维度称为称为axes,axes的数量称为rank

Numpy’s array class is called ndarray. It is also known by the alias array. Note that numpy.array is not the same as the Standard Python Library class array.array, which only handles one-dimensional arrays and offers less functionality. The more important attributes of an ndarray object are:

Numpy的数组类称为ndarray,也称作别名数组。numpy.array与Python标准库里的array.array类并不一样,标准库里的数组只能是一维的而且功能很少。ndarray对象的重要属性展示如下:

  • ndarray.ndim 返回一个number,维度,axes数,rank值
    the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.
  • ndarray.shape 返回一个tuple,表示形状,如(2,3)表示2x3,(3,3,3)表示3x3x3
    the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.
  • ndarray.size 返回一个number,表示ndarray澳门新濠3559Numpy中的维度称为称为axes,轴的个数被称作秩。中所有元素的个数,等价于shape中各个元素的乘积
    the total number of elements of the array. This is equal to the product of the elements of shape.
  • ndarray.dtype 返回一个dtype对象,表示ndarray中元素的类型
    an object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples.
  • ndarray.itemsize
    the size in bytes of each element of the array. For example, an array of elements of type float64 hasitemsize
    8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent tondarray.dtype.itemsize.
  • ndarray.data
    the buffer containing the actual elements of the array. Normally, we won’t need to use this attribute because we will access the elements in an array using indexing facilities.

The Basics


NumPy’s main object is the homogeneous(同类型的) multidimensional(多维) array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In NumPy dimensions are called axes(轴). The number of axes is rank.

For example, the coordinates(坐标) of a point in 3D space [1, 2, 1] is an array of rank 1, because it has one axis. That axis has a length of 3. In the example pictured below, the array has rank 2 (it is 2-dimensional). The first dimension (axis) has a length of 2, the second dimension has a length of 3.

[

[1,2,3],

[4,5,6]

]

NumPy’s array class is called ndarray. It is also known by the alias array. Note that numpy.array is not the same as the Standard Python Library class array.array, which only handles one-dimensional arrays and offers less functionality. The more important attributes of an ndarray object are:

ndarray.ndim(维度):

the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.

ndarray.shape(形状):

the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix(矩阵) with rows and columns, shape will be(n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.

ndarray.size(元素个数)

the total number of elements of the array. This is equal to the product(乘积) of the elements of shape.

ndarray.dtype(元素类型):

an object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples.

ndarray.itemsize(元素大小):

the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize.

ndarray.data:

the buffer containing the actual elements of the array. Normally, we won’t need to use this attribute because we will access the elements in an array using indexing facilities.

An example:

>>>import numpy as np

>>> a = np.arange(15).reshape(3,5)

>>> a

array([[0,1,2,3,4],

[5,6,7,8,9],

[10,11,12,13,14]])

>>> a.shape

(3,5)

>>> a.ndim

2

>>> a.dtype.name

'int64'

>>> a.itemsize

8

>>> a.size

15

>>>type(a)

>>> b = np.array([6,7,8])

>>> b

array([6,7,8])

>>>type(b)

一、官网的定义:

For example, the coordinates of a point in 3D space [1, 2, 1] is an array of rank 1, because it has one axis. That axis has a length of 3. In the example pictured below, the array has rank 2 (it is 2-dimensional). The first dimension (axis) has a length of 2, the second dimension has a length of 3.

Array Creation

有几种方式可以产生数组,可以使用array方法通过常规的Python list或者tuple来生成数组

  1. ndarray.array(seq[, dtype='']) 参数必须为sequence, 这个seq可以是单一的seq也可以是seq的seq的seq...,对应着产生几维的array。也可以同时指定元素类型
>>> b = np.array([1.2, 3.5, 5.1])      #seq
>>> b.dtypedtype('float64')

>>> b = np.array([(1.5,2,3), (4,5,6)])    #seq of seq
>>> b
array([[ 1.5, 2. , 3. ], [ 4. , 5. , 6. ]])

>>> c = np.array( [ [1,2], [3,4] ], dtype=complex )
>>> c
array([[ 1.+0.j, 2.+0.j], [ 3.+0.j, 4.+0.j]])
  1. 有时候不知道数组的元素,却知道数组的shape,这时可以通过以下三种方法生产数组
  • zeros(tuple, dtype) : np.zeros( (3,4) ),3x4全零数组
  • ones(tuple, dtype) :np.ones( (2,3,4), dtype=np.int16 ),2x3x4全1数组
  • empty(tuple):np.empty( (2,3) ),随机数组
  1. arange(init,stop,step) 类似Python中标准的range函数,step为间隔长度
  2. linspace(init,stop,segment) segment为array的长度

[[ 1., 0., 0.],
 [ 0., 1., 2.]]

Printing Arrays

print()函数这样展示数组

  • 最后一个轴从左往右打印,
  • 倒数第二个轴从上往下打印,
  • 其余的也是从上往下打印,只是规模变大了。

如果数组太大,打印会省略一部分

>>> print(np.arange(10000))
[ 0 1 2 ..., 9997 9998 9999]

In NumPy dimensions are called axes.

ndarray.ndim

Basic Operations

  1. 算术操作 (Arithmetic operators on arrays apply elementwise.)
  • +,-,*,/,四则运算
  • ** 乘方运算
  • >,<, == 逻辑运算,返回布尔数组

这几种操作都是elementwise operation,都是针对数组元素的操作。

  1. matrix product
  • A.dot(B)
  • np.dot(A, B)
  1. 求和与极值,可以通过axis选择数组的轴
  • A.sum(axis)
  • A.min(axis)
  • A.max(axis)
>>> b = np.arange(12).reshape(3,4)
>>> b
array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
>>>
>>> b.sum(axis=0) # sum of each column
array([12, 15, 18, 21])
>>>
>>> b.min(axis=1) # min of each row
array([0, 4, 8])
>>>
>>> b.cumsum(axis=1) # cumulative sum along each row
array([[ 0, 1, 3, 6], [ 4, 9, 15, 22], [ 8, 17, 27, 38]])

For example, the coordinates of a point in 3D space [1, 2, 1] has one axis. That axis has 3 elements in it, so we say it has a length of 3. In the example pictured below, the array has 2 axes. The first axis has a length of 2, the second axis has a length of 3.

数组轴的个数,在python的世界中,轴的个数被称作秩

Universal Functions¶

NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called “universal functions” (ufunc). Within NumPy, these functions operate elementwise on an array, producing an array as output.

Numpy提供了像sin,cos,exp这样类似的数学函数。在Numpy,它们被称作全局函数。这些函数操作数组的所有元素,产生一个输出数组。

>>> B = np.arange(3)
>>> Barray([0, 1, 2])
>>> np.exp(B)
array([ 1. , 2.71828183, 7.3890561 ])
>>> np.sqrt(B)
array([ 0. , 1. , 1.41421356])
>>> C = np.array([2., -1., 4.])
>>> np.add(B, C)
array([ 2., 0., 6.])
[[ 1., 0., 0.],
 [ 0., 1., 2.]]
>> X = np.reshape(np.arange(24), (2, 3, 4))
  # 也即 2 行 3 列的 4 个平面(plane)
>> X
array([[[ 0, 1, 2, 3],
    [ 4, 5, 6, 7],
    [ 8, 9, 10, 11]],
    [[12, 13, 14, 15],
    [16, 17, 18, 19],
    [20, 21, 22, 23]]])

Indexing, Slicing and Iterating 索引,切片和迭代

  1. 一维数组的索引,切片和迭代就像python中常用的sequence一样。

  2. 多维数组每个轴有一个索引, 这些下标用逗号分割的tuple表示,表示方法与matlab相似。省略的下标表示全部索引

  3. 当数组的维度比较大时,可以使用...来省略索引。对于rank=5的数组:

  • x[1,2,...] is equivalent to x[1,2,:,:,:]
  • x[...,3] to x[:,:,:,:,3] and
  • x[4,...,5,:] to x[4,:,:,5,:]
  1. 迭代。多维数组的第一个轴作为迭代轴for row in b: print(row)打印的是b的第一个轴即行。可以用flat属性把多维数组的元素全部展开for element in b.flat: print(element),这样能打印b的所有元素。

其实,可以这么理解。维度(dimension) D和数组A,D[axis]和A[i] 。是不是大概懂了,axis对应第几维度,与数组的下标的作用差不多。但是axis有点区别的。既然axis是下标那么就有范围:

shape函数是numpy.core.fromnumeric中的函数,它的功能是读取矩阵的长度,比如shape[0]就是读取矩阵第一维度的长度。

Shape Manipulation

  1. 改变数组的形状
>>> a = np.floor(10*np.random.random((3,4)))
>>> a
array([[ 2., 8., 0., 6.], 
          [ 4., 5., 1., 1.], 
          [ 8., 9., 3., 6.]])
>>> a.shape
(3, 4)
>>> a.ravel() # flatten the array
array([ 2., 8., 0., 6., 4., 5., 1., 1., 8., 9., 3., 6.])
>>> a.shape = (6, 2)
>>> a.T
array([[ 2., 0., 4., 1., 8., 3.], 
          [ 8., 6., 5., 1., 9., 6.]])
  1. 把不同的数组堆到一起

[-维度,维度),如上例子axis的取值范围 [-2,2),记住不包括2。

shape(x)

Random sampling (numpy.random)

1
1
11
1
1
1
1
1
11
1
1
1
11

维度与axis的对应关系:axis是从最外层的 [] 数起来的,如上的例子,axis=0:第二维,axis=1:第一维。

(2,3,4)

二、验证:

shape(x)[0]

1 # 产生24个[0,50)的随机整数,维度为3
2 x = np.random.RandomState(5).randint(50, size=[2, 3, 4])
3 print(x.ndim, x.shape, x.size)
4 print("x:n", x)

2

澳门新濠3559 1

或者

选一个能够使用到axis的函数:这里选用numpy.amax()(选出最大的元素),

x.shape[0]

为了方便理解,先从最内层开始

2

1 print("x[0][0]:n", x[0][0])
2 print("axis=2: n", np.amax(x, 2))

再来分别看每一个平面的构成:

澳门新濠3559 2

>> X[:, :, 0]
array([[ 0, 4, 8],
    [12, 16, 20]])
>> X[:, :, 1]
array([[ 1, 5, 9],
    [13, 17, 21]])
>> X[:, :, 2]
array([[ 2, 6, 10],
    [14, 18, 22]])
>> X[:, :, 3]
array([[ 3, 7, 11],
    [15, 19, 23]])

 

也即在对 np.arange(24)(0, 1, 2, 3, ..., 23) 进行重新的排列时,在多维数组的多个轴的方向上,先分配最后一个轴(对于二维数组,即先分配行的方向,对于三维数组即先分配平面的方向)

print("x[0]:n", x[0])
print("axis=1: n", np.amax(x, 1))

reshpae,是数组对象中的方法,用于改变数组的形状。

 澳门新濠3559 3

二维数组

1 print("x:n", x)
2 print("axis=0: n", np.amax(x, 0))
#!/usr/bin/env python 
# coding=utf-8 
import numpy as np 

a=np.array([1, 2, 3, 4, 5, 6, 7, 8]) 
print a 
d=a.reshape((2,4)) 
print d 

澳门新濠3559 4

澳门新濠3559 5

很显然,从axis=2,axis=1都挺好理解,但是axis=0就有点困惑了,而且这个仅仅是三维而已,那么四维、五维呢。

三维数组

但是其实仔细观察axis=2的第一个数字54是怎么来的呢?是从x[0][0][0]—x[0][0][4]比较而得。因此一共有3*4个。

#!/usr/bin/env python 
# coding=utf-8 
import numpy as np 

a=np.array([1, 2, 3, 4, 5, 6, 7, 8]) 
print a 
f=a.reshape((2, 2, 2)) 
print f 

同理axis=1时,比较的就是:x[0][0][0]—x[0][3][0],共3*5个

澳门新濠3559 6

同理axis=2时,比较的是:x[0][0][0]—x[2][0][0],共4*澳门新濠3559,5个

形状变化的原则是数组元素不能发生改变,比如这样写就是错误的,因为数组元素发生了变化。

现在,是不是就对不同的axis的输出的形状或者说排列有一定的了解了?而且是不是体会到axis的作用了?我可是烦死那么多方括号了!!

#!/usr/bin/env python 
# coding=utf-8 
import numpy as np 

a=np.array([1, 2, 3, 4, 5, 6, 7, 8]) 
print a 
print a.dtype 
e=a.reshape((2,2)) 
print e 

 三、总结

澳门新濠3559 7

最直观的:函数所选的axis的值,就表明 x[][][] 的第几个方块号,从0开始,代表第一个[ ],即x[ ] [ ] [ ]

注意:通过reshape生成的新数组和原始数组公用一个内存,也就是说,假如更改一个数组的元素,另一个数组也将发生改变。

不足或者错误之处,欢迎指正!

#!/usr/bin/env python 
# coding=utf-8 
import numpy as np 

a=np.array([1, 2, 3, 4, 5, 6, 7, 8]) 
print a 
e=a.reshape((2, 4)) 
print e 
a[1]=100 
print a 
print e 

澳门新濠3559 8澳门新濠3559 9

澳门新濠3559 10

 1 import numpy as np
 2 
 3 # 产生60个[0,60)的随机整数,维度为3
 4 x = np.random.RandomState(5).randint(60, size=[3, 4, 5])
 5 print(x.ndim, x.shape, x.size)
 6 print("x:n", x)
 7 print("x[0][0]:n", x[0][0])
 8 print("axis=2: n", np.amax(x, 2))
 9 
10 print("x[0]:n", x[0])
11 print("axis=1: n", np.amax(x, 1))
12 
13 print("x:n", x)
14 print("axis=0: n", np.amax(x, 0))
15 print("n", np.amin(x, 0))
16 for i in range(4):
17     print(x[0][i][1])

Python中reshape函数参数-1的意思

全部代码

a=np.arange(0, 60, 10)
>>>a
array([0,10,20,30,40,50])
>>>a.reshape(-1,1)
array([[0],
[10],
[20],
[30],
[40],
[50]])

 

如果写成a.reshape(1,1)就会报错

ValueError:cannot reshape array of size 6 into shape (1,1)

>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
array([[1, 2],
    [3, 4],
    [5, 6]])

-1表示我懒得计算该填什么数字,由python通过a和其他的值3推测出来。

# 下面是两张2*3大小的照片(不知道有几张照片用-1代替),如何把所有二维照片给摊平成一维
>>> image = np.array([[[1,2,3], [4,5,6]], [[1,1,1], [1,1,1]]])
>>> image.shape
(2, 2, 3)
>>> image.reshape((-1, 6))
array([[1, 2, 3, 4, 5, 6],
    [1, 1, 1, 1, 1, 1]])

以上这篇对numpy中轴与维度的理解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

编辑:编程 本文来源:澳门新濠3559Numpy中的维度称为称为axes,轴的个数

关键词: