Lud
Lud

Reputation: 67

MinMax scaling on numpy array multiple dimensions

How to minmax normalize in the most efficient way, a XD-numpy array in "columns" of each 2D matrix of the array.

For example with a 3D-array :

a = np.array([[[  0,  10],
        [ 20,  30]],

       [[ 40,  50],
        [ 60,  70]],

       [[ 80,  90],
        [100, 110]]])

into the normalized array :

b = np.array([[[0., 0.],
      [1., 1.]],
     [[0., 0.],
      [1., 1.]],
     [[0., 0.],
      [1., 1.]]])

Upvotes: 3

Views: 923

Answers (3)

MSS
MSS

Reputation: 3623

Broadcasting and simple list comprehension

f= lambda ar:(ar==ar.max(axis=0)[None,:]).astype(int)
b = np.array([f(x) for x in a], dtype=float)
print(b)

This can also be done using numpy.apply_along_axis as follows:

ar = np.array([[[0, 10], [20, 30]], [[40, 50], [60, 70]], [[80, 90], [100, 110]]])

def f(a):
   a = a.reshape(2,2)
   return (a==a.max(axis=0)[None,:]).astype(int)

ar = ar.reshape(3,4)
b = np.apply_along_axis(f, 1, ar)

output

array([[[0., 0.],
        [1., 1.]],

       [[0., 0.],
        [1., 1.]],

       [[0., 0.],
        [1., 1.]]])

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With sklearn.preprocessing.minmax_scale + numpy.apply_along_axis single applying:

from sklearn.preprocessing import minmax_scale

a = np.array([[[0, 10], [20, 30]], [[40, 50], [60, 70]], [[80, 90], [100, 110]]])
a_scaled = np.apply_along_axis(minmax_scale, 1, a)

# a_scaled
[[[0. 0.]
  [1. 1.]]

 [[0. 0.]
  [1. 1.]]

 [[0. 0.]
  [1. 1.]]]

Upvotes: 2

Chrysophylaxs
Chrysophylaxs

Reputation: 6583

a_min = a.min(axis=-2, keepdims=True)
a_max = a.max(axis=-2, keepdims=True)
out = (a - a_min) / (a_max - a_min)

out:

array([[[0., 0.],
        [1., 1.]],

       [[0., 0.],
        [1., 1.]],

       [[0., 0.],
        [1., 1.]]])

Upvotes: 2

Related Questions