从矩阵B的每一行中减去矩阵A的每一行而无循环 [英] Subtract each row of matrix A from every row of matrix B without loops

查看:197
本文介绍了从矩阵B的每一行中减去矩阵A的每一行而无循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出两个数组,A(形状:M X C)和B(形状:N X C),有没有一种方法可以在不使用循环的情况下从B的每一行减去A的每一行?最终输出将为(M N X C).

Given two arrays, A (shape: M X C) and B (shape: N X C), is there a way to subtract each row of A from each row of B without using loops? The final output would be of shape (M N X C).

A = np.array([[  1,   2,   3], 
              [100, 200, 300]])

B = np.array([[  10,   20,   30],
              [1000, 2000, 3000],
              [ -10,  -20,   -2]])

所需结果(可以具有其他形状)(已编辑):

Desired result (can have some other shape) (edited):

array([[  -9,   -18,   -27],
       [-999, -1998, -2997],
       [  11,    22,     5],
       [  90,   180,   270],
       [-900, -1800, -2700],
       [ 110,   220,   302]])

Shape: 6 X 3

(循环太慢,外部"减去每个元素而不是每一行)

推荐答案

可以通过利用

It's possible to do it efficiently (without using any loops) by leveraging broadcasting like:

In [28]: (A[:, np.newaxis] - B).reshape(-1, A.shape[1])
Out[28]: 
array([[   -9,   -18,   -27],
       [ -999, -1998, -2997],
       [   11,    22,     5],
       [   90,   180,   270],
       [ -900, -1800, -2700],
       [  110,   220,   302]])


或者,比 broadcasting ,我们将不得不使用 numexpr ,例如:


Or, for a little faster solution than broadcasting, we would have to use numexpr like:

In [31]: A_3D = A[:, np.newaxis]
In [32]: import numexpr as ne

# pass the expression for subtraction as a string to `evaluate` function
In [33]: ne.evaluate('A_3D - B').reshape(-1, A.shape[1])
Out[33]: 
array([[   -9,   -18,   -27],
       [ -999, -1998, -2997],
       [   11,    22,     5],
       [   90,   180,   270],
       [ -900, -1800, -2700],
       [  110,   220,   302]], dtype=int64)


另一种效率最低的方法是使用 np.tile 来匹配两个数组的形状.但是,请注意,这样做效率最低,因为在尝试匹配形状时会进行复制.


One more least efficient approach would be by using np.repeat and np.tile to match the shapes of both arrays. But, note that this is least efficient because it makes copies when trying to match the shapes.

In [27]: np.repeat(A, B.shape[0], 0) - np.tile(B, (A.shape[0], 1))
Out[27]: 
array([[   -9,   -18,   -27],
       [ -999, -1998, -2997],
       [   11,    22,     5],
       [   90,   180,   270],
       [ -900, -1800, -2700],
       [  110,   220,   302]])

这篇关于从矩阵B的每一行中减去矩阵A的每一行而无循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