首页 > 解决方案 > numpy.matmul 给出的答案与@不同

问题描述

我正在转换一些 pre python-3.5 代码,并决定使用@而不是numpy.matmul为了可读性。但是,我注意到他们并不总是给出相同的答案。这是一个例子:

A = np.array([[-5.30378554e-01, 5.48418433e-01, -6.46479552e-01],
              [-7.72981719e-01, 3.13526179e-04, 6.34428218e-01],
              [3.48134817e-01, 8.36203996e-01, 4.23751136e-01]])
B = np.array([[0.84927215, 0., 0.],
              [0., 0.52771296, 0.],
              [0., 0., 0., ]])
C = np.array([[0.59677163, -0.05442458, 0.80056329],
              [0.38445308, 0.89512016, -0.22573375],
              [0.70431488, -0.44249052, -0.55510602]])
foo = A @ B @ C
bar = np.matmul(A, np.matmul(B, C))
print(foo)
print(bar)
print(np.array_equal(foo, bar))
print(foo - bar)

这段代码的输出是:

[[-0.15754366  0.28356928 -0.42593136]
 [-0.39170017  0.0358763  -0.52558461]
 [ 0.34609202  0.37890353  0.13708469]]
[[-0.15754366  0.28356928 -0.42593136]
 [-0.39170017  0.0358763  -0.52558461]
 [ 0.34609202  0.37890353  0.13708469]]
False
[[ 0.00000000e+00  0.00000000e+00  0.00000000e+00]
 [ 0.00000000e+00  6.93889390e-18 -1.11022302e-16]
 [ 0.00000000e+00  0.00000000e+00  0.00000000e+00]]

您可以看到计算之间存在细微差别。我曾期望 using@可以完全替代numpy.matmul,但鉴于上述情况,它们之间肯定存在一些差异。

标签: python-3.xnumpy

解决方案


根据PEP 465@是左结合的。因此A @ B @ C等价于np.matmul(np.matmul(A, B), C)而不是np.matmul(A, np.matmul(B, C))


推荐阅读