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



我使用 numpy dot 函数来计算 2D 和 1D 数组的乘积。我注意到,当 2D 数组是矩阵类型而 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 %dn"%(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

首先,对于矩阵类:

注意:
不再建议使用此类,即使对于线性 代数。而是使用常规数组。该类可能会在 前途。

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

这是因为点积中的第一个元素是矩阵类型,因此您会收到一个矩阵作为输出。但是,如果您使用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 %dn"%(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)的矩阵,它实际上是一个向量(dim 1,因为你有 1 行和 3 列(

基本上,要获取矩阵实例的维度,您应该使用shape,而不是ndim

为了更清楚起见,如果您定义一个空矩阵,则默认始终为 2 点:

c=np.mat([])
print(c.ndim) # 2

可能是以这种方式打算的,因为当我们至少有 2 点时,我们开始谈论矩阵

最新更新