NumPy简单入门教程

NumPy简单入门教程

NumPy是Python中的一个运算速度非常快的一个数学库,它非常重视数组。它允许你在Python中进行向量和矩阵计算,并且由于许多底层函数实际上是用C编写的,因此你可以体验在原生Python中永远无法体验到的速度。

 

#数组基础

#数组的创建

NumPy围绕这些称为数组的事物展开。实际上它被称之为 ndarrays。

定义一维数组
 

import numpy as np

#定义一维数组
my_array = np.array([1,2,3,4,5])
print(my_array)

输出为:

  [1,2,3,4,5]

定义二维数组

#定义二维数组
my_array = np.array([[1,2,3],[3,4,5]])
print(my_array)

输出为:

[[1 2 3]
 [3 4 5]]

定义一些特殊数组:

np.zeros((x,y))    #定义元素全为0的x行y列数组

np.ones((x,y))    #定义元素全为1的x行y列数组

np.random.random((x,y))    #每个元素都在0-1之间的x行y列随机数组

my_zero_array = np.zeros((2,5)) #2行5列的全零二维数组
print(my_zero_array)

my_one_array = np.ones((2,5)) #2行5列的全为1的二维数组
print(my_one_array)

my_random_array = np.random.random((2,5)) #2行5列的0~1之间随机数的二维数组
print(my_random_array)

输出为:

[[0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]]
[[1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]]
[[0.51120513 0.74959219 0.75214013 0.33745769 0.8484016 ]
 [0.14101515 0.92684853 0.23266783 0.37040777 0.98653671]]
[2 4]

 

#数组的运算

#数组运算
a = np.array([[1,2],[3,4]])
b = np.array([[2,2],[1,1]])
print("a = ",a)
print("b = ",b)
print("a + b = ",a + b)
print("a - b = ",a - b)
print("a * b = ",a * b)     #逐元素相乘
print("a / b = ",a / b)     #逐元素相除

输出结果:

a =  [[1 2]
 [3 4]]
b =  [[2 2]
 [1 1]]
a + b =  [[3 4]
 [4 5]]
a - b =  [[-1  0]
 [ 2  3]]
a * b =  [[2 4]
 [3 4]]
a / b =  [[0.5 1. ]
 [3.  4. ]]

 

矩阵乘法

a.dot(b)#矩阵a和矩阵b的矩阵乘法

print("矩阵a和矩阵的矩阵乘法:",a.dot(b))

输出结果:

矩阵a和矩阵的矩阵乘法: [[ 4  4]
 [10 10]]

 

#数组属性

ndarray.ndim 秩,即轴的数量或维度的数量
ndarray.shape 数组的维度,对于矩阵,n 行 m 列
ndarray.size 数组元素的总个数,相当于 .shape 中 n*m 的值
ndarray.dtype ndarray 对象的元素类型
ndarray.itemsize ndarray 对象中每个元素的大小,以字节为单位
ndarray.flags ndarray 对象的内存信息
ndarray.real ndarray元素的实部
ndarray.imag ndarray 元素的虚部
ndarray.data 包含实际数组元素的缓冲区,由于一般通过数组的索引获取元素,所以通常不需要使用这个属性。
print(type(a)) # >>>
print(a.dtype) # >>>int32
print(a.size) # >>>4
print(a.shape) # >>>(2,2)
print(a.itemsize) # >>>4
print(a.ndim) # >>>2
print(a.nbytes) # >>>16

ndarray.shape

ndarray.shape 表示数组的维度,返回一个元组,这个元组的长度就是维度的数目,即 ndim 属性(秩)。比如,一个二维数组,其维度表示"行数"和"列数"。

ndarray.reshape 

numpy.reshape 函数可以在不改变数据的条件下修改形状,格式如下: numpy.reshape(arr, newshape, order='C')

  • arr:要修改形状的数组
  • newshape:整数或者整数数组,新的形状应当兼容原有形状
  • order:'C' -- 按行,'F' -- 按列,'A' -- 原顺序,'k' -- 元素在内存中的出现顺序。
import numpy as np
 
a = np.arange(8)
print ('原始数组:')
print (a)
print ('\n')
 
b = a.reshape(4,2)
print ('修改后的数组:')
print (b)

 

#数组截取

Numpy提供了几种索引数组的方法。

