3D Numpy Array Minmax Normalization

I'd like to MinMax normalize the following 3D numpy array "at 2D-layer level" :

np.array([[[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]],
          [[0, 1, 2],
           [3, 4, 5],
           [6, 7, 10]],
          [[0, 1, 2],
           [3, 4, 5],
           [6, 7, 12]]])

to obtain :

np.array([[[0. , 0.1, 0.2],
           [0.3, 0.4, 0.5],
           [0.6, 0.7, 1. ]],
          [[0. , 0.1, 0.2],
           [0.3, 0.4, 0.5],
           [0.6, 0.7, 1. ]],
          [[0.        , 0.08333333, 0.16666667],
           [0.25      , 0.33333333, 0.41666667],
           [0.5       , 0.58333333, 1.        ]]])

any idea how if could be done without using loops ? Many thanks in advance !

2

2 Answers

One approach is to use .max as follows:

res = arr / arr.max(axis=(1, 2), keepdims=True)
print(res)

Output

[[[0.125      0.125      0.25      ]
  [0.375      0.5        0.625     ]
  [0.75       0.875      1.        ]]

 [[0.         0.1        0.2       ]
  [0.3        0.4        0.5       ]
  [0.6        0.7        1.        ]]

 [[0.         0.08333333 0.16666667]
  [0.25       0.33333333 0.41666667]
  [0.5        0.58333333 1.        ]]]
2

If you define your array as:

x = np.array([[[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]],
          [[0, 1, 2],
           [3, 4, 5],
           [6, 7, 10]],
          [[0, 1, 2],
           [3, 4, 5],
           [6, 7, 12]]])

You can use reshape to flatten the array:

(
    x.reshape(x.shape[-1],x.shape[0]*x.shape[1]).T / 
    np.max(x.reshape(x.shape[2], x.shape[0]*x.shape[1]), axis=1)
).T.reshape(x.shape)

Here the array is flatten to a 2D array where one can take the max of axis=1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest