Applying a function to an array using Numpy when the function contains a condition

时间:2018-12-03 13:21:31

标签: python numpy lambda conditional vectorization

I am having a difficulty with applying a function to an array when the function contains a condition. I have an inefficient workaround and am looking for an efficient (fast) approach. In a simple example:

pts = np.linspace(0,1,11)
def fun(x, y):
    if x > y:
        return 0
    else:
        return 1

Now, if I run:

result = fun(pts, pts)

then I get the error

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

raised at the if x > y line. My inefficient workaround, which gives the correct result but is too slow is:

result = np.full([len(pts)]*2, np.nan)
for i in range(len(pts)):
    for j in range(len(pts)):
        result[i,j] = fun(pts[i], pts[j])

What is the best way to obtain this in a nicer (and more importantly, faster) way?

I am having a difficulty with applying a function to an array when the function contains a condition. I have an inefficient workaround and am looking for an efficient (fast) approach. In a simple example:

pts = np.linspace(0,1,11)
def fun(x, y):
    if x > y:
        return 0
    else:
        return 1

Now, if I run:

result = fun(pts, pts)

then I get the error

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

raised at the if x > y line. My inefficient workaround, which gives the correct result but is too slow is:

result = np.full([len(pts)]*2, np.nan)
for i in range(len(pts)):
    for j in range(len(pts)):
        result[i,j] = fun(pts[i], pts[j])

What is the best way to obtain this in a nicer (and more importantly, faster) way?

EDIT: using

def fun(x, y):
    if x > y:
        return 0
    else:
        return 1
x = np.array(range(10))
y = np.array(range(10))
xv,yv = np.meshgrid(x,y)
result = fun(xv, yv)  

still raises the same ValueError.

3 个答案:

答案 0 :(得分:1)

错误非常明显-假设您有

x = np.array([1,2])
y = np.array([2,1])

这样

(x>y) == np.array([0,1])

您的if np.array([0,1])语句的结果应该是什么?是真的还是假的? numpy告诉您这是模棱两可的。使用

(x>y).all()

(x>y).any()

是明确的,因此numpy为您提供了解决方案-任何一个单元对都满足条件,或者全部满足-两者都是明确的真实值。您必须自己定义向量x大于向量y 的含义。

numpy解决方案可在xy的所有对上运行,使得x[i]>y[j]使用网格网格生成所有对:

>>> import numpy as np
>>> x=np.array(range(10))
>>> y=np.array(range(10))
>>> xv,yv=np.meshgrid(x,y)
>>> xv[xv>yv]
array([1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, 6, 7, 8, 9, 3, 4, 5, 6, 7, 8,
       9, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 6, 7, 8, 9, 7, 8, 9, 8, 9, 9])
>>> yv[xv>yv]
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
       2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 8])

xvyv发送到fun,或在函数中创建网格,具体取决于哪个更有意义。这将生成所有xi,yj对,例如xi>yj。如果想要实际的索引,只需返回xv>yv,其中每个单元格ij对应于x[i]y[j]。就您而言:

def fun(x, y):
    xv,yv=np.meshgrid(x,y)
    return xv>yv

将返回一个矩阵,其中fun(x,y)[i][j]x[i]>y[j]时为True,否则为False。或者

return  np.where(xv>yv)

将返回两个成对的索引数组的元组,这样

for i,j in fun(x,y):

也将保证x[i]>y[j]

答案 1 :(得分:1)

In [253]: x = np.random.randint(0,10,5)
In [254]: y = np.random.randint(0,10,5)
In [255]: x
Out[255]: array([3, 2, 2, 2, 5])
In [256]: y
Out[256]: array([2, 6, 7, 6, 5])
In [257]: x>y
Out[257]: array([ True, False, False, False, False])
In [258]: np.where(x>y,0,1)
Out[258]: array([0, 1, 1, 1, 1])

要对这两个1d数组进行笛卡尔比较,请重塑一个,以便可以使用broadcasting

In [259]: x[:,None]>y
Out[259]: 
array([[ True, False, False, False, False],
       [False, False, False, False, False],
       [False, False, False, False, False],
       [False, False, False, False, False],
       [ True, False, False, False, False]])
In [260]: np.where(x[:,None]>y,0,1)
Out[260]: 
array([[0, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [0, 1, 1, 1, 1]])

带有if的函数仅适用于标量输入。如果给定数组,则a>b会生成一个布尔数组,该布尔数组不能在if语句中使用。您的迭代有效,因为它传递了标量值。对于某些最好的复杂函数,您可以做的最好(np.vectorize可以使迭代更简单,但不能更快)。

我的答案是看一下数组比较,然后从中得出答案。在这种情况下,3参数where可以很好地将布尔数组映射到所需的1/0。还有其他进行此映射的方法。

您的双循环需要增加一层编码,即广播的None

答案 2 :(得分:1)

对于更复杂的示例,或者如果您要处理的数组更大,或者如果您可以写入已经预先分配的数组,则可以考虑使用Numba

示例

import numba as nb
import numpy as np

@nb.njit()
def fun(x, y):
  if x > y:
    return 0
  else:
    return 1

@nb.njit(parallel=False)
#@nb.njit(parallel=True)
def loop(x,y):
  result=np.empty((x.shape[0],y.shape[0]),dtype=np.int32)
  for i in nb.prange(x.shape[0]):
    for j in range(y.shape[0]):
      result[i,j] = fun(x[i], y[j])
  return result

@nb.njit(parallel=False)
def loop_preallocated(x,y,result):
  for i in nb.prange(x.shape[0]):
    for j in range(y.shape[0]):
      result[i,j] = fun(x[i], y[j])
  return result

时间

x = np.array(range(1000))
y = np.array(range(1000))

#Compilation overhead of the first call is neglected

res=np.where(x[:,None]>y,0,1) -> 2.46ms
loop(single_threaded)         -> 1.23ms
loop(parallel)                -> 1.0ms
loop(single_threaded)*        -> 0.27ms
loop(parallel)*               -> 0.058ms

*可能受缓存影响。测试自己的示例。