加快Python中的双循环 [英] Speed up double loop in Python

查看:380
本文介绍了加快Python中的双循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以加快双循环的速度,从而从上一次迭代中更新其值?

Is there a way to speed up a double loop that updates its values from the previous iteration?

在代码中:

def calc(N, m):
    x = 1.0
    y = 2.0
    container = np.zeros((N, 2))
    for i in range(N):
      for j in range(m):
        x=np.random.gamma(3,1.0/(y*y+4))
        y=np.random.normal(1.0/(x+1),1.0/sqrt(x+1))
      container[i, 0] = x
      container[i, 1] = y
    return container

calc(10, 5)

如您所见,内部循环正在更新变量x和y,而外部循环每次都以不同的x值开始.我认为这不是可矢量化的,但也许还有其他可能的改进.

As you can see, the inner loop is updating variables x and y while the outer loop starts with a different value of x each time. I don't think this is vectorizable but maybe there are other possible improvements.

谢谢!

推荐答案

我认为这不会增加任何重要的速度,但是如果您生成所有的伽玛值并且服从正态分布的随机变量,则可以保存一些函数调用值.

I don't think it's going to add up to any important speed up, but you can save some function calls if you generate all your gamma and normally distributed random values at once.

Gamma函数具有缩放属性,因此,如果绘制值来自gamma(k,1)分布,则c*x将是从gamma(k,c)分布得出的值.同样,对于正态分布,您可以采用从正态(0,1)分布中提取的y值,并将其转换为从正态(m,s)分布中进行x*s + m绘制的值.因此,您可以按以下方式重写函数:

Gamma functions have a scaling property, so that if you draw a value x from a gamma(k, 1) distribution, then c*x will be a value drawn from a gamma(k, c) distribution. Similarly, with the normal distribution, you can take a y value drawn from a normal(0, 1) distribution and convert it into a value drawn from a normal(m, s) distribution doing x*s + m. So you can rewrite your function as follows:

def calc(N, m):
    x = 1.0
    y = 2.0
    container = np.zeros((N, 2))
    nm = N*m
    gamma_vals = np.random.gamma(3, 1, size=(nm,))
    norm_vals = np.random.normal(0, 1, size=(nm,))
    for i in xrange(N):
        for j in xrange(m):
            ij = i*j
            x = gamma_vals[ij] / (y*y+4)
            y = norm_vals[ij]/np.sqrt(x+1) + 1/(x+1)
        container[i, 0] = x
        container[i, 1] = y
    return container

如果您的发行版的实际参数具有更简单的表达式,则实际上您可以使用某些精心制作的np.cumprod形式或类似形式,从而避免循环.我不知道这样做的方法...

If the actual parameters of your distributions had a simpler expression, you may actually be able to use some elaborate form of np.cumprod or the like, and spare yourself the loops. I am not able to figure out a way of doing so...

这篇关于加快Python中的双循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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