numpy array和mat的乘法

总结:pytorch和numpy中,星号*都表示矩阵点对点相乘;matmul都表示矩阵乘法。

=======================================================================================

1.mat()函数中矩阵的乘积可以使用(星号) *  或 .dot()函数,其结果相同。而矩阵对应位置元素相乘需调用numpy.multiply()函数。

a = np.mat([1, 2, 3])
b = np.mat([1, 2, 3])
c = np.mat([[1],
            [2],
            [3]])

ele_multiply = np.multiply(a, b)
mat_multiply = a*c
dot_multiply = a.dot(c)

结果如下:

2.array()函数中矩阵的乘积可以使用np.matmul或者.dot()函数。而星号乘 (*)则表示矩阵对应位置元素相乘,与numpy.multiply()函数结果相同。

import numpy as np

# np.dot示例----------------------------------------------------
a = np.array([[1, 2, 3],
              [4, 5, 6]])
b = np.array([0, 1, 2])
print(np.dot(a, b.T))   # array([ 8, 17]).  shape (2,)

c = np.array([[0, 1, 2],
              [0, 1, 2]])
print(np.dot(a, c.T))   # array([[ 8,  8],
                        #        [17, 17]])    shape(2, 2)

# *示例----------------------------------------------------
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[0, 0, 0], [1, 1, 1]])
print(a*b)   # array([[0, 0, 0],
             #        [4, 5, 6]])    shape(2, 3)

c = np.array([2])
print(a*c)  # array([[ 2,  4,  6],
            #        [ 8, 10, 12]])   shape(2, 3)

d = 2
print(a*d)  # array([[ 2,  4,  6],
            #        [ 8, 10, 12]])   shape(2, 3)

 

posted @ 2019-11-12 11:19  Picassooo  阅读(815)  评论(0)    收藏  举报