在Python中建立三维阵列,以取代优化循环 [英] Building 3D arrays in Python to replace loops for optimization

查看:176
本文介绍了在Python中建立三维阵列,以取代优化循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更好地了解蟒蛇的优化,所以这是一个虚拟的情况,但希望勾勒我的想法......

I'm trying to better understand python optimization so this is a dummy case, but hopefully outlines my idea...

说我有一个函数,它接受两个变量:

Say I have a function which takes two variables:

def func(param1, param2):
    return some_func(param1) + some_const*(param2/2)

和我有参数1和参数(不同长度的)阵列,在此我要进行评估的功能,(some_func是参数1的任意功能)例如。

and I have arrays for param1 and param2 (of different lengths), at which I want the function to be evaluated, (some_func is an arbitrary function of param1) e.g.

param1 = np.array((1,2,3,4,5))
param2 = np.array((5,2,3,1,9, 9, 10))

我可以通过做评估对所有参数空间:

I can evaluate over all parameter space by doing:

result = []
for p in param1:
    result.append(func(p, param2))
result = np.asarray(result)

然而,在Python环比数组操作慢。因此,我不知道有没有办法实现了三维数组,它包含两个参数1和参数数组FUNC的所有值的结果?

However, loops in Python are slower than array operations. Therefore, I wonder is there a way to achieve a 3D array which contains the results of func for all values in both param1 and param2 arrays?

推荐答案

您例如:

In [198]: result=[]
In [199]: for p in param1:
   .....:     result.append(p+3*(param2/2))
In [200]: result=np.array(result)

同样的结果通过广播(和 np.newaxis

In [197]: param1[:,None] + 3*(param2[None,:]/2)
Out[197]: 
array([[ 7,  4,  4,  1, 13, 13, 16],
       [ 8,  5,  5,  2, 14, 14, 17],
       [ 9,  6,  6,  3, 15, 15, 18],
       [10,  7,  7,  4, 16, 16, 19],
       [11,  8,  8,  5, 17, 17, 20]])

some_func 的细节将决定是否使用 some_func(参数1 [:,无]) some_func(参数1):,无]

Details of some_func would determine whether you use some_func(param1[:,None]) or some_func(param1)[:,None].

这篇关于在Python中建立三维阵列,以取代优化循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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