简体   繁体   中英

Recursive function to apply any function to N arrays of any length to form one jagged multidimensional array of N dimensions

Given N input arrays, all of any length, I would like to be able to apply a function to all combinations of every combination of each arrays.

For example:

Given input arrays:

[1, 2] [3, 4, 5] [6, 7, 8, 9]

And a function which returns the product of N elements

I would like to be able to apply a function to every combination of these elements. In this case it results in a 3 dimensional array, of lengths 2, 3, and 4 respectively.

The resulting array would look like this:

[
    [
        [18, 21, 24, 27], 
        [24, 28, 32, 36], 
        [30, 35, 40, 45]
    ], 
    [
        [36, 42, 48, 54], 
        [48, 56, 64, 72], 
        [60, 70, 80, 90]
    ]
]

You can do this with broadcasting:

import numpy as np


a = np.array([1, 2, 3])
b = np.array([4, 5])

c = a[None, ...] * b[..., None]
print(c)

Output:

[[ 4  8 12]
 [ 5 10 15]]

This can be easily generalized by crafting the appropriate slicing to be passed to the operands.


EDIT

An implementation of such generalization could be:

import numpy as np


def apply_multi_broadcast_1d(func, dim1_arrs):
    n = len(dim1_arrs)
    iter_dim1_arrs = iter(dim1_arrs)
    slicing = tuple(
        slice(None) if j == 0 else None
        for j in range(n))
    result = next(iter_dim1_arrs)[slicing]
    for i, dim1_arr in enumerate(iter_dim1_arrs, 1):
        slicing = tuple(
            slice(None) if j == i else None
            for j in range(n))
        result = func(result, dim1_arr[slicing])
    return result


dim1_arrs = [np.arange(1, n + 1) for n in range(2, 5)]
print(dim1_arrs)
# [array([1, 2]), array([1, 2, 3]), array([1, 2, 3, 4])]
arr = apply_multi_broadcast_1d(lambda x, y: x * y, dim1_arrs)
print(arr.shape)
# (2, 3, 4)
print(arr)
# [[[ 1  2  3  4]
#   [ 2  4  6  8]
#   [ 3  6  9 12]]

#  [[ 2  4  6  8]
#   [ 4  8 12 16]
#   [ 6 12 18 24]]]

There is no need for recursion here, and I am not sure how it could be beneficial.


