【问题标题】:dot product of 2-D array and 1-D array is different from matrix and 1-D array二维数组和一维数组的点积不同于矩阵和一维数组
【发布时间】:2019-10-11 14:01:59
【问题描述】:

我使用 numpy dot 函数来计算 2D 和 1D 数组的乘积。我注意到,当二维数组的类型为 matrix 而一维数组的类型为 ndarray 时,dot 函数返回的结果与我传递一个类型为 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

【问题讨论】:

    标签: python arrays python-3.x numpy matrix


    【解决方案1】:

    首先,对于矩阵类:

    注意:
    不再推荐使用这个类,即使是线性的 代数。而是使用常规数组。该类可能会在 未来。

    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 %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-dims 时我们开始谈论矩阵

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 2021-11-17
      相关资源
      最近更新 更多