numpy.dot(), numpy.multiply(), 乘

2019-01-29  本文已影响0人  默写年华Antifragile

1. numpy.dot()

两个数组的点乘操作,即先对应位置相乘然后再相加

  • If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
  • If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.
  • If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred.
  • If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
  • If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b
>>> import numpy as np
>>> np.dot([1,2,3],[4,5,6])
32

>>> np.dot([1,2,3],2)
array([2, 4, 6])

>>> np.dot([[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]) # 注意维度
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)

>>> np.dot([[1,2,3],[4,5,6]],[[1,2,3],[4,5,6],[7,8,9]])
array([[30, 36, 42],
       [66, 81, 96]])
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> np.dot(a,b)
32

>>> np.dot(np.mat(a), np.mat(b))
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.dot(np.mat([[1,2,3],[4,5,6]]),np.mat([[1,2,3],[4,5,6],[7,8,9]]))
matrix([[30, 36, 42],
        [66, 81, 96]])

--------------------------------------------------------------------------------------------------------------------

2. 乘号 *

对数组执行对应位置相乘操作
对矩阵执行矩阵乘法操作

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

>>> b = np.arange(0,6).reshape(2,3)
>>> b
array([[0, 1, 2],
       [3, 4, 5]])

>>> a*b
array([[ 0,  2,  6],
       [12, 20, 30]])

>>> (np.mat(a))*(np.mat(b.T)) #注意 a 的行数与 b 的列数相同
matrix([[ 8, 26],
        [17, 62]])

----------------------------------------------------------------------------------------------------------------------

3. np.multiply()

Multiply arguments element-wise.
数组和矩阵对应位置相乘,输出与相乘数组/矩阵的大小一致

>>> np.multiply(a,a)
array([[ 1,  4,  9],
       [16, 25, 36]])
>>> np.multiply(np.mat(a),np.mat(a))
matrix([[ 1,  4,  9],
        [16, 25, 36]])
上一篇 下一篇

猜你喜欢

热点阅读