【问题标题】:How to perform outer subtraction along an axis in numpy如何在numpy中沿轴执行外减法
【发布时间】:2021-11-11 11:23:36
【问题描述】:

我曾经对两个一维数组执行外减法如下,以接收包含所有减法对的单个二维数组:

import numpy as np

a = np.arange(5)
b = np.arange(3)
result = np.subtract.outer(a, b)
assert result.shape == (5, 3)
assert np.all(result == np.array([[aa - bb for bb in b] for aa in a ])) # no rounding errors

现在状态空间切换到二维,我想执行相同的操作,但只对数组 A 和 B 的最后一个轴上的两个值执行每个减法:

import numpy as np

A = np.arange(5 * 2).reshape(-1, 2)
B = np.arange(3 * 2).reshape(-1, 2)
result = np.subtract.outer(A, B)

# Obviously the following does not hold, because here we have got all subtractions, therefore the shape (5, 2, 3, 2)
# I would like to exchange np.subtract.outer such that the following holds:
# assert result.shape == (5, 3, 2)

expected_result = np.array([[aa - bb for bb in B] for aa in A ])
assert expected_result.shape == (5, 3, 2)

# That's what I want to hold:
# assert np.all(result == expected_result) # no rounding errors

是否有“仅限 numpy”的解决方案来执行此操作?

【问题讨论】:

    标签: python python-3.x numpy


    【解决方案1】:

    您可以将 A 扩展/重塑为 (5, 1, 2) 并将 B 扩展/重塑为 (1, 3, 2),然后让广播完成这项工作:

    A[:, None, :] - B[None, :, :]
    

    【讨论】:

      【解决方案2】:

      A[:, None] - B[None, :] 做到了。

      A = np.arange(5 * 2).reshape(-1, 2)
      B = np.arange(3 * 2).reshape(-1, 2)
      
      expected_result = np.array([[aa - bb for bb in B] for aa in A ])
      
      C = A[:, None] - B[None, :]
      
      np.allclose(expected_result, C)
      #> True
      

      完全相同的语法也适用于您的第一个示例。这是因为根据您的要求,您将A 的每个第一个轴元素与B 的每个第一个轴元素组合在一起。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-13
        • 2021-06-04
        • 1970-01-01
        • 1970-01-01
        • 2017-06-03
        • 1970-01-01
        相关资源
        最近更新 更多