Another approach is to generate a np.ufunc from a Python function (as proposed in @TlsChris's answer ) and use its np.ufunc.outer() method:

import numpy as np


def apply_multi_outer(func, dim1_arrs):
    ufunc = np.frompyfunc(func, 2, 1)
    iter_dim1_arrs = iter(dim1_arrs)
    result = next(iter_dim1_arrs)
    for dim1_arr in iter_dim1_arrs:
        result = ufunc.outer(result, dim1_arr)
    return result

While this would give identical results (for 1D arrays), this is slower (from slightly to considerably depending on the input sizes) than the broadcasting approach.

Also, while apply_multi_broadcast_1d() is limited to 1-dim inputs, apply_multi_outer() would work for input arrays of higher dimensionality too. The broadcasting approach can be easily adapted to higher dimensionality inputs, as shown below.


EDIT 2

A generalization of apply_multi_broadcast_1d() to N-dim inputs, including a separation of the broadcasting from the function application, follows:

import numpy as np


def multi_broadcast(arrs):
    for i, arr in enumerate(arrs):
        yield arr[tuple(
            slice(None) if j == i else None
            for j, arr in enumerate(arrs) for d in arr.shape)]


def apply_multi_broadcast(func, arrs):
    gen_arrs = multi_broadcast(arrs)
    result = next(gen_arrs)
    for i, arr in enumerate(gen_arrs, 1):
        result = func(result, arr)
    return result

The benchmarks for the three show that apply_multi_broadcast() is marginally slower than apply_multi_broadcast_1d() but faster than apply_multi_outer() :

def f(x, y):
    return x * y


dim1_arrs = [np.arange(1, n + 1) for n in range(2, 5)]
print(np.all(apply_multi_outer(f, dim1_arrs) == apply_multi_broadcast_1d(f, dim1_arrs)))
print(np.all(apply_multi_outer(f, dim1_arrs) == apply_multi_broadcast(f, dim1_arrs)))
# True
# True
%timeit apply_multi_broadcast_1d(f, dim1_arrs)
# 100000 loops, best of 3: 7.76 µs per loop
%timeit apply_multi_outer(f, dim1_arrs)
# 100000 loops, best of 3: 9.46 µs per loop
%timeit apply_multi_broadcast(f, dim1_arrs)
# 100000 loops, best of 3: 8.63 µs per loop

dim1_arrs = [np.arange(1, n + 1) for n in range(10, 16)]
print(np.all(apply_multi_outer(f, dim1_arrs) == apply_multi_broadcast_1d(f, dim1_arrs)))
print(np.all(apply_multi_outer(f, dim1_arrs) == apply_multi_broadcast(f, dim1_arrs)))
# True
# True
%timeit apply_multi_broadcast_1d(f, dim1_arrs)
# 100 loops, best of 3: 10 ms per loop
%timeit apply_multi_outer(f, dim1_arrs)
# 1 loop, best of 3: 538 ms per loop
%timeit apply_multi_broadcast(f, dim1_arrs)
# 100 loops, best of 3: 10.1 ms per loop

Let we are given N arrays that has size of n1, n2, ..., nN. Then, we can part this problem as (N-1) computations of two arrays. In first computation, compute product of n1, n2. Let the output is result1. In second computation, compute product of result1, n3. Let the output is result2. . . In last computation, compute product of result(N-2), nN. Let the output is result(N-1).

You would know that the size of result1 is n2 _ n1, the size of result2 is n3 _ n2 _ n1. . . As you could infer, the size of result(N-1) is n(N) _ n(N-1) _ ... _ n2 * n1.

Now let we are given two arrays: result(k-1), and arr(k). Then we should get product of each elements from result(k-1) and arr(k). Cause result(k-1) has size of n(k-1) _ n(k-2) _ ... _ n1, arr(k) has size of n(k), The output array (result(k)) should have size of n(k) _ n(k-1) _ ... _ n1. It means the solution of this problem is dot product of transposed n(k) and result(k-1). So, the function should be like below.

productOfTwoArrays = lambda arr1, arr2: np.dot(arr2.T, arr1)

So now we solve the first problem. What left is just applying this to all N arrays. So the solution might be iterative. Let the input array has N arrays.

def productOfNArrays(Narray: list) -> list:
  result = Narray[0]
  N = len(Narray)

  for idx in range(1, N):
    result = productOfTwoArrays(result, Narray[idx])

  return result

The whole code might be below.

def productOfNArrays(Narray: list) -> list:
  import numpy as np

  productOfTwoArrays = lambda arr1, arr2: np.dot(arr2.T, arr1)

  result = Narray[0]
  N = len(Narray)

  for idx in range(1, N):
    result = productOfTwoArrays(result, Narray[idx])

  return result

An alternative approach using np.frompyfunc to create a ufunc of the required function. This is the applied with the ufuncs .outer method n-1 times for the n arguments.

import numpy as np

def testfunc( a, b):
    return a*(a+b) + b*b

def apply_func( func, *args, dtype = np.float ):
    """ Apply func sequentially to the args
    """
    u_func = np.frompyfunc( func, 2, 1) # Create a ufunc from func
    result = np.array(args[0])
    for vec in args[1:]:
        result = u_func.outer( result, vec )  # apply the outer method of the ufunc
        # This returns arrays of object type. 
    return np.array(result, dtype = dtype) # Convert to type and return the result

apply_func(lambda x,y: x*y, [1,2], [3,4,5],[6,7,8,9] )

# array([[[18., 21., 24., 27.],
#         [24., 28., 32., 36.],
#         [30., 35., 40., 45.]],

#        [[36., 42., 48., 54.],
#         [48., 56., 64., 72.],
#         [60., 70., 80., 90.]]])

apply_func( testfunc, [1,2], [3,4,5],[6,7,8,9])

# array([[[ 283.,  309.,  337.,  367.],
#         [ 603.,  637.,  673.,  711.],
#         [1183., 1227., 1273., 1321.]],

#        [[ 511.,  543.,  577.,  613.],
#         [ 988., 1029., 1072., 1117.],
#         [1791., 1843., 1897., 1953.]]])

In my experience, in most cases we are not looking for a truly general solution . Of course, such a general solution seems elegant and desirable, as it will be inherently able to adapt, should our requirements change -- as they do quite often when writing reasearch code.

However, instead we are usually actually looking for a solution that is easy to understand and easy to modify , should our requirements change.

One such solution is to use np.einsum() :

import numpy as np

a = np.array([1, 2])
b = np.array([3, 4, 5])
c = np.array([6, 7, 8, 9])

np.einsum('a,b,c->abc', a, b, c)
# array([[[18, 21, 24, 27],
#         [24, 28, 32, 36],
#         [30, 35, 40, 45]],
#
#        [[36, 42, 48, 54],
#         [48, 56, 64, 72],
#         [60, 70, 80, 90]]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM