我使用了numpy dot函数来计算2D和1D数组的乘积。我注意到,当2D数组的类型为matrix时,而1D数组的类型为ndarray时,dot
函数返回的结果与将2D数组传递给我的结果不同类型ndarray
的数组。
问题:为什么结果不同?
简短示例
import numpy as np
a=[[1,2],
[3,4],
[5,6]]
e=np.array([1,2])
b=np.array(a)
print("Ndarrray:%s"%(type(b)))
print(b)
print("Dim of ndarray %d"%(np.ndim(b)))
be=np.dot(b,e)
print(be)
print("Dim of array*array %d\n"%(np.ndim(be)))
c=np.mat(a)
print("Matrix:%s"%(type(c)))
print(c)
print("Dim of matrix %d"%(np.ndim(c)))
ce=np.dot(c,e)
print(ce)
print("Dim of matrix*array %d"%(np.ndim(ce)))
Ndarrray:<class 'numpy.ndarray'>
[[1 2]
[3 4]
[5 6]]
Dim of ndarray 2
[ 5 11 17]
Dim of array*array 1
Matrix:<class 'numpy.matrix'>
[[1 2]
[3 4]
[5 6]]
Dim of matrix 2
[[ 5 11 17]]
Dim of matrix*array 2
答案 0 :(得分:4)
首先,对于矩阵类:
注意:
不再建议使用此类,即使对于线性 代数而是使用常规数组。该类可以在 未来。
这是因为点积中的第一个元素是矩阵类型,因此您会收到一个矩阵作为输出。但是,如果使用shape method
来获得矩阵的“实际”大小,则会得到一致的结果:
import numpy as np
a=[[1,2],
[3,4],
[5,6]]
e=np.array([1,2])
b=np.array(a)
print("Ndarrray:%s"%(type(b)))
print(b)
print("Dim of ndarray %d"%(np.ndim(b)))
be=np.dot(b,e)
print(be)
print("Dim of array*array %d\n"%(np.ndim(be)))
c=np.mat(a)
print("Matrix:%s"%(type(c)))
print(c)
print("Dim of matrix %d"%(np.ndim(c)))
ce=np.dot(c,e)
print(ce)
print("Dim of matrix*array %d"%(np.ndim(ce)))
print("Dim of matrix*array ",(ce.shape)) # -> ('Dim of matrix*array ', (1, 3))
print(type(ce)) # <class 'numpy.matrixlib.defmatrix.matrix'>
您有一个形状为(1,3)
的矩阵,它实际上是一个向量(第1维,因为您有1行3列)
基本上,要获取矩阵实例的尺寸,应使用shape
,而不是ndim
更清楚地说,如果定义一个空矩阵,则默认情况下始终为2暗:
c=np.mat([])
print(c.ndim) # 2
可能是这样设计的,因为当我们至少有2维的时候我们开始谈论矩阵