8

I am using Python 3 within Pyzo. Please could you tell me why the linalg.norm function does not recognise the axis argument.

This code:

c = np.array([[ 1, 2, 3],[-1, 1, 4]])
d=linalg.norm(c, axis=1)

returns the error:

TypeError: norm() got an unexpected keyword argument 'axis'

Thomas Hopkins
  • 671
  • 2
  • 10
  • 20
  • 5
    The `axis` argument was added in version 1.8 of numpy; see http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html. What version are you using? – Warren Weckesser Nov 23 '13 at 23:43

2 Answers2

11

linalg.norm does not accept an axis argument. You can get around that with:

np.apply_along_axis(np.linalg.norm, 1, c)
# array([ 3.74165739,  4.24264069])

Or to be faster, implement it yourself with:

np.sqrt(np.einsum('ij,ij->i',c,c))
# array([ 3.74165739,  4.24264069])

For timing:

timeit np.apply_along_axis(np.linalg.norm, 1, c)
10000 loops, best of 3: 170 µs per loop

timeit np.sqrt(np.einsum('ij,ij->i',c,c))
100000 loops, best of 3: 10.7 µs per loop
askewchan
  • 45,161
  • 17
  • 118
  • 134
5

On numpy versions below 1.8 linalg.norm does not take axis argument, you can use np.apply_along_axis to get your desired outcome, as pointed out by Warren Weckesser in the comment to the question.

import numpy as np
from numpy import linalg

c = np.array([[ 1, 2, 3],[-1, 1, 4]])

d = np.apply_along_axis(linalg.norm, 1, c)

Result:

>>> d
array([ 3.74165739,  4.24264069])
Akavall
  • 82,592
  • 51
  • 207
  • 251
  • Don't know about the downvoter, but this worked for me! Small correction: you need np.linalg in your example code above. Thanks especially for comment about it not working below v1.8. – GnomeDePlume Mar 05 '14 at 17:36
  • @GnomeDePlume, Thanks. In my code I import `linalg` separately, so my code works as it is. Of course, it might more elegant to import just `numpy`. – Akavall Mar 05 '14 at 18:19
  • Oops, I'd overlooked that! Correction redacted :) – GnomeDePlume Mar 05 '14 at 20:52