Need help vectorizing code

Peter Otten __peter__ at web.de
Sat Jan 18 16:50:00 EST 2014


Kevin K wrote:

> I have some code that I need help vectorizing.
> I want to convert the following to vector form, how can I? I want to get
> rid of the inner loop - apparently, it's possible to do so. X is an NxD
> matrix. y is a 1xD vector.
> 
> def foo(X, y, mylambda, N, D, epsilon):
> ...
>         for j in xrange(D):
>             aj = 0
>             cj = 0
>             for i in xrange(N):
>                 aj += 2 * (X[i,j] ** 2)
>                 cj += 2 * (X[i,j] * (y[i] - w.transpose()*X[i].transpose()
>                 + w[j]*X[i,j]))
> 
> ...
> 
> If I call numpy.vectorize() on the function, it throws an error at
> runtime.

Maybe 

a = (2*X**2).sum(axis=0)
c = no idea.

Judging from the code y should be 1xN rather than 1xD. Also, should

w.transpose()*X[i].transpose()

be a vector or a scalar? If the latter, did you mean

numpy.dot(w, X[i])

?




More information about the Python-list mailing list