gpt4 book ai didi

python - numpy 数组乘法问题

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:05 24 4
gpt4 key购买 nike

假设我有三个数组(即 numpy.array 类型):

>>> w.shape
(113,)
>>> X.shape
(113,1)
>>> Y.shape
(113,)

numpy 帮助页面建议在数组上每个乘法都是按元素计算的。由于以上三个向量在第一维的大小都是 113,我认为乘法在所有情况下都会给出 113 长度的向量,但事实并非如此:

>>> (w * Y).shape     # expected
(113,)
>>> (w * X).shape # ?!?!?!?!
(113,113)

第二个轴上的113是哪里来的?对我来说看起来不太符合元素。

最佳答案

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when they are equal, or one of them is 1.

两个轴中较小的一个被拉伸(stretch)或“复制”以匹配另一个。

Numpy 的 broadcasting 此处应用规则。

w      (1d array):       113
X (2d array): 113 x 1
Result (2d array): 113 x 113

关于python - numpy 数组乘法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13288294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com