关于python中的矩阵乘法(array和mat类型)

一、关于python中的矩阵乘法,我们一般有两种数据格式可以实现:np.array()类型和np.mat()类型;

对于这两种数据类型均有三种操作方式:

(1)乘号 *

(2)np.dot()

(3)np.multiply()

而这三种操作方式在操作这两种数据格式时又有点区别,下面一一列出来:

import numpy as np 

#np.array() type
#1. np.dot()
a = np.array([[1 , 2] , [3 , 4]] , dtype = np.float)
b = np.array([[1 , 2] , [3 , 4]] , dtype = np.float)
c = np.dot(a , b)
print(c)
#output:[[  7.  10.],[ 15.  22.]]

#2. *
d = a * b
print(d)
#output:[[  1.   4.],[  9.  16.]]

#3. np.multiply()
e = np.multiply(a , b)
print(e)
#output:[[  1.   4.],[  9.  16.]]

#np.mat() type
#4. *
A = np.mat([[1 , 2] , [3 , 4]] , dtype = np.float)
B = np.mat([[1 , 2] , [3 , 4]] , dtype = np.float)
C = A * B
print(C)
#output:[[  7.  10.],[ 15.  22.]]

#5. np.dot()
D = np.dot(A , B)
print(D)
#output:[[  7.  10.],[ 15.  22.]]

#6. np.multiply()
E = np.multiply(A , B)
print(E)
#output:[[  1.   4.],[  9.  16.]]

# np.mat() * np.array()
F = A * a;
print(F)
#output:[[  7.  10.],[ 15.  22.]]

由上面的代码可以总结如下:

(1)np.dot()对于这两种数据格式均为矩阵乘法;

(2)np.multiply()对于这两种数据格式均为按元素相乘;

(3)符号“*”对于array类型是矩阵乘法,对于mat类型是按元素类型相乘,而当一个array类型乘上一个mat类型时,则为矩阵乘法;

二、pytorch中的乘法:

(1)矩阵相乘:torch.mm();

(2)对应元素点乘:torch.mul();

原文地址:https://www.cnblogs.com/zf-blog/p/10018452.html