根据索引将列表中的函数应用于numpy中的矩阵行

问题描述

我有类似的功能列表:

test_functions = [lambda x: np.sin(x),lambda x: np.sin(x * np.cos(x)),lambda x: np.exp(np.sin(10*x)),lambda x: np.sin(np.exp(np.abs(np.cos(x))))]

我还有一个矩阵[batch_size,channels,sample_len],这样每个样本都代表x axis采样点,例如:

tensor = [[[0,2.5,7]],[[1,3]]]

所以batch_size = 2channels = 1sample_len = 3。该示例本身意味着我想知道x=0,x=2.5 and x=7处的函数值(对于第一个示例)。

生成一个整数(shape=(batch_size,channels)随机矩阵,这样条目就是索引要使用的函数

例如,如果矩阵为: functions_to_be_used = [[0],[2]]

然后我要实现某种索引,该索引将产生:

result = [[[np.sin(0),np.sin(2.5),np.sin(7)]],[np.exp(np.sin(10*1)),np.exp(np.sin(10*2.5)),np.exp(np.sin(10*3))]]]

有些事情(无效):

result = functions[functions_to_be_used](tensor[:,:,:])

出于性能考虑,我不想使用for循环。

解决方法

您需要在行上循环,但可以避免在列上循环。例如:

result = [[test_functions[functions_to_be_used[0][0]](tensor[0][0])],[test_functions[functions_to_be_used[0][1]](tensor[0][1])]]

在跑步之前,您应该始终学会走路,因此,忽略退化的最外层尺寸,我们可以这样做:

result = [[test_functions[functions_to_be_used[0][ii]](tensor[0][ii])] for ii in range(2)]

或者:

result = []
for funcidx,data in zip(functions_to_be_used[0],tensor[0]):
    result.append([test_functions[funcidx](data)])

延伸尺寸作为练习。关键是您将整个数组(行)传递给test_function,而不是一次传递一个标量值。

如果这种方法的性能不足,我建议您使用Numba,它可以通过编译循环代码来大大提高速度。