我需要矢量化以下的代码才能运行

2024-10-03 23:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

这一部分我能够矢量化并摆脱嵌套循环。你知道吗

def EMalgofast(obsdata, beta, pjt):
     n = np.shape(obsdata)[0]
     g = np.shape(pjt)[0]
     zijtpo = np.zeros(shape=(n,g))
     for j in range(g):
         zijtpo[:,j] = pjt[j]*stats.expon.pdf(obsdata,scale=beta[j])

     zijdenom = np.sum(zijtpo, axis=1)
     zijtpo = zijtpo/np.reshape(zijdenom, (n,1))

     pjtpo = np.mean(zijtpo, axis=0)

我无法矢量化下面的部分。我需要弄清楚

     betajtpo_1 = []
     for j in range(g):
         num = 0
         denom = 0
         for i in range(n):
             num = num + zijtpo[i][j]*obsdata[i]
             denom = denom + zijtpo[i][j]
         betajtpo_1.append(num/denom)

     betajtpo = np.asarray(betajtpo_1)

     return(pjtpo,betajtpo)

Tags: infornprange矢量化numbetashape
1条回答
网友
1楼 · 发布于 2024-10-03 23:24:12

根据我所见,我猜Python不是你的第一种编程语言。我之所以这么说,是因为在python中,通常我们不必处理操纵索引的问题。您可以直接对返回的值或键执行操作。千万不要把这个当成冒犯,我也一样,C++来自我自己。这是一个很难改掉的习惯。你知道吗

如果您对性能感兴趣,Raymond Hettinger提供了一个很好的演示,介绍了如何在Python中优化和优化: https://www.youtube.com/watch?v=OSGv2VnC0go

至于你需要帮助的代码,这对你有帮助吗?不幸的是,我还没有经过测试,因为我需要离开。。。 裁判: Iterating over a numpy array

http://docs.scipy.org/doc/numpy/reference/generated/numpy.true_divide.html

 def EMalgofast(obsdata, beta, pjt):
     n = np.shape(obsdata)[0]
     g = np.shape(pjt)[0]
     zijtpo = np.zeros(shape=(n,g))
     for j in range(g):
         zijtpo[:,j] = pjt[j]*stats.expon.pdf(obsdata,scale=beta[j])

     zijdenom = np.sum(zijtpo, axis=1)
     zijtpo = zijtpo/np.reshape(zijdenom, (n,1))

     pjtpo = np.mean(zijtpo, axis=0)
     betajtpo_1 = []

     #manipulating an array of numerator and denominator instead of creating objects each iteration
     num=np.zeros(shape=(g,1))
     denom=np.zeros(shape=(g,1))
     #generating the num and denom real value for the end result
     for (x,y), value in numpy.ndenumerate(zijtpo):
         num[x],denom[x] = num[x] + value *obsdata[y],denom[x] + value 

     #dividing all at once after instead of inside the loop
     betajtpo_1= np.true_divide(num/denom)

     betajtpo = np.asarray(betajtpo_1)

     return(pjtpo,betajtpo)

请给我一些反馈!你知道吗

谨致问候

埃里克·拉方丹

相关问题 更多 >