hukd321
hukd321

Reputation: 11

Speeding up my calculation by using Vectorization

I'm new to python, so I have some problems with the efficiency of my computation. I'm using this code to fill my H matrix and my h vector (x_tr, x_te and c are lists):

for l in xrange(0, b):
    for ls in xrange(0, b):
        H[l][ls] = 1.0/n_tr * numpy.sum([numpy.exp(-((numpy.linalg.norm(x_tr[i]-c[l])**2 + numpy.linalg.norm(x_tr[i]-c[ls])**2)/(2*s**2))) for i in range(0, n_tr)])
    h[l] = 1.0/n_te * numpy.sum([numpy.exp(-((numpy.linalg.norm(x_te[j]-c[l])**2)/(2*s**2))) for j in range(0, n_te)])

I think it might be inefficient to use 2 loops... Is there any easy way to speed my calculation up? I've been told, that I might use Vectorization, but I somehow don't know how this works

Thanks for your help :)

Upvotes: 1

Views: 235

Answers (1)

Pierre GM
Pierre GM

Reputation: 20339

Example of vectorization:

>>> x_te = np.arange(10)
>>> c = np.range(5)
>>> (x_te[:,None] - c).sum(axis=0)
array([45, 35, 25, 15,  5])

is equivalent to:

np.array([np.sum(xte[i]-c[j] for i in range(xte.size)) for j in range(c.size)])

That said:

as x_te[j] and c[l] are two scalars in your loops, your np.linalg.norm(x[j]-c[i])**2 is just (x[j]-c[i]), right ? So your h could be calculated as

h = 1.0/n_te * numpy.sum([numpy.exp(-(x_te[: None]-c))/(2*s**2))) 

Which should get you started for H...

EDIT You should probably check some documentation on broadcasting.

Upvotes: 1

Related Questions