gpt4 book ai didi

python - Numpy 将函数数组应用于矩阵列的最快方法

转载 作者:行者123 更新时间:2023-12-01 01:38:17 27 4
gpt4 key购买 nike

我有一个形状为(n,)的函数数组和一个形状为(m, n)的numpy矩阵。现在我想将每个函数应用到矩阵中相应的列,即

matrix[:, i] = funcs[i](matrix[:, i])

我可以使用 for 循环来完成此操作(请参见下面的示例),但在 numpy 中通常不鼓励使用 for 循环。我的问题是最快(最好是最优雅)的方法是什么?

一个工作示例

import numpy as np

# Example of functions to apply to each row
funcs = np.array([np.vectorize(lambda x: x+1),
np.vectorize(lambda x: x-2),
np.vectorize(lambda x: x+3)])
# Initialise dummy matrix
matrix = np.random.rand(50, 3)

# Apply each function to each column
for i in range(funcs.shape[0]):
matrix[:, i] = funcs[i](matrix[:, i])

最佳答案

对于具有多行和几列的数组,简单的列迭代应该是有效的:

In [783]: funcs = [lambda x: x+1, lambda x: x+2, lambda x: x+3]
In [784]: arr = np.arange(12).reshape(4,3)
In [785]: for i in range(3):
...: arr[:,i] = funcs[i](arr[:,i])
...:
In [786]: arr
Out[786]:
array([[ 1, 3, 5],
[ 4, 6, 8],
[ 7, 9, 11],
[10, 12, 14]])

如果函数使用一维数组输入,则不需要 np.vectorize (np.vectorize 通常比普通迭代慢。)也适用于像这样的迭代这样就不需要将函数列表包装在数组中。迭代列表的速度更快。

索引迭代的变体:

In [787]: for f, col in zip(funcs, arr.T):
...: col[:] = f(col)
...:
In [788]: arr
Out[788]:
array([[ 2, 5, 8],
[ 5, 8, 11],
[ 8, 11, 14],
[11, 14, 17]])

我在这里使用arr.T,因此迭代是在arr的列上进行的,而不是在行上。

一般观察:对复杂任务进行几次迭代是非常好的 numpy 风格。简单任务的许多迭代速度很慢,应尽可能在编译代码中执行。

关于python - Numpy 将函数数组应用于矩阵列的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52167120/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com