0

For example, to normalize each row in a 2-dimensional vector such that the magnitude of a row is one:

import numpy as np

a = np.arange(0,27,3).reshape(3,3)

result = a / norm_of_rows( a )

Such that:

np.sum( result**2, axis=-1 )
# array([ 1.,  1.,  1.]) 

The original question, How to normalize a 2-dimensional numpy array in python less verbose?, which people feel my question is a duplicate of, the author actually asks how to make the elements of each row sum to one. This is different than normalizing each row such that its magnitude is one (the sum of the square of each element equals one).

Community
  • 1
  • 1
walt
  • 71
  • 1
  • 3
  • 1
    duplicate of http://stackoverflow.com/q/8904694/1461210 – ali_m May 11 '14 at 02:01
  • I asked this question because – walt May 12 '14 at 15:25
  • It would have been helpful to make the difference clearer from the title and original description. At any rate, the answer is almost identical. You already have `np.sum( result**2, axis=-1 )`, which is what you want to equal to 1 for each row. You just need to remember to take the square root before dividing (remember that you are summing over the rows of `result**2` rather than `result`). So an answer might look like: `result_norm = result / np.sqrt(np.sum(result**2, axis=-1))[:, None]` (note the broadcasting over rows using `[:, None]`). – ali_m May 12 '14 at 20:53
  • Also, in versions of numpy > 1.9, `np.linalg.norm` accepts an `axis=` argument. Since you essentially want to make the euclidean norm of each row equal to 1, with recent versions you could just do `result_norm = result / np.linalg.norm(result, ord=2, axis=-1)[:, None]`. – ali_m May 12 '14 at 20:59

1 Answers1

0

np.max(a[0,:]) will give you the maximum of the 1st row, np.max(a[1,:]) will give you the maximum of the 2nd row

To normalize the whole matrix just loop through your rows and divide each element by the corresponding max_row

Sleepyhead
  • 1,009
  • 1
  • 10
  • 27
  • 2
    Consider `np.max(a, axis=1)` and `a / np.max(a, axis=1)[:,None]`. For most operations you should not be looping through numpy arrays with python. – Daniel May 11 '14 at 02:00