在 NumPy 数组的每一行(逐行)上应用函数 [英] Apply function on each row (row-wise) of a NumPy array

查看:46
本文介绍了在 NumPy 数组的每一行(逐行)上应用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有这个功能 -

So, I have the function -

def function(x):
    x , y = vector
    return exp(((-x**2/200))-0.5*(y+0.05*(x**2) - 100*0.05)**2)

假设我想在以下几点对其进行评估(第一列是 x 值,第二列是 y 值) -

and let's say that I would like to evaluate it at the following points (first column are the x-values and second column are the y-values) -

array([[-1.56113514,  4.51759732],
       [-2.80261623,  5.068371  ],
       [ 0.7792729 ,  6.0169462 ],
       [-1.35672858,  3.52517478],
       [-1.92074891,  5.79966161],
       [-2.79340321,  4.73430001],
       [-2.79655868,  5.05361163],
       [-2.13637747,  5.39255837],
       [ 0.17341809,  3.60918261],
       [-1.22712921,  4.95327158]])

即我想传递函数的第一行值并评估,然后是第二行并评估等,然后最终结果将是在这些点评估的值的数组(因此,一个由 10 个值组成的数组).

i.e. I would like to pass the function the first row of values and evaluate, then the second row and evaluate etc. and then the final result would be an array of the values evaluated at these points (so, an array consisting of 10 values).

例如,如果函数是二元正态分布 -

So, for example, if the function was, say, a bivariate normal distribution -

def function2(x):

function2 = (mvnorm.pdf(x,[0,0],[[1,0],[0,1]]))

return function2

我将上面的值传递给这个函数,我会得到 -

and I passed the above values into this function, I would get -

array([  1.17738907e-05,   1.08383957e-04,   1.69855078e-04,
         5.64757613e-06,   1.37432346e-05,   1.44032800e-04,
         1.33426313e-05,   1.97822328e-06,   6.56121709e-08,
         4.67076770e-05])

所以基本上,我正在寻找一种重写函数的方法,以便它可以做到这一点.此外,我想将该函数保留为仅包含一个变量的函数(即仅包含 x 的函数).

So basically, I am looking for a way to rewrite the function so that it can do this. Moreover, I would like to keep the function as a function of one variable only (i.e. only a function of x).

感谢您的帮助!

推荐答案

您可以使用 np.apply_along_axis:

np.apply_along_axis(function, 1, array)

第一个参数是函数,第二个参数是要应用函数的轴.在您的情况下,它是第一个轴.最后一个参数当然是数组.

The first argument is the function, the second argument is the axis along which the function is to be applied. In your case, it is the first axis. The last argument is the array, of course.

但是,应该警告您,apply_along_axis 只是一个方便的功能,而不是灵丹妙药.它有一个严重的速度限制,因为它只是隐藏了一个循环.在可能的情况下,您应该始终尝试矢量化您的计算.这是我的做法:

You should be warned, however, that apply_along_axis is only a convenience function, not a magic bullet. It has a severe speed limitation, since it just hides a loop. You should always try to vectorize your computation, where possible. Here's how I'd do this:

v = array[:, 0] ** 2   # computing just once  
return np.exp((-v / 200) - 0.5 * (array[:, 1] + 0.05 * v - 5) ** 2)

这篇关于在 NumPy 数组的每一行(逐行)上应用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