Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient standard basis vector with numpy

Tags:

python

numpy

Given an index and a size, is there a more efficient way to produce the standard basis vector:

import numpy as np
np.array([1.0 if i == index else 0.0 for i in range(size)])
like image 809
Neil G Avatar asked Aug 15 '12 18:08

Neil G


People also ask

Are Numpy arrays efficient?

As array size gets close to 5,000,000, Numpy gets around 120 times faster. As the array size increases, Numpy is able to execute more parallel operations and making computation faster.

What does .all do in Numpy?

all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.

What does Linalg mean in Python?

linalg. norm() of Python library Numpy. This function returns one of the seven matrix norms or one of the infinite vector norms depending upon the value of its parameters.


2 Answers

In [2]: import numpy as np

In [9]: size = 5

In [10]: index = 2

In [11]: np.eye(1,size,index)
Out[11]: array([[ 0.,  0.,  1.,  0.,  0.]])

Hm, unfortunately, using np.eye for this is rather slow:

In [12]: %timeit np.eye(1,size,index)
100000 loops, best of 3: 7.68 us per loop

In [13]: %timeit a = np.zeros(size); a[index] = 1.0
1000000 loops, best of 3: 1.53 us per loop

Wrapping np.zeros(size); a[index] = 1.0 in a function makes only a modest difference, and is still much faster than np.eye:

In [24]: def f(size, index):
   ....:     arr = np.zeros(size)
   ....:     arr[index] = 1.0
   ....:     return arr
   ....: 

In [27]: %timeit f(size, index)
1000000 loops, best of 3: 1.79 us per loop
like image 120
unutbu Avatar answered Sep 21 '22 13:09

unutbu


x = np.zeros(size)
x[index] = 1.0

at least i think thats it...

>>> t = timeit.Timer('np.array([1.0 if i == index else 0.0 for i in range(size)]
)','import numpy as np;size=10000;index=5123')
>>> t.timeit(10)
0.039461429317952934  #original method
>>> t = timeit.Timer('x=np.zeros(size);x[index]=1.0','import numpy as np;size=10000;index=5123')
>>> t.timeit(10)
9.4077963240124518e-05 #zeros method
>>> t = timeit.Timer('x=np.eye(1.0,size,index)','import numpy as np;size=10000;index=5123')
>>> t.timeit(10)
0.0001398340635319073 #eye method

looks like np.zeros is fastest...

like image 25
Joran Beasley Avatar answered Sep 19 '22 13:09

Joran Beasley