Pranay Aryal
Pranay Aryal

Reputation: 5396

normalizing a matrix in numpy

What does np.linalg.norm(x, axis = 1, keepdims=True) return?

I have a matrix np.array([[3.0,4.0],[1, 2]]) . I am trying to normalize each row of the matrix . The answer should be np.array([[0.6,0.8],[0.4472136,0.89442719]]) but I am not able to understand what the code does to get the answer.

Here is the code:

x  = np.array([[3.0,4.0],[1, 2]])
norms = np.linalg.norm(x, axis = 1, keepdims = True)
x /= norms

This code should give the normalized x but I don't understand what np.linalg.norm() is returning here.

Upvotes: 1

Views: 8543

Answers (1)

Pranay Aryal
Pranay Aryal

Reputation: 5396

np.linalg.norm(x, axis = 1, keepdims=True) is doing this in every row (for x):

np.sqrt(3**2 + 4**2) for row 1 of x which gives 5

np.sqrt(1**2 + 2**2) for row 2 of x which gives 2.23

This vector [5, 2.23] is then the norms variable

All values in x are then divided by this norms variable which should give you np.array([[0.6,0.8],[0.4472136,0.89442719]]). I hope this helps

Please also see http://mathworld.wolfram.com/FrobeniusNorm.html

Upvotes: 4

Related Questions