切片(Slicing): 与Python列表类似,可以对numpy数组进行切片。由于数组可能是多维的,因此必须为数组的每个维指定一个切片:

import numpy as np

# Create the following rank 2 array with shape (3, 4)
# [[ 1  2  3  4]
#  [ 5  6  7  8]
#  [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
#  [6 7]]
b = a[:2, 1:3]

# A slice of an array is a view into the same data, so modifying it
# will modify the original array.
print(a[0, 1])   # Prints "2"
b[0, 0] = 77     # b[0, 0] is the same piece of data as a[0, 1]
print(a[0, 1])   # Prints "77"

你还可以将整数索引与切片索引混合使用。 但是,这样做会产生比原始数组更低级别的数组。 请注意,这与MATLAB处理数组切片的方式完全不同:

import numpy as np

# Create the following rank 2 array with shape (3, 4)
# [[ 1  2  3  4]
#  [ 5  6  7  8]
#  [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

# Two ways of accessing the data in the middle row of the array.
# Mixing integer indexing with slices yields an array of lower rank,
# while using only slices yields an array of the same rank as the
# original array:
row_r1 = a[1, :]    # Rank 1 view of the second row of a
row_r2 = a[1:2, :]  # Rank 2 view of the second row of a
print(row_r1, row_r1.shape)  # Prints "[5 6 7 8] (4,)"
print(row_r2, row_r2.shape)  # Prints "[[5 6 7 8]] (1, 4)"

# We can make the same distinction when accessing columns of an array:
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape)  # Prints "[ 2  6 10] (3,)"
print(col_r2, col_r2.shape)  # Prints "[[ 2]
                             #          [ 6]
                             #          [10]] (3, 1)"

整数数组索引: 使用切片索引到numpy数组时,生成的数组视图将始终是原始数组的子数组。 相反,整数数组索引允许你使用另一个数组中的数据构造任意数组。 这是一个例子:

import numpy as np

a = np.array([[1,2], [3, 4], [5, 6]])

# An example of integer array indexing.
# The returned array will have shape (3,) and
print(a[[0, 1, 2], [0, 1, 0]])  # Prints "[1 4 5]"

# The above example of integer array indexing is equivalent to this:
print(np.array([a[0, 0], a[1, 1], a[2, 0]]))  # Prints "[1 4 5]"

# When using integer array indexing, you can reuse the same
# element from the source array:
print(a[[0, 0], [1, 1]])  # Prints "[2 2]"

# Equivalent to the previous integer array indexing example
print(np.array([a[0, 1], a[0, 1]]))  # Prints "[2 2]"

整数数组索引的一个有用技巧是从矩阵的每一行中选择或改变一个元素:

import numpy as np

# Create a new array from which we will select elements
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])

print(a)  # prints "array([[ 1,  2,  3],
          #                [ 4,  5,  6],
          #                [ 7,  8,  9],
          #                [10, 11, 12]])"

# Create an array of indices
b = np.array([0, 2, 0, 1])

# Select one element from each row of a using the indices in b
print(a[np.arange(4), b])  # Prints "[ 1  6  7 11]"

# Mutate one element from each row of a using the indices in b
a[np.arange(4), b] += 10

print(a)  # prints "array([[11,  2,  3],
          #                [ 4,  5, 16],
          #                [17,  8,  9],
          #                [10, 21, 12]])

布尔数组索引: 布尔数组索引允许你选择数组的任意元素。通常,这种类型的索引用于选择满足某些条件的数组元素。下面是一个例子:

import numpy as np

a = np.array([[1,2], [3, 4], [5, 6]])

bool_idx = (a > 2)   # Find the elements of a that are bigger than 2;
                     # this returns a numpy array of Booleans of the same
                     # shape as a, where each slot of bool_idx tells
                     # whether that element of a is > 2.

print(bool_idx)      # Prints "[[False False]
                     #          [ True  True]
                     #          [ True  True]]"

# We use boolean array indexing to construct a rank 1 array
# consisting of the elements of a corresponding to the True values
# of bool_idx
print(a[bool_idx])  # Prints "[3 4 5 6]"

# We can do all of the above in a single concise statement:
print(a[a > 2])     # Prints "[3 4 5 6]"

 

#广播(Broadcasting)

广播是一种强大的机制,它允许numpy在执行算术运算时使用不同形状的数组。通常,我们有一个较小的数组和一个较大的数组,我们希望多次使用较小的数组来对较大的数组执行一些操作。

例如,假设我们要向矩阵的每一行添加一个常数向量。我们可以这样做:

import numpy as np

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x)   # Create an empty matrix with the same shape as x

# Add the vector v to each row of the matrix x with an explicit loop
for i in range(4):
    y[i, :] = x[i, :] + v

# Now y is the following
# [[ 2  2  4]
#  [ 5  5  7]
#  [ 8  8 10]
#  [11 11 13]]
print(y)

这会凑效; 但是当矩阵 x 非常大时,在Python中计算显式循环可能会很慢。注意,向矩阵 x 的每一行添加向量 v 等同于通过垂直堆叠多个 v 副本来形成矩阵 vv,然后执行元素的求和x 和 vv。 我们可以像如下这样实现这种方法:

import numpy as np

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
vv = np.tile(v, (4, 1))   # Stack 4 copies of v on top of each other
print(vv)                 # Prints "[[1 0 1]
                          #          [1 0 1]
                          #          [1 0 1]
                          #          [1 0 1]]"
y = x + vv  # Add x and vv elementwise
print(y)  # Prints "[[ 2  2  4
          #          [ 5  5  7]
          #          [ 8  8 10]
          #          [11 11 13]]"

Numpy广播允许我们在不实际创建v的多个副本的情况下执行此计算。考虑这个需求,使用广播如下:

import numpy as np

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v  # Add v to each row of x using broadcasting
print(y)  # Prints "[[ 2  2  4]
          #          [ 5  5  7]
          #          [ 8  8 10]
          #          [11 11 13]]"

y=x+v行即使x具有形状(4,3)v具有形状(3,),但由于广播的关系,该行的工作方式就好像v实际上具有形状(4,3),其中每一行都是v的副本,并且求和是按元素执行的。

将两个数组一起广播遵循以下规则:

  1. 如果数组不具有相同的rank,则将较低等级数组的形状添加1,直到两个形状具有相同的长度。
  2. 如果两个数组在维度上具有相同的大小,或者如果其中一个数组在该维度中的大小为1,则称这两个数组在维度上是兼容的。
  3. 如果数组在所有维度上兼容,则可以一起广播。
  4. 广播之后,每个阵列的行为就好像它的形状等于两个输入数组的形状的元素最大值。
  5. 在一个数组的大小为1且另一个数组的大小大于1的任何维度中,第一个数组的行为就像沿着该维度复制一样

如果对于以上的解释依然没有理解,请尝试阅读这篇文档或这篇解释中的说明。

支持广播的功能称为通用功能。你可以在这篇文档中找到所有通用功能的列表。

以下是广播的一些应用:

import numpy as np

# Compute outer product of vectors
v = np.array([1,2,3])  # v has shape (3,)
w = np.array([4,5])    # w has shape (2,)
# To compute an outer product, we first reshape v to be a column
# vector of shape (3, 1); we can then broadcast it against w to yield
# an output of shape (3, 2), which is the outer product of v and w:
# [[ 4  5]
#  [ 8 10]
#  [12 15]]
print(np.reshape(v, (3, 1)) * w)

# Add a vector to each row of a matrix
x = np.array([[1,2,3], [4,5,6]])
# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),
# giving the following matrix:
# [[2 4 6]
#  [5 7 9]]
print(x + v)

# Add a vector to each column of a matrix
# x has shape (2, 3) and w has shape (2,).
# If we transpose x then it has shape (3, 2) and can be broadcast
# against w to yield a result of shape (3, 2); transposing this result
# yields the final result of shape (2, 3) which is the matrix x with
# the vector w added to each column. Gives the following matrix:
# [[ 5  6  7]
#  [ 9 10 11]]
print((x.T + w).T)
# Another solution is to reshape w to be a column vector of shape (2, 1);
# we can then broadcast it directly against x to produce the same
# output.
print(x + np.reshape(w, (2, 1)))

# Multiply a matrix by a constant:
# x has shape (2, 3). Numpy treats scalars as arrays of shape ();
# these can be broadcast together to shape (2, 3), producing the
# following array:
# [[ 2  4  6]
#  [ 8 10 12]]
print(x * 2)

广播通常会使你的代码更简洁,效率更高,因此你应该尽可能地使用它。

 

你可能感兴趣的:(python)