【发布时间】:2020-12-24 08:19:29
【问题描述】:
问题
请详细说明 2012 年 Numpy array broadcasting rules 中的答案,并澄清 尾轴 是什么,因为我不确定答案指的是哪个“链接文档页面” .也许在过去的 8 年里发生了变化。
由于trailing axes 中的axes 是复数,因此至少最后两个轴大小必须匹配(单数除外)?如果是,为什么至少有两个?
给出的答案是:
嗯,尾轴的含义在链接中解释过 文档页面。如果你有两个不同维度的数组 数,比如说一个 1x2x3 和另一个 2x3,那么你只比较 尾随常见尺寸,在本例中为 2x3。但是如果你的两个数组 是二维的,那么它们对应的尺寸必须是 等于或其中之一必须为 1。
在您的情况下,您有 2x2 and 4x2 and 4 != 2 而不是 4 或 2 等于 1,所以这不起作用。
错误和提出的问题是:
A = np.array([[1,2],[3,4]])
B = np.array([[2,3],[4,6],[6,9],[8,12]])
print("A.shape {}".format(A.shape))
print("B.shape {}".format(B.shape))
A*B
---
A.shape (2, 2) # <---- The last axis size is 2 in both shapes.
B.shape (4, 2) # <---- Apparently this "2" is not the size of trailing axis/axes
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-91-7a3f7e97944d> in <module>
3 print("A.shape {}".format(A.shape))
4 print("B.shape {}".format(B.shape))
----> 5 A*B
ValueError: operands could not be broadcast together with shapes (2,2) (4,2)
Since both A and B have two columns, I would have thought this would work.
So, I'm probably misunderstanding something here about the term "trailing axis",
and how it applies to N-dimensional arrays.
参考文献
广播规则
为了广播,操作中两个数组的尾轴的大小必须相同或其中之一必须是一个。
更新
根据@Akshay Sehgal 的回复了解。考虑 2 个数组 A.shape = (4,5,1) 和 B.shape = (1,2)。
A = np.arange(20).reshape((4, 5, 1))
B = np.arange(2).reshape((1,2))
print("A.shape {}".format(A.shape))
print("B.shape {}".format(B.shape))
---
A.shape (4, 5, 1)
B.shape (1, 2)
首先看axis=-1,A中的形状01是从01到02广播的,因为它是奇异的,来匹配B的。那么B中的形状01对于axis=-2是从01广播的(单数) 到 05 以匹配 A。结果是形状 (4, 5, 2)。
print("A * B shape is {}".format((A*B).shape))
---
A * B shape is (4, 5, 2)
基于@hpaulj 的回答,一种模拟广播的方法。
print("A.shape {}".format(A.shape))
print("B.shape {}".format(B.shape))
---
A.shape (4, 5, 1)
B.shape (1, 2)
# Check ranks.
print("rank(A) {} rank(B) {}".format(A.ndim, B.ndim))
---
rank(A) 3 rank(B) 2
# Expand B because rank(B) < rank(A).
B = B[
None,
::
]
B.shape
---
(1, 1, 2)
A:(4,5,1)
↑ ↑ ↓
B:(1,1,2)
----------
C:(4,5,2)
【问题讨论】:
-
添加了一个前导暗淡来制作 (1,1,2)。然后所有的 1 都被缩放了
标签: python numpy array-broadcasting