Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 627
Lud Avatar asked Jun 06 '26 23:06

Lud


2 Answers

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.]]]
like image 189
RomanPerekhrest Avatar answered Jun 08 '26 12:06

RomanPerekhrest


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.]]])
like image 26
Chrysophylaxs Avatar answered Jun 08 '26 12:06

Chrysophylaxs