二维数组和一维数组的点积与矩阵和一维数组的点积不同

3
我使用了numpy的dot函数来计算2D和1D数组的乘积。我注意到当2D数组是matrix类型而1D数组是ndarray类型时,dot函数返回的结果与我传递一个类型为ndarray的2D数组时不同。 问题:为什么结果不同? 简短示例
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

1个回答

4

首先,对于矩阵类:

注意:
不建议再使用此类,即使是用于线性代数。相反,应该使用普通数组。此类可能在将来被删除。

https://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html

这是因为点积中的第一个元素是矩阵类型,因此您将获得一个矩阵作为输出。但是,如果您使用 shape 方法 来获取矩阵的“实际”大小,则可以得到一致的结果:

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

也许这是有意为之的,因为当我们至少有两个维度时才开始谈论矩阵。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接