python中的*、np.dot和np.multiply辨析

在之前学习别人开源代码的时候,对于python中的*、np.dot()和np.multiply()具体结果产生了疑惑,遂去了解了一下相关说明,并实验了一下,结合别人的博客,这里进行总结


建议:当我们需要在python中进行像matlab中的矩阵运算时,最好将ndarray转化成matrix,以免出错

  1. * 号运算符

numpy arrays consistently abide by the rule that operations are applied element-wise. Thus, if a and b are numpy arrays, then a*b is the array formed by multiplying the components element-wise。

  • 对于ndarray, * 表示的是multiplying the components element-wise,按位相乘, 必要时需要广播,广播细节可以看下面的例子
a = np.array(range(6)).reshape((2, 3))
b = np.array([1, 0, 1])
print(b.shape)
# shape=(3,)
bt = b.T
print(bt.shape)
# shape=(3,)
print(a)
# [[0 1 2]
#  [3 4 5]]
print(b)
# [1 0 1]
c = a * b
print(c)
# broadcast operation
# [[0 0 2]
#  [3 0 5]]
d = a * b.T
print(d)
#[[0 0 2]
# [3 0 5]]

这里的广播,举个简单的例子:
(2,3)的array * (3,)的array,会自动广播,变成(2,3)和(2,3)的array按位相乘

  • 对于 matrix,*表示矩阵乘法,运算保证矩阵乘法的法则,例子如下:
A = np.matrix(a)
B = np.matrix(b)
print('A:' + str(A))
# A:[[0 1 2]
     [3 4 5]]

B:[[1 0 1]]
B.shape:(1, 3)
print('A:' + str(A.shape))
# A.shape:(2, 3)
print('B:' + str(B))
# B:[[1 0 1]]
print('shape:' + str(B.shape))
# B.shape:(1, 3)
C = A * B
#  Traceback (most recent call last):
#  	File "D:/IR/MLPY/Tagging/temp.py", line 37, in <module>
#    	C = A * B
#  	File "D:\Anaconda\lib\site-packages\numpy\matrixlib\defmatrix.py", 	
#        line 343, in __mul__
#    return N.dot(self, asmatrix(other))
#	ValueError: shapes (2,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)
C = A * B.T
# C:[[2]
#    [8]]
# C.shape:(2, 1)
  1. np.dot()

官方文档:Dot product of two arrays.
For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b

  • 对于ndarray ,一般情况下,都是进行矩阵乘法或者向量的内积运算。但这仅仅是等价于矩阵相乘,但等于就是矩阵相乘。对于ndarray,有时,dot的运算并不要求操作数像矩阵相乘的要求那么严格,当然相乘的结果的格式也不是矩阵,而是数组
print(np.dot(a, b))
# [2, 8]

  • 但是对于matrix,矩阵相乘就是矩阵相乘,严格要求,所以必须满足矩阵相乘的条件
  1. np.multiply()

multiply是numpy的ufunc函数,执行方法是对应元素相乘,而不是线性代数中的矩阵运算方式,类似于matlab中的点乘,当矩阵的维度不相同时,会根据一定的广播规则将维数扩充到一致的形式. 如果不能广播相同的size,multiply就会失败

np.multiply(a,b)                                                             # [[0, 0, 2],
#  [3, 0, 5]]
np.multiply(a,b.T)
# [[0, 0, 2],
#  [3, 0, 5]]
np.multiply(A,B)                                                             # [[0, 0, 2],
#  [3, 0, 5]]
np.multiply(A,B.T)                                                           # Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2,3) (3,1) 

(2,3) 去和(1,3)按位乘,后者广播成为(2,3)
(2,3) 去和(3,1)按位乘,后者任一维度广播不能成为(2,3),遂报错


参考:numpy * dot multiply

### Python Numpy `np.dot` 函数详解 #### 功能描述 `np.dot` 是 NumPy中的一个重要函数,用于计算两个数组间的点积。对于二维数组而言,这相当于执行矩阵乘法;而对于一维数组,则是它们对应位置元素相乘后的求操作[^1]。 #### 参数解释 该方法接受两个主要参数: - **a**: 输入的第一个数组。 - **b**: 输入的第二个数组。 此外还可以接收其他可选参数如 `out` 来指定输出缓冲区的位置[^2]。 #### 返回值 返回的是输入数组按规则计算得到的结果数组或标量值(当两者均为向量时)。如果第一个参数是一维而另一个不是,则会抛出错误提示不兼容的操作数形状[^4]。 #### 示例代码展示 下面通过具体例子来理解如何使用此功能: ```python import numpy as np # 一维数组之间做内积运算 vector_a = np.array([1, 2, 3]) vector_b = np.array([4, 5, 6]) result_vector_dot = vector_a @ vector_b # 或者使用 np.dot(vector_a, vector_b) print(f"Vector dot product result: {result_vector_dot}") # 输出应为 32 # 矩阵间进行标准矩阵乘法 matrix_c = np.mat([[1, 2], [3, 4]]) matrix_d = np.mat([[4, 5], [6, 7]]) result_matrix_multiply = matrix_c * matrix_d # 对于mat对象可以直接用*号代替dot() alternative_result = np.dot(matrix_c, matrix_d) print("Matrix multiplication results:") print(alternative_result) ``` 上述代码展示了两种不同类型的输入——向量与矩阵下 `np.dot()` 的应用方式及其预期输出效果[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值