【问题标题】:"ValueError: shapes (1,4) and (1,4) not aligned: 4 (dim 1) != 1 (dim 0)" but array sizes are the same“ValueError:形状(1,4)和(1,4)未对齐:4(dim 1)!= 1(dim 0)”但数组大小相同
【发布时间】:2020-10-07 15:56:08
【问题描述】:
import numpy as np

arr = np.array([[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]])

def np2dOperations(arr):
    a = arr[0:1]
    print(a)
    b = arr[1:2]
    print(b)
    c = arr[2:3]
    print(c)
    d = arr[3:4]
    print(d)
    e = np.matmul(a,c)
    print(e, "e")
    f = b*d
    x = e.sum()
    y = np.amax(f)
    print(x)
    print(y)
    print(x-y)
    return x-y

np2dOperations(arr)

我的输出:

[[1 1 2 2]]
[[1 1 2 2]]
[[3 3 4 4]]
[[3 3 4 4]]
Traceback (most recent call last):
  File "/Users/bethanne/Documents/NumPy2DOperations.py", line 24, in <module>
    np2dOperations(arr)
  File "/Users/bethanne/Documents/NumPy2DOperations.py", line 14, in np2dOperations
    e = np.matmul(a,c)
ValueError: shapes (1,4) and (1,4) not aligned: 4 (dim 1) != 1 (dim 0)

即使数组 a 和 c 的大小相同,我仍不断收到以下错误“ValueError:形状 (1,4) 和 (1,4) 未对齐:4 (dim 1) != 1 (dim 0)” .结果应该是 x-y 的 16。我尝试在数组 a 上使用 np.transpose ,但这也不起作用。我是使用 numpy 和 python 编程的新手,所以请解释我做错了什么。谢谢!

【问题讨论】:

  • 如果你想执行矩阵乘法,那么你应该做np.matmul(a, c.T)np.matmul(a.T,c)。如果你想要一个元素产品,那么你可以做 a*cnp.dot(a,c)

标签: python arrays numpy


【解决方案1】:

所以你从一个 4x4 数组开始:

In [17]: arr = np.array([[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]])
In [18]: arr
Out[18]: 
array([[1, 1, 2, 2],
       [1, 1, 2, 2],
       [3, 3, 4, 4],
       [3, 3, 4, 4]])
In [19]: arr.shape
Out[19]: (4, 4)

使用切片索引会保留二维形状:

In [20]: a = arr[0:1]
In [21]: a
Out[21]: array([[1, 1, 2, 2]])
In [22]: a.shape
Out[22]: (1, 4)

标量索引将维度减少 1

In [23]: a1 = arr[0]
In [24]: a1
Out[24]: array([1, 1, 2, 2])
In [25]: a1.shape
Out[25]: (4,)

一维数组的matmul 已明确记录:

In [26]: np.matmul(arr[0],arr[1])
Out[26]: 10
In [27]: 
In [27]: np.matmul(arr[0],arr[2])
Out[27]: 22

matmul for 2d arrays 也有明确记录,并且错误中明确说明了要求:

In [28]: np.matmul(arr[0:1],arr[2:3])
Traceback (most recent call last):
  File "<ipython-input-28-88ee2e80387e>", line 1, in <module>
    np.matmul(arr[0:1],arr[2:3])
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 4)

matmul of a (1,4) with a (4,1) 确实有效,产生与一维“点”相同的结果 - 除了结果是 (1,1) 数组:

In [29]: np.matmul(arr[0:1],arr[2:3].T)
Out[29]: array([[22]])

元素乘法:

In [30]: arr[1]*arr[3]
Out[30]: array([3, 3, 8, 8])
In [31]: arr[1:2]*arr[3:4]
Out[31]: array([[3, 3, 8, 8]])

等等其他表达式。在numpy 中,一维数组和二维数组之间有明显的区别。 (n,) 形状的数组不同于 (1,n) 或 (n,1) 形状,即使它们可以相互重新调整形状。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2017-02-11
    • 1970-01-01
    • 2019-03-21
    • 2019-05-28
    • 2021-04-25
    • 2021-05-09
    相关资源
    最近更新 更多