Numpy dot产品问题

2024-09-25 08:32:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

B=np.ones(2)

A的形状显然是2X2

numpy如何允许我计算点积美国运输部(A,B)

^{pr2}$

对于点积,B的尺寸必须是2X1,或者更确切地说是这个

[1,2]  (dot)  [1]
[3,4]         [1]

这是一个非常愚蠢的问题,但我不知道我错在哪里?在

以前我常这么想np.ones公司(2) 会给我这个:

[1]
[1]

但它给我的是:

[1,1]

Tags: numpy尺寸npones公司arraydot形状
3条回答

我复制了我今天早些时候写的answer的一部分:

You should resist the urge to think of numpy arrays as having rows and columns, but instead consider them as having dimensions and shape. This is an important point which differentiates np.array and np.matrix:

x = np.array([1, 2, 3])
print(x.ndim, x.shape)  # 1 (3,)

y = np.matrix([1, 2, 3])
print(y.ndim, y.shape)  # 2 (1, 3)

An n-D array can only use n integer(s) to represent its shape. Therefore, a 1-D array only uses 1 integer to specify its shape.

In practice, combining calculations between 1-D and 2-D arrays is not a problem for numpy, and syntactically clean since @ matrix operation was introduced in Python 3.5. Therefore, there is rarely a need to resort to np.matrix in order to satisfy the urge to see expected row and column counts.

与点积有关的向量和矩阵形状的大多数规则的存在主要是为了有一个连贯的方法,可以扩展到更高的张量阶。但在处理一阶(向量)和二阶(矩阵)张量时,它们并不十分重要。而这些订单正是绝大多数numpy用户所需要的。在

因此,@和{}会针对这些顺序进行优化(数学上和输入解析),始终在第一个轴的最后一个轴上求和,以及第二个轴的第二个到最后一个轴(如果适用)。“如果适用”是一种白痴证明,以确保输出是在绝大多数情况下,即使形状不符合技术要求。在

同时,我们这些使用高阶张量的人,则被归为np.tensordot或{},它们都有关于维数匹配的所有琐碎的小规则。在

这种行为是故意的。The NumPy docs状态:

If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.

相关问题 更多 >