numpy里*与dot与multiply

Posted chen狗蛋儿

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了numpy里*与dot与multiply相关的知识,希望对你有一定的参考价值。

一、*   dot()   multiply()

1, 对于array来说,* 和 dot()运算不同,* 和 multiply()运算相同

*和multiply() 是每个元素对应相乘

dot() 是矩阵乘法

2, 对于matrix来说,* 和 multiply() 运算不同

* 和dot() 是矩阵乘法

multiply()  是每个元素对应相乘

 

3, 混合的时候(与矩阵同)

multiply 为对应乘

*为 矩阵乘法(但无下述适应性)

dot为矩阵乘法(矩阵在前数组在后时,均为一维时数组可适应,即能做矩阵乘法)

 

Python 3.6.4 (default, Jan 7 2018, 03:52:16)
[GCC 4.2.1 Compatible android Clang 5.0.300080 ] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> a1=np.array([1,2,3])
>>> a1*a1
array([1, 4, 9])
>>> np.dot(a1,a1)
14
>>> np.multiply(a1,a1)
array([1, 4, 9])
>>> m1 = np.mat(a1)
>>> m1
matrix([[1, 2, 3]])
>>> m1*m1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/data/data/com.termux/files/usr/lib/python3.6/site-packages/numpy-1.13.3-py3.6-linux-aarch64.egg/numpy/matrixlib/defmatrix.py", line 309, in __mul__
return N.dot(self, asmatrix(other))
ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)
>>> np.dot(m1,m1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)
>>> np.multiply(m1,m1)
matrix([[1, 4, 9]])
>>> np.multiply(a1,m1)
matrix([[1, 4, 9]])
>>> np.multiply(m1,a1)
matrix([[1, 4, 9]])
>>> np.dot(a1,m1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shapes (3,) and (1,3) not aligned: 3 (dim 0) != 1 (dim 0)
>>> np.dot(m1,a1)
matrix([[14]])
>>> a1*m1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/data/data/com.termux/files/usr/lib/python3.6/site-packages/numpy-1.13.3-py3.6-linux-aarch64.egg/numpy/matrixlib/defmatrix.py", line 315, in __rmul__
return N.dot(other, self)
ValueError: shapes (3,) and (1,3) not aligned: 3 (dim 0) != 1 (dim 0)
>>> m1*a1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/data/data/com.termux/files/usr/lib/python3.6/site-packages/numpy-1.13.3-py3.6-linux-aarch64.egg/numpy/matrixlib/defmatrix.py", line 309, in __mul__
return N.dot(self, asmatrix(other))
ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)
>>> a1,m1
(array([1, 2, 3]), matrix([[1, 2, 3]]))
>>>

 

以上是关于numpy里*与dot与multiply的主要内容,如果未能解决你的问题,请参考以下文章

将高阶矩阵与 numpy 相乘

Numpy:将矩阵与 3d 张量相乘——建议

numpy使用np.dot函数或者@操作符计算两个numpy数组的点积数量积(dot productscalar product)

Numpy:点积和 dot() 矩阵相乘

numpy中dot, multiply, *区别

Numpy数据的操作 * dot() multiply() 的区别