簡體   English   中英

numpy數組-有效地從A減去B的每一行

[英]numpy array - efficiently subtract each row of B from A

我有兩個numpy數組a和b。 我想從a中減去b的每一行。 我嘗試使用:

a1 - b1[:, None]

這適用於小型陣列,但是在實際數據大小上花費的時間太長。

a = np.arange(16).reshape(8,2)

a
Out[35]: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15]])

b = np.arange(6).reshape(3,2)

b
Out[37]: 
array([[0, 1],
       [2, 3],
       [4, 5]])

a - b[:, None]
Out[38]: 
array([[[ 0,  0],
        [ 2,  2],
        [ 4,  4],
        [ 6,  6],
        [ 8,  8],
        [10, 10],
        [12, 12],
        [14, 14]],

       [[-2, -2],
        [ 0,  0],
        [ 2,  2],
        [ 4,  4],
        [ 6,  6],
        [ 8,  8],
        [10, 10],
        [12, 12]],

       [[-4, -4],
        [-2, -2],
        [ 0,  0],
        [ 2,  2],
        [ 4,  4],
        [ 6,  6],
        [ 8,  8],
        [10, 10]]])

%%timeit
a - b[:, None]
The slowest run took 10.36 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.18 µs per loop

對於較大的陣列,這種方法太慢/效率低下。

a1 = np.arange(18900 * 41).reshape(18900, 41)

b1 = np.arange(2674 * 41).reshape(2674, 41)

%%timeit
a1 - b1[:, None]
1 loop, best of 3: 12.1 s per loop

%%timeit
for index in range(len(b1)):
    a1 - b1[index]
1 loop, best of 3: 2.35 s per loop

有什么小技巧可以加快速度嗎?

您正在使用內存限制。

如果像您的示例中一樣,8位足以存儲數據,請使用uint8:

import numpy as np
a1 = np.arange(18900 * 41,dtype=np.uint8).reshape(18900, 41)
b1 = np.arange(2674 * 41,dtype=np.uint8).reshape(2674, 41)
%time c1=(a1-b1[:,None])
#1.02 s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM