Unfortunately the simple solution x/numpy.linalg.norm(x) doesn't work if x is an array of vectors. But with a simple reshape() you can force it into a flat list, use a list comprehension, and use reshape() again to get back the original shape.
s=x.shape
np.array([ v/np.linalg.norm(v) for v in x.reshape(-1, s[-1])]).reshape(s)
First we store the shape of the array
s=x.shape
Then we reshape it into a simple (one-dimensional) array of vectors
x.reshape(-1, s[-1])
by making use of the '-1' argument of reshape() which essentially means "take as many as it needs", e.g . if x was a (4,5,3) array, x.reshape(-1,3) would be of shape (20,3). The use of s[-1] allows for an arbitrary dimension of the vectors.
Then we use a list comprehension to step through the array and calculate the unit vector one vector at a time
[ v/np.linalg.norm(v) for v in x.reshape(-1, s[-1])]
and finally we turn it back into an numpy array and give it back its original shape
np.array([ v/np.linalg.norm(v) for v in x.reshape(-1, s[-1])]).reshape(s)
raisean exception!x/np.linalg.norm(x)was not much slower (about 15-20%) thanx/np.sqrt((x**2).sum())in numpy 1.15.1 on a CPU.