简体   繁体   English

python numpy优化n维投影

[英]python numpy optimization n-dimensional projection

I am relatively new to python and am interested in any ideas to optimize and speed up this function. 我对python相对较新,并且对任何优化和加速此功能的想法感兴趣。 I have to call it tens~hundreds of thousands of times for a numerical computation I am doing and it takes a major fraction of the code's overall computational time. 对于我正在进行的数值计算,我必须将其称为数十万次,并且它占用了代码总体计算时间的很大一部分。 I have written this in c, but I am interested to see any tricks to make it run faster in python specifically. 我已经用c写了这个,但是我有兴趣看到任何技巧让它在python中运行得更快。

This code calculates a stereographic projection of a bigD-length vector to a littleD-length vector, per http://en.wikipedia.org/wiki/Stereographic_projection . 该代码根据http://en.wikipedia.org/wiki/Stereographic_projection计算bigD长度向量与littleD长度向量的立体投影。 The variable a is a numpy array of length ~ 96. 变量a是一个长度约为96的numpy数组。

import numpy as np 
def nsphere(a):
    bigD = len(a)
    littleD = 3
    temp = a
# normalize before calculating projection
    temp = temp/np.sqrt(np.dot(temp,temp))
# calculate projection
    for i in xrange(bigD-littleD + 2,2,-1 ):
        temp = temp[0:-1]/(1.0 - temp[-1])
    return temp
#USAGE:
q = np.random.rand(96)
b = nsphere(q)
print b

This should be faster: 这应该更快:

def nsphere(a, littleD=3):
    a = a / np.sqrt(np.dot(a, a))
    z = a[littleD:].sum()
    return a[:littleD] / (1. - z)

Please do the math to double check that this is in fact the same as your iterative algorithm. 请进行数学运算以仔细检查这实际上与您的迭代算法相同。

Obviously the main speedup here is going to come from the fact that this is a O(n) algorithm that replaces your O(n**2) algorithm for computing the projection. 显然,这里的主要加速来自于这是一个O(n)算法,它取代了你的O(n ** 2)算法来计算投影。 But specifically to speeding things up in python, you want to "vectorize your inner loop". 但是特别是为了在python中加快速度,你想要“向内化循环”。 Meaning try and avoid loops and anything else that is going to have high python overhead in the most performance critical parts of your code and instead try and use python and numpy builtins which are highly optimized. 意思是尝试并避免循环以及在代码的大多数性能关键部分中具有高python开销的任何其他东西,而是尝试使用高度优化的python和numpy内置函数。 Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM