簡體   English   中英

如何計算2d中數組元素之間差異的所有組合?

[英]How to calculate all combinations of difference between array elements in 2d?

給定一個數組arr = [10, 11, 12]我想計算一個元素可以從另一個元素中減去的所有方法。 對於1xN陣列,所需輸出是NxN陣列,其中output[i, j] = arr[i] - arr[j] 我的方法是生成兩個數字的所有可能的配對,減去和重塑。 如下

opts = np.array(list(product(arr, arr)))
[[10 10] 
 [10 11]
 [10 12]
 [11 10]
 [11 11]
 [11 12]
 [12 10]
 [12 11]
 [12 12]]
 diffs = (opts[:, 0] - opts[:, 1]).reshape(len(arr), -1)
 [[ 0 -1 -2]
  [ 1  0 -1]
  [ 2  1  0]]

這很好用,我接下來要做的是將它推廣到2d輸入。 基本上我想要完成的是給出一個MxN數組來輸出一個MxNxN數組,並且對於每一層(深度方向),為每一行執行上述功能。

我試圖將MxN輸入數組重新MxNx1MxNx1 ,然后像以前一樣計算產品。 我的假設是,它會像以前一樣在元素方面表現,遺憾的是沒有。

我的第一個想法是初始化適當形狀的輸出並循環遍歷行並“手動”設置值,但我希望采用矢量化方法。 有沒有人知道如何在不繞過數千行的情況下在2維中完成此操作?

這是一種通用的矢量化方式,涵蓋了在將輸入數組重新映射為可廣播的shpaes之后利用broadcasting 1D和2D情況 -

def permute_axes_subtract(arr, axis):
    # Get array shape
    s = arr.shape

    # Get broadcastable shapes by introducing singleton dimensions
    s1 = np.insert(s,axis,1)
    s2 = np.insert(s,axis+1,1)

    # Perform subtraction after reshaping input array to 
    # broadcastable ones against each other
    return arr.reshape(s1) - arr.reshape(s2)

要執行任何其他的elementwise ufunc操作,只需用它取代了減法運算。

樣品運行 -

In [184]: arr = np.random.rand(3)

In [185]: permute_axes_subtract(arr, axis=0).shape
Out[185]: (3, 3)

In [186]: arr = np.random.rand(3,4)

In [187]: permute_axes_subtract(arr, axis=0).shape
Out[187]: (3, 3, 4)

In [188]: permute_axes_subtract(arr, axis=1).shape
Out[188]: (3, 4, 4)

@ ClimbingTheCurve上發布的解決方案func - permute_difference和在大型2D陣列上發布的解決方案 -

In [189]: arr = np.random.rand(100,100)

In [190]: %timeit permute_difference(arr, axis=0)
     ...: %timeit permute_axes_subtract(arr, axis=0)
1 loop, best of 3: 295 ms per loop
1000 loops, best of 3: 1.17 ms per loop

In [191]: %timeit permute_difference(arr, axis=1)
     ...: %timeit permute_axes_subtract(arr, axis=1)
1 loop, best of 3: 303 ms per loop
1000 loops, best of 3: 1.12 ms per loop

解決方案是為1d情況編寫函數,並且為了概括使用函數np.apply_along_axis() ,該函數接受函數,應用軸和輸入數組。 這完全符合預期。 我用過的代碼:

from itertools import product

import numpy as np


def permute_difference(arr, axis=1):
    """
    applies the _permute_difference to a 2d array
    along the specified axis

    Parameters
    ----------
    arr numpy.array

    Returns
    -------
    numpy.array
        a 3d array, each 2d array the i^th along the depth
        contains the permuted difference of the i^th row
        in the input array
    """
    def _permute_difference(arr):
        """
        calculates all the differences between all combinations
        terms in the input array. output[i,j] = arr[i] - arr[j]
        for every combination if ij.

        Parameters
        ----------
        arr numpy.array
            a 1d input array

        Returns
        -------
        numpy.array
            a 2d array

        Examples
        --------
        arr = [10, 11, 12]

        diffs = [[ 0 -1 -2]
                [ 1  0 -1]
                [ 2  1  0]]
        """
        opts = np.array(list(product(arr, arr)))
        d = (opts[:, 0] - opts[:, 1]).reshape(len(arr), -1)
        return d

    if arr.ndim == 1:
        diffs = _permute_difference(arr)
    else:
        diffs = np.apply_along_axis(permute_difference, axis, arr)
    return diffs

暫無
暫無

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

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