一、四则运算(运算都作用在各个元素上,可理解为批量操作):
- 加 a+b
- 减 a-b
- 乘 a*b (注意:不是矩阵或向量乘法)
- 除 a/b
>>> a = np.ones((2,3)) >>> b = np.random.rand(2,3) >>> a + b array([[ 1.31103566, 1.80777764, 1.66783499], [ 1.12616354, 1.76684873, 1.18431413]]) >>> a - b array([[ 0.68896434, 0.19222236, 0.33216501], [ 0.87383646, 0.23315127, 0.81568587]]) >>> a * b array([[ 0.31103566, 0.80777764, 0.66783499], [ 0.12616354, 0.76684873, 0.18431413]]) >>> a / b array([[ 3.21506541, 1.23796445, 1.49737586], [ 7.92621993, 1.30403815, 5.42552009]])
二、矩阵运算:
np.dot表示向量点积或者矩阵运算,两个向量可以直接做点积,不需要转置。
Unlike in many matrix languages, the product operator * operates elementwise in NumPy arrays. The matrix product can be performed using the dot function or method
>>> A = np.array( [[1,1], ... [0,1]] ) >>> B = np.array( [[2,0], ... [3,4]] ) >>> A*B # elementwise product array([[2, 0], [0, 4]]) >>> A.dot(B) # matrix product array([[5, 4], [3, 4]]) >>> np.dot(A, B) # another matrix product array([[5, 4], [3, 4]])
三、通用函数
包括如求和,开方,求均值等函数,非常方便。
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.
>>> B = np.arange(3) >>> B array([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.])