0

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
  • 1
    Is the expected output correct? How did you get 0.2 in the first row? Commented Dec 30, 2022 at 7:46
  • you're right, expected output isn't correct here above, you're one below is the right one, sorry for that Commented Dec 30, 2022 at 10:15

2 Answers 2

2

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.        ]]]
Sign up to request clarification or add additional context in comments.

2 Comments

nice use of axis, I did not know it was possible to use both axis, nice and clean answer.
nice way to do that, thanks, any possibility to do the same but using sklearn MinMaxScaler ?
0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.