简体   繁体   中英

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 !

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM