【问题标题】:Applying a function from a list according to indexing to rows of a matrix in numpy根据索引将列表中的函数应用于numpy中的矩阵行
【发布时间】:2020-08-14 11:35:39
【问题描述】:

我有一个这样的函数列表:

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, 2.5, 3]]]

所以batch_size = 2、channels = 1 和sample_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 循环。

【问题讨论】:

    标签: python-3.x numpy indexing data-science


    【解决方案1】:

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

    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,通过编译循环代码可能会加快速度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 2021-06-29
      • 2011-12-26
      • 2015-05-08
      • 1970-01-01
      • 2022-08-19
      • 2014-11-27
      相关资源
      最近更新 更多