python - 使用 NumPy 在 Python 中的数组上运行矢量化函数

标签 python arrays numpy

我在 python 中有一个函数,用于对标量输入进行运算,但在此过程中乘以矩阵。具体代码如下所示:

def f(t, n):
    T = np.pi
    a_0 = 0.5

    n = np.arange(1, n + 1)
    # Calculate the Fourier series of f(t)
    a_n = np.sin(n*T) / (n * np.pi)
    b_n = (1 - np.cos(n * T)) / (n * np.pi)
    res = a_0 + np.sum(a_n * np.cos(n*t)) + np.sum(b_n * np.sin(n*t))
    return res

现在,我希望它对输入向量 t 进行操作,并使实现保持向量化(不使用 for 循环)。我可以看到制作维度矩阵 len(t) x n 其中初始向量 n 只是垂直堆叠 len(t) 次,然后与 t 执行元素乘法将是一个解决方案,但是什么是实现此功能的正确方法吗?

最佳答案

这是一种向量化方法,它使用 broadcasting 接受输入向量作为 t和使用 np.dot 矩阵乘法的最后一步的总和减少-

def f_vectorized(t, n): # where t is an array
    t2D = t[:,None]    

    T = np.pi
    a_0 = 0.5

    n = np.arange(1, n + 1)
    a_n = np.sin(n*T) / (n * np.pi)
    b_n = (1 - np.cos(n * T)) / (n * np.pi)

    nt2D = n*t2D
    return a_0 + np.cos(nt2D).dot(a_n) + np.sin(nt2D).dot(b_n)

sample 运行-

In [142]: t
Out[142]: array([8, 1, 8, 0, 2, 7, 8, 8])

In [143]: n = 5

In [144]: f_vectorized(t,n)
Out[144]: 
array([ 1.03254608,  0.94354963,  1.03254608,  0.5       ,  0.95031599,
        1.04127659,  1.03254608,  1.03254608])

关于python - 使用 NumPy 在 Python 中的数组上运行矢量化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42516065/

相关文章:

python - Django 中的非主外键

python - 正则表达式单词匹配

javascript - lodash 按数组的属性数组过滤

javascript - 使用ajax将数组从javascript传递到spring mvc Controller

c++ - 在排序和旋转的数组中搜索

python - 当它应该返回 Series 时应用返回 DataFrame

python - numpy 中的直方图反投影如何工作?

python - 在 pandas 或 numpy 中,我们可以在行上设置一个标志来进行向量化并将其用于下一行计算

python - 如何组合 python 列表并根据第一个元素在列表中创建列表?

python - LSTM MNIST 数据集中的特征和时间步