Home > Net >  MinMax scaling on numpy array multiple dimensions
MinMax scaling on numpy array multiple dimensions

Time:12-29

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.]]])

CodePudding user response:

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.]]])

CodePudding user response:

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.]]]

CodePudding user response:

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)

output

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

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

       [[0., 0.],
        [1., 1.]]])
  • Related