SnapBlog

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.

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobm1xZW5%2BdoKObJtmpqWivbp5wKupmrFdoravucCxZKenoqKurbXZmquip54%3D

Mittie Cheatwood

Update: 2024-06-29