Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

This code calculates a stereographic projection of a bigD-length vector to a littleD-length vector, per http://en.wikipedia.org/wiki/Stereographic_projection. The variable a is a numpy array of length ~ 96.

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
like image 230
user1850461 Avatar asked Dec 18 '25 02:12

user1850461


1 Answers

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. But specifically to speeding things up in python, you want to "vectorize your inner loop". 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. Hope that helps.

like image 71
Bi Rico Avatar answered Dec 19 '25 15:12

Bi Rico