Chris Joo
Chris Joo

Reputation: 639

Normalize numpy ndarray data

My data is numpy ndarray with shape(2,3,4) following this: I've try to normalize 0-1 scale for each column through sklearn normalization.

from sklearn.preprocessing import normalize  

x = np.array([[[1, 2, 3, 4],
      [2, 2, 3, 4],
      [3, 2, 3, 4]],
      [[4, 2, 3, 4],
      [5, 2, 3, 4],
      [6, 2, 3, 4]]])

x.shape ==> ( 2,3,4) 

x = normalize(x, norm='max', axis=0, ) 

However, I catch the error :

ValueError: Found array with dim 3. the normalize function expected <= 2.

How do I solve this problem?

Thank you.

Upvotes: 2

Views: 3858

Answers (1)

Divakar
Divakar

Reputation: 221504

It seems scikit-learn expects ndarrays with at most two dims. So, to solve it would be to reshape to 2D, feed it to normalize that gives us a 2D array, which could be reshaped back to original shape -

from sklearn.preprocessing import normalize  

normalize(x.reshape(x.shape[0],-1), norm='max', axis=0).reshape(x.shape)

Alternatively, it's much simpler with NumPy that works fine with generic ndarrays -

x/np.linalg.norm(x, ord=np.inf, axis=0, keepdims=True)

Upvotes: 4

Related Questions