Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 30th, 2012  |  syntax: None  |  size: 0.71 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to apply numpy.linalg.norm to each row of a matrix?
  2. np.sum(np.abs(x)**2,axis=-1)**(1./2)
  3.        
  4. In [48]: %timeit np.apply_along_axis(np.linalg.norm, 1, x)
  5. 1000 loops, best of 3: 208 us per loop
  6.  
  7. In [49]: %timeit np.sum(np.abs(x)**2,axis=-1)**(1./2)
  8. 100000 loops, best of 3: 18.3 us per loop
  9.        
  10. In [55]: %timeit np.apply_along_axis(lambda row:np.linalg.norm(row,ord=1), 1, x)
  11. 1000 loops, best of 3: 203 us per loop
  12.  
  13. In [54]: %timeit np.sum(abs(x), axis=-1)
  14. 100000 loops, best of 3: 10.9 us per loop
  15.        
  16. In [16]: numpy.apply_along_axis(numpy.linalg.norm, 1, a)
  17. Out[16]: array([ 5.38516481,  1.41421356,  5.38516481])
  18.        
  19. In [22]: numpy.apply_along_axis(lambda row:numpy.linalg.norm(row,ord=1), 1, a)
  20. Out[22]: array([9, 2, 9])